Merge pull request #72178 from dims/remove-ovirt-photon-cloudstack-cloud-providers

Remove ovirt/cloudstack/photon cloud providers
This commit is contained in:
Kubernetes Prow Robot 2019-06-13 19:12:19 -07:00 committed by GitHub
commit c6bc1639c3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
155 changed files with 0 additions and 83744 deletions

687
Godeps/LICENSES generated
View File

@ -3932,402 +3932,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
================================================================================
================================================================================
= vendor/github.com/d2g/dhcp4 licensed under: =
Copyright (c) 2013 Skagerrak Software Limited. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Skagerrak Software Limited nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
= vendor/github.com/d2g/dhcp4/LICENSE 0187683301a45e8ea393bb2ffd7889c8
================================================================================
================================================================================
= vendor/github.com/d2g/dhcp4client licensed under: =
Mozilla Public License, version 2.0
1. Definitions
1.1. “Contributor”
means each individual or legal entity that creates, contributes to the
creation of, or owns Covered Software.
1.2. “Contributor Version”
means the combination of the Contributions of others (if any) used by a
Contributor and that particular Contributors Contribution.
1.3. “Contribution”
means Covered Software of a particular Contributor.
1.4. “Covered Software”
means Source Code Form to which the initial Contributor has attached the
notice in Exhibit A, the Executable Form of such Source Code Form, and
Modifications of such Source Code Form, in each case including portions
thereof.
1.5. “Incompatible With Secondary Licenses”
means
a. that the initial Contributor has attached the notice described in
Exhibit B to the Covered Software; or
b. that the Covered Software was made available under the terms of version
1.1 or earlier of the License, but not also under the terms of a
Secondary License.
1.6. “Executable Form”
means any form of the work other than Source Code Form.
1.7. “Larger Work”
means a work that combines Covered Software with other material, in a separate
file or files, that is not Covered Software.
1.8. “License”
means this document.
1.9. “Licensable”
means having the right to grant, to the maximum extent possible, whether at the
time of the initial grant or subsequently, any and all of the rights conveyed by
this License.
1.10. “Modifications”
means any of the following:
a. any file in Source Code Form that results from an addition to, deletion
from, or modification of the contents of Covered Software; or
b. any new file in Source Code Form that contains any Covered Software.
1.11. “Patent Claims” of a Contributor
means any patent claim(s), including without limitation, method, process,
and apparatus claims, in any patent Licensable by such Contributor that
would be infringed, but for the grant of the License, by the making,
using, selling, offering for sale, having made, import, or transfer of
either its Contributions or its Contributor Version.
1.12. “Secondary License”
means either the GNU General Public License, Version 2.0, the GNU Lesser
General Public License, Version 2.1, the GNU Affero General Public
License, Version 3.0, or any later versions of those licenses.
1.13. “Source Code Form”
means the form of the work preferred for making modifications.
1.14. “You” (or “Your”)
means an individual or a legal entity exercising rights under this
License. For legal entities, “You” includes any entity that controls, is
controlled by, or is under common control with You. For purposes of this
definition, “control” means (a) the power, direct or indirect, to cause
the direction or management of such entity, whether by contract or
otherwise, or (b) ownership of more than fifty percent (50%) of the
outstanding shares or beneficial ownership of such entity.
2. License Grants and Conditions
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
a. under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or as
part of a Larger Work; and
b. under Patent Claims of such Contributor to make, use, sell, offer for
sale, have made, import, and otherwise transfer either its Contributions
or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution become
effective for each Contribution on the date the Contributor first distributes
such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under this
License. No additional rights or licenses will be implied from the distribution
or licensing of Covered Software under this License. Notwithstanding Section
2.1(b) above, no patent license is granted by a Contributor:
a. for any code that a Contributor has removed from Covered Software; or
b. for infringements caused by: (i) Your and any other third partys
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
c. under Patent Claims infringed by Covered Software in the absence of its
Contributions.
This License does not grant any rights in the trademarks, service marks, or
logos of any Contributor (except as may be necessary to comply with the
notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this License
(see Section 10.2) or under the terms of a Secondary License (if permitted
under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its Contributions
are its original creation(s) or it has sufficient rights to grant the
rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under applicable
copyright doctrines of fair use, fair dealing, or other equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in
Section 2.1.
3. Responsibilities
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under the
terms of this License. You must inform recipients that the Source Code Form
of the Covered Software is governed by the terms of this License, and how
they can obtain a copy of this License. You may not attempt to alter or
restrict the recipients rights in the Source Code Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
a. such Covered Software must also be made available in Source Code Form,
as described in Section 3.1, and You must inform recipients of the
Executable Form how they can obtain a copy of such Source Code Form by
reasonable means in a timely manner, at a charge no more than the cost
of distribution to the recipient; and
b. You may distribute such Executable Form under the terms of this License,
or sublicense it under different terms, provided that the license for
the Executable Form does not attempt to limit or alter the recipients
rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for the
Covered Software. If the Larger Work is a combination of Covered Software
with a work governed by one or more Secondary Licenses, and the Covered
Software is not Incompatible With Secondary Licenses, this License permits
You to additionally distribute such Covered Software under the terms of
such Secondary License(s), so that the recipient of the Larger Work may, at
their option, further distribute the Covered Software under the terms of
either this License or such Secondary License(s).
3.4. Notices
You may not remove or alter the substance of any license notices (including
copyright notices, patent notices, disclaimers of warranty, or limitations
of liability) contained within the Source Code Form of the Covered
Software, except that You may alter any license notices to the extent
required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on behalf
of any Contributor. You must make it absolutely clear that any such
warranty, support, indemnity, or liability obligation is offered by You
alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
If it is impossible for You to comply with any of the terms of this License
with respect to some or all of the Covered Software due to statute, judicial
order, or regulation then You must: (a) comply with the terms of this License
to the maximum extent possible; and (b) describe the limitations and the code
they affect. Such description must be placed in a text file included with all
distributions of the Covered Software under this License. Except to the
extent prohibited by statute or regulation, such description must be
sufficiently detailed for a recipient of ordinary skill to be able to
understand it.
5. Termination
5.1. The rights granted under this License will terminate automatically if You
fail to comply with any of its terms. However, if You become compliant,
then the rights granted under this License from a particular Contributor
are reinstated (a) provisionally, unless and until such Contributor
explicitly and finally terminates Your grants, and (b) on an ongoing basis,
if such Contributor fails to notify You of the non-compliance by some
reasonable means prior to 60 days after You have come back into compliance.
Moreover, Your grants from a particular Contributor are reinstated on an
ongoing basis if such Contributor notifies You of the non-compliance by
some reasonable means, this is the first time You have received notice of
non-compliance with this License from such Contributor, and You become
compliant prior to 30 days after Your receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions, counter-claims,
and cross-claims) alleging that a Contributor Version directly or
indirectly infringes any patent, then the rights granted to You by any and
all Contributors for the Covered Software under Section 2.1 of this License
shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user
license agreements (excluding distributors and resellers) which have been
validly granted by You or Your distributors under this License prior to
termination shall survive termination.
6. Disclaimer of Warranty
Covered Software is provided under this License on an “as is” basis, without
warranty of any kind, either expressed, implied, or statutory, including,
without limitation, warranties that the Covered Software is free of defects,
merchantable, fit for a particular purpose or non-infringing. The entire
risk as to the quality and performance of the Covered Software is with You.
Should any Covered Software prove defective in any respect, You (not any
Contributor) assume the cost of any necessary servicing, repair, or
correction. This disclaimer of warranty constitutes an essential part of this
License. No use of any Covered Software is authorized under this License
except under this disclaimer.
7. Limitation of Liability
Under no circumstances and under no legal theory, whether tort (including
negligence), contract, or otherwise, shall any Contributor, or anyone who
distributes Covered Software as permitted above, be liable to You for any
direct, indirect, special, incidental, or consequential damages of any
character including, without limitation, damages for lost profits, loss of
goodwill, work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses, even if such party shall have been
informed of the possibility of such damages. This limitation of liability
shall not apply to liability for death or personal injury resulting from such
partys negligence to the extent applicable law prohibits such limitation.
Some jurisdictions do not allow the exclusion or limitation of incidental or
consequential damages, so this exclusion and limitation may not apply to You.
8. Litigation
Any litigation relating to this License may be brought only in the courts of
a jurisdiction where the defendant maintains its principal place of business
and such litigation shall be governed by laws of that jurisdiction, without
reference to its conflict-of-law provisions. Nothing in this Section shall
prevent a partys ability to bring cross-claims or counter-claims.
9. Miscellaneous
This License represents the complete agreement concerning the subject matter
hereof. If any provision of this License is held to be unenforceable, such
provision shall be reformed only to the extent necessary to make it
enforceable. Any law or regulation which provides that the language of a
contract shall be construed against the drafter shall not be used to construe
this License against a Contributor.
10. Versions of the License
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version of
the License under which You originally received the Covered Software, or
under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a modified
version of this License if you rename the license and remove any
references to the name of the license steward (except to note that such
modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
Exhibit A - Source Code Form License Notice
This Source Code Form is subject to the
terms of the Mozilla Public License, v.
2.0. If a copy of the MPL was not
distributed with this file, You can
obtain one at
http://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular file, then
You may include the notice in a location (such as a LICENSE file in a relevant
directory) where a recipient would be likely to look for such a notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - “Incompatible With Secondary Licenses” Notice
This Source Code Form is “Incompatible
With Secondary Licenses”, as defined by
the Mozilla Public License, v. 2.0.
= vendor/github.com/d2g/dhcp4client/LICENSE b278a92d2c1509760384428817710378
================================================================================
================================================================================
= vendor/github.com/davecgh/go-spew licensed under: =
@ -18390,297 +17994,6 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI
================================================================================
================================================================================
= vendor/github.com/vmware/photon-controller-go-sdk licensed under: =
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.
= vendor/github.com/vmware/photon-controller-go-sdk/LICENSE 0de60303c844eac44e45012dac1987de
================================================================================
================================================================================
= vendor/github.com/xanzy/go-cloudstack licensed under: =
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.
= vendor/github.com/xanzy/go-cloudstack/LICENSE 136e4f49dbf29942c572a3a8f6e88a77
================================================================================
================================================================================
= vendor/github.com/xiang90/probing licensed under: =

View File

@ -100,7 +100,6 @@ go_library(
"//pkg/volume/iscsi:go_default_library",
"//pkg/volume/local:go_default_library",
"//pkg/volume/nfs:go_default_library",
"//pkg/volume/photon_pd:go_default_library",
"//pkg/volume/portworx:go_default_library",
"//pkg/volume/quobyte:go_default_library",
"//pkg/volume/rbd:go_default_library",

View File

@ -45,7 +45,6 @@ import (
"k8s.io/kubernetes/pkg/volume/iscsi"
"k8s.io/kubernetes/pkg/volume/local"
"k8s.io/kubernetes/pkg/volume/nfs"
"k8s.io/kubernetes/pkg/volume/photon_pd"
"k8s.io/kubernetes/pkg/volume/portworx"
"k8s.io/kubernetes/pkg/volume/quobyte"
"k8s.io/kubernetes/pkg/volume/rbd"
@ -73,7 +72,6 @@ func ProbeAttachableVolumePlugins() []volume.VolumePlugin {
allPlugins = append(allPlugins, portworx.ProbeVolumePlugins()...)
allPlugins = append(allPlugins, vsphere_volume.ProbeVolumePlugins()...)
allPlugins = append(allPlugins, azure_dd.ProbeVolumePlugins()...)
allPlugins = append(allPlugins, photon_pd.ProbeVolumePlugins()...)
allPlugins = append(allPlugins, scaleio.ProbeVolumePlugins()...)
allPlugins = append(allPlugins, storageos.ProbeVolumePlugins()...)
allPlugins = append(allPlugins, fc.ProbeVolumePlugins()...)
@ -105,7 +103,6 @@ func ProbeExpandableVolumePlugins(config persistentvolumeconfig.VolumeConfigurat
allPlugins = append(allPlugins, rbd.ProbeVolumePlugins()...)
allPlugins = append(allPlugins, azure_dd.ProbeVolumePlugins()...)
allPlugins = append(allPlugins, azure_file.ProbeVolumePlugins()...)
allPlugins = append(allPlugins, photon_pd.ProbeVolumePlugins()...)
allPlugins = append(allPlugins, scaleio.ProbeVolumePlugins()...)
allPlugins = append(allPlugins, storageos.ProbeVolumePlugins()...)
allPlugins = append(allPlugins, fc.ProbeVolumePlugins()...)
@ -164,7 +161,6 @@ func ProbeControllerVolumePlugins(cloud cloudprovider.Interface, config persiste
allPlugins = append(allPlugins, cinder.ProbeVolumePlugins()...)
allPlugins = append(allPlugins, vsphere_volume.ProbeVolumePlugins()...)
allPlugins = append(allPlugins, azure_dd.ProbeVolumePlugins()...)
allPlugins = append(allPlugins, photon_pd.ProbeVolumePlugins()...)
if utilfeature.DefaultFeatureGate.Enabled(features.CSIInlineVolume) {
allPlugins = append(allPlugins, csi.ProbeVolumePlugins()...)

View File

@ -95,12 +95,9 @@
"k8s.io/kubernetes/pkg/cloudprovider/providers",
"k8s.io/kubernetes/pkg/cloudprovider/providers/aws",
"k8s.io/kubernetes/pkg/cloudprovider/providers/azure",
"k8s.io/kubernetes/pkg/cloudprovider/providers/cloudstack",
"k8s.io/kubernetes/pkg/cloudprovider/providers/fake",
"k8s.io/kubernetes/pkg/cloudprovider/providers/gce",
"k8s.io/kubernetes/pkg/cloudprovider/providers/openstack",
"k8s.io/kubernetes/pkg/cloudprovider/providers/ovirt",
"k8s.io/kubernetes/pkg/cloudprovider/providers/photon",
"k8s.io/kubernetes/pkg/cloudprovider/providers/vsphere",
"k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset"
]

View File

@ -99,7 +99,6 @@ go_library(
"//pkg/volume/iscsi:go_default_library",
"//pkg/volume/local:go_default_library",
"//pkg/volume/nfs:go_default_library",
"//pkg/volume/photon_pd:go_default_library",
"//pkg/volume/portworx:go_default_library",
"//pkg/volume/projected:go_default_library",
"//pkg/volume/quobyte:go_default_library",

View File

@ -44,7 +44,6 @@ import (
"k8s.io/kubernetes/pkg/volume/iscsi"
"k8s.io/kubernetes/pkg/volume/local"
"k8s.io/kubernetes/pkg/volume/nfs"
"k8s.io/kubernetes/pkg/volume/photon_pd"
"k8s.io/kubernetes/pkg/volume/portworx"
"k8s.io/kubernetes/pkg/volume/projected"
"k8s.io/kubernetes/pkg/volume/quobyte"
@ -90,7 +89,6 @@ func ProbeVolumePlugins() []volume.VolumePlugin {
allPlugins = append(allPlugins, configmap.ProbeVolumePlugins()...)
allPlugins = append(allPlugins, vsphere_volume.ProbeVolumePlugins()...)
allPlugins = append(allPlugins, azure_dd.ProbeVolumePlugins()...)
allPlugins = append(allPlugins, photon_pd.ProbeVolumePlugins()...)
allPlugins = append(allPlugins, projected.ProbeVolumePlugins()...)
allPlugins = append(allPlugins, portworx.ProbeVolumePlugins()...)
allPlugins = append(allPlugins, scaleio.ProbeVolumePlugins()...)

4
go.mod
View File

@ -43,8 +43,6 @@ require (
github.com/coreos/rkt v1.30.0 // indirect
github.com/cpuguy83/go-md2man v1.0.4
github.com/cyphar/filepath-securejoin v0.0.0-20170720062807-ae69057f2299 // indirect
github.com/d2g/dhcp4 v0.0.0-20170904100407-a1d1b6c41b1c
github.com/d2g/dhcp4client v0.0.0-20170829104524-6e570ed0a266
github.com/davecgh/go-spew v1.1.1
github.com/daviddengcn/go-colortext v0.0.0-20160507010035-511bcaf42ccd
github.com/docker/distribution v0.0.0-20170726174610-edc3ab29cdff
@ -148,8 +146,6 @@ require (
github.com/vishvananda/netlink v0.0.0-20171020171820-b2de5d10e38e
github.com/vishvananda/netns v0.0.0-20171111001504-be1fbeda1936 // indirect
github.com/vmware/govmomi v0.20.1
github.com/vmware/photon-controller-go-sdk v0.0.0-20170310013346-4a435daef6cc
github.com/xanzy/go-cloudstack v0.0.0-20160728180336-1e2cbf647e57
github.com/xlab/handysort v0.0.0-20150421192137-fb3537ed64a1 // indirect
golang.org/x/crypto v0.0.0-20181025213731-e84da0312774
golang.org/x/lint v0.0.0-20181217174547-8f45f776aaf1

8
go.sum
View File

@ -89,10 +89,6 @@ github.com/cpuguy83/go-md2man v1.0.4 h1:OwjhDpK9YGCcI5CDf8HcdfsXqr6znFyAJfuZ27ix
github.com/cpuguy83/go-md2man v1.0.4/go.mod h1:N6JayAiVKtlHSnuTCeuLSQVs75hb8q+dYQLjr7cDsKY=
github.com/cyphar/filepath-securejoin v0.0.0-20170720062807-ae69057f2299 h1:2pOMM/RaFhI52FyCITl8aTf5HZ9LoHD8SkjbghAEG1E=
github.com/cyphar/filepath-securejoin v0.0.0-20170720062807-ae69057f2299/go.mod h1:FpkQEhXnPnOthhzymB7CGsFk2G9VLXONKD9G7QGMM+4=
github.com/d2g/dhcp4 v0.0.0-20170904100407-a1d1b6c41b1c h1:Xo2rK1pzOm0jO6abTPIQwbAmqBIOj132otexc1mmzFc=
github.com/d2g/dhcp4 v0.0.0-20170904100407-a1d1b6c41b1c/go.mod h1:Ct2BUK8SB0YC1SMSibvLzxjeJLnrYEVLULFNiHY9YfQ=
github.com/d2g/dhcp4client v0.0.0-20170829104524-6e570ed0a266 h1:1iKpuOrCnaRBKKNoChzmVDXeoFuCS7wsooRncvzVPxo=
github.com/d2g/dhcp4client v0.0.0-20170829104524-6e570ed0a266/go.mod h1:j0hNfjhrt2SxUOw55nL0ATM/z4Yt3t2Kd1mW34z5W5s=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/daviddengcn/go-colortext v0.0.0-20160507010035-511bcaf42ccd h1:uVsMphB1eRx7xB1njzL3fuMdWRN8HtVzoUOItHMwv5c=
@ -388,10 +384,6 @@ github.com/vishvananda/netns v0.0.0-20171111001504-be1fbeda1936 h1:J9gO8RJCAFlln
github.com/vishvananda/netns v0.0.0-20171111001504-be1fbeda1936/go.mod h1:ZjcWmFBXmLKZu9Nxj3WKYEafiSqer2rnvPr0en9UNpI=
github.com/vmware/govmomi v0.20.1 h1:7b/SeTUB3tER8ZLGLLLH3xcnB2xeuLULXmfPFqPSRZA=
github.com/vmware/govmomi v0.20.1/go.mod h1:URlwyTFZX72RmxtxuaFL2Uj3fD1JTvZdx59bHWk6aFU=
github.com/vmware/photon-controller-go-sdk v0.0.0-20170310013346-4a435daef6cc h1:uyYiBHCUWsifUdIWrBzUUq9B3FSZKFTAuUyMQczS1q8=
github.com/vmware/photon-controller-go-sdk v0.0.0-20170310013346-4a435daef6cc/go.mod h1:e6humHha1ekIwTCm+A5Qed5mG8V4JL+ChHcUOJ+L/8U=
github.com/xanzy/go-cloudstack v0.0.0-20160728180336-1e2cbf647e57 h1:3OK6oXqbbEUeWvTJgg1pZgNjzdCNE6hMu2TragCfwb8=
github.com/xanzy/go-cloudstack v0.0.0-20160728180336-1e2cbf647e57/go.mod h1:s3eL3z5pNXF5FVybcT+LIVdId8pYn709yv6v5mrkrQE=
github.com/xiang90/probing v0.0.0-20160813154853-07dd2e8dfe18 h1:MPPkRncZLN9Kh4MEFmbnK4h3BD7AUmskWv2+EeZJCCs=
github.com/xiang90/probing v0.0.0-20160813154853-07dd2e8dfe18/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU=
github.com/xlab/handysort v0.0.0-20150421192137-fb3537ed64a1 h1:j2hhcujLRHAg872RWAV5yaUrEjHEObwDv3aImCaNLek=

View File

@ -51,7 +51,6 @@ pkg/apis/scheduling/v1beta1
pkg/apis/storage
pkg/apis/storage/v1
pkg/apis/storage/v1beta1
pkg/cloudprovider/providers/photon
pkg/controller
pkg/controller/apis/config/v1alpha1
pkg/controller/certificates
@ -315,7 +314,6 @@ pkg/volume/csi/csiv0
pkg/volume/csi/fake
pkg/volume/git_repo
pkg/volume/iscsi
pkg/volume/photon_pd
pkg/volume/rbd
pkg/volume/scaleio
pkg/volume/storageos

View File

@ -13,10 +13,7 @@ go_library(
"//cmd/kubelet/app:__pkg__",
],
deps = [
"//pkg/cloudprovider/providers/cloudstack:go_default_library",
"//pkg/cloudprovider/providers/openstack:go_default_library",
"//pkg/cloudprovider/providers/ovirt:go_default_library",
"//pkg/cloudprovider/providers/photon:go_default_library",
"//staging/src/k8s.io/legacy-cloud-providers/aws:go_default_library",
"//staging/src/k8s.io/legacy-cloud-providers/azure:go_default_library",
"//staging/src/k8s.io/legacy-cloud-providers/gce:go_default_library",
@ -35,10 +32,7 @@ filegroup(
name = "all-srcs",
srcs = [
":package-srcs",
"//pkg/cloudprovider/providers/cloudstack:all-srcs",
"//pkg/cloudprovider/providers/openstack:all-srcs",
"//pkg/cloudprovider/providers/ovirt:all-srcs",
"//pkg/cloudprovider/providers/photon:all-srcs",
],
tags = ["automanaged"],
)

View File

@ -1,88 +0,0 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
"go_test",
)
go_library(
name = "go_default_library",
srcs = [
"cloudstack.go",
"cloudstack_instances.go",
"cloudstack_loadbalancer.go",
"metadata.go",
"metadata_linux.go",
"metadata_other.go",
],
importpath = "k8s.io/kubernetes/pkg/cloudprovider/providers/cloudstack",
deps = [
"//staging/src/k8s.io/api/core/v1:go_default_library",
"//staging/src/k8s.io/apimachinery/pkg/types:go_default_library",
"//staging/src/k8s.io/cloud-provider:go_default_library",
"//vendor/github.com/d2g/dhcp4:go_default_library",
"//vendor/github.com/kardianos/osext:go_default_library",
"//vendor/github.com/xanzy/go-cloudstack/cloudstack:go_default_library",
"//vendor/gopkg.in/gcfg.v1:go_default_library",
"//vendor/k8s.io/klog:go_default_library",
] + select({
"@io_bazel_rules_go//go/platform:android": [
"//vendor/github.com/d2g/dhcp4client:go_default_library",
],
"@io_bazel_rules_go//go/platform:darwin": [
"//vendor/github.com/d2g/dhcp4client:go_default_library",
],
"@io_bazel_rules_go//go/platform:dragonfly": [
"//vendor/github.com/d2g/dhcp4client:go_default_library",
],
"@io_bazel_rules_go//go/platform:freebsd": [
"//vendor/github.com/d2g/dhcp4client:go_default_library",
],
"@io_bazel_rules_go//go/platform:linux": [
"//vendor/github.com/d2g/dhcp4client:go_default_library",
],
"@io_bazel_rules_go//go/platform:nacl": [
"//vendor/github.com/d2g/dhcp4client:go_default_library",
],
"@io_bazel_rules_go//go/platform:netbsd": [
"//vendor/github.com/d2g/dhcp4client:go_default_library",
],
"@io_bazel_rules_go//go/platform:openbsd": [
"//vendor/github.com/d2g/dhcp4client:go_default_library",
],
"@io_bazel_rules_go//go/platform:plan9": [
"//vendor/github.com/d2g/dhcp4client:go_default_library",
],
"@io_bazel_rules_go//go/platform:solaris": [
"//vendor/github.com/d2g/dhcp4client:go_default_library",
],
"@io_bazel_rules_go//go/platform:windows": [
"//vendor/github.com/d2g/dhcp4client:go_default_library",
],
"//conditions:default": [],
}),
)
go_test(
name = "go_default_test",
srcs = ["cloudstack_test.go"],
embed = [":go_default_library"],
deps = [
"//staging/src/k8s.io/api/core/v1:go_default_library",
"//staging/src/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
)

View File

@ -1,6 +0,0 @@
# See the OWNERS docs at https://go.k8s.io/owners
approvers:
- ngtuna
- sebgoa
- svanharmelen

View File

@ -1,265 +0,0 @@
/*
Copyright 2016 The Kubernetes Authors.
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 cloudstack
import (
"context"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"github.com/kardianos/osext"
"github.com/xanzy/go-cloudstack/cloudstack"
"gopkg.in/gcfg.v1"
"k8s.io/apimachinery/pkg/types"
cloudprovider "k8s.io/cloud-provider"
"k8s.io/klog"
)
// ProviderName is the name of this cloud provider.
const ProviderName = "cloudstack"
// CSConfig wraps the config for the CloudStack cloud provider.
type CSConfig struct {
Global struct {
APIURL string `gcfg:"api-url"`
APIKey string `gcfg:"api-key"`
SecretKey string `gcfg:"secret-key"`
SSLNoVerify bool `gcfg:"ssl-no-verify"`
ProjectID string `gcfg:"project-id"`
Zone string `gcfg:"zone"`
}
}
// CSCloud is an implementation of Interface for CloudStack.
type CSCloud struct {
client *cloudstack.CloudStackClient
metadata *metadata
projectID string // If non-"", all resources will be created within this project
zone string
}
func init() {
cloudprovider.RegisterCloudProvider(ProviderName, func(config io.Reader) (cloudprovider.Interface, error) {
cfg, err := readConfig(config)
if err != nil {
return nil, err
}
return newCSCloud(cfg)
})
}
func readConfig(config io.Reader) (*CSConfig, error) {
cfg := &CSConfig{}
if config == nil {
return cfg, nil
}
if err := gcfg.ReadInto(cfg, config); err != nil {
return nil, fmt.Errorf("could not parse cloud provider config: %v", err)
}
return cfg, nil
}
// newCSCloud creates a new instance of CSCloud.
func newCSCloud(cfg *CSConfig) (*CSCloud, error) {
cs := &CSCloud{
projectID: cfg.Global.ProjectID,
zone: cfg.Global.Zone,
}
exe, err := osext.Executable()
if err != nil {
return nil, fmt.Errorf("cloud not find the service executable: %v", err)
}
// When running the kubelet service it's fine to not specify a config file (or only a
// partial config file) as all needed info can be retrieved anonymously using metadata.
if filepath.Base(exe) == "kubelet" || filepath.Base(exe) == "kubelet.exe" {
// In CloudStack your metadata is always served by the DHCP server.
dhcpServer, err := findDHCPServer()
if err == nil {
klog.V(4).Infof("Found metadata server: %v", dhcpServer)
cs.metadata = &metadata{dhcpServer: dhcpServer, zone: cs.zone}
} else {
klog.Errorf("Error searching metadata server: %v", err)
}
}
if cfg.Global.APIURL != "" && cfg.Global.APIKey != "" && cfg.Global.SecretKey != "" {
cs.client = cloudstack.NewAsyncClient(cfg.Global.APIURL, cfg.Global.APIKey, cfg.Global.SecretKey, !cfg.Global.SSLNoVerify)
}
if cs.client == nil {
if cs.metadata != nil {
klog.V(2).Infof("No API URL, key and secret are provided, so only using metadata!")
} else {
return nil, errors.New("no cloud provider config given")
}
}
return cs, nil
}
var _ cloudprovider.Interface = (*CSCloud)(nil)
var _ cloudprovider.Instances = (*CSCloud)(nil)
var _ cloudprovider.LoadBalancer = (*CSCloud)(nil)
var _ cloudprovider.Zones = (*CSCloud)(nil)
// Initialize passes a Kubernetes clientBuilder interface to the cloud provider
func (cs *CSCloud) Initialize(clientBuilder cloudprovider.ControllerClientBuilder, stop <-chan struct{}) {
}
// LoadBalancer returns an implementation of LoadBalancer for CloudStack.
func (cs *CSCloud) LoadBalancer() (cloudprovider.LoadBalancer, bool) {
if cs.client == nil {
return nil, false
}
return cs, true
}
// Instances returns an implementation of Instances for CloudStack.
func (cs *CSCloud) Instances() (cloudprovider.Instances, bool) {
if cs.metadata != nil {
return cs.metadata, true
}
if cs.client == nil {
return nil, false
}
return cs, true
}
// Zones returns an implementation of Zones for CloudStack.
func (cs *CSCloud) Zones() (cloudprovider.Zones, bool) {
if cs.metadata != nil {
return cs.metadata, true
}
if cs.client == nil {
return nil, false
}
return cs, true
}
// Clusters returns an implementation of Clusters for CloudStack.
func (cs *CSCloud) Clusters() (cloudprovider.Clusters, bool) {
if cs.client == nil {
return nil, false
}
return nil, false
}
// Routes returns an implementation of Routes for CloudStack.
func (cs *CSCloud) Routes() (cloudprovider.Routes, bool) {
if cs.client == nil {
return nil, false
}
return nil, false
}
// ProviderName returns the cloud provider ID.
func (cs *CSCloud) ProviderName() string {
return ProviderName
}
// HasClusterID returns true if the cluster has a clusterID
func (cs *CSCloud) HasClusterID() bool {
return true
}
// GetZone returns the Zone containing the region that the program is running in.
func (cs *CSCloud) GetZone(ctx context.Context) (cloudprovider.Zone, error) {
zone := cloudprovider.Zone{}
if cs.zone == "" {
hostname, err := os.Hostname()
if err != nil {
return zone, fmt.Errorf("failed to get hostname for retrieving the zone: %v", err)
}
instance, count, err := cs.client.VirtualMachine.GetVirtualMachineByName(hostname)
if err != nil {
if count == 0 {
return zone, fmt.Errorf("could not find instance for retrieving the zone: %v", err)
}
return zone, fmt.Errorf("error getting instance for retrieving the zone: %v", err)
}
cs.zone = instance.Zonename
}
klog.V(2).Infof("Current zone is %v", cs.zone)
zone.FailureDomain = cs.zone
zone.Region = cs.zone
return zone, nil
}
// GetZoneByProviderID returns the Zone, found by using the provider ID.
func (cs *CSCloud) GetZoneByProviderID(ctx context.Context, providerID string) (cloudprovider.Zone, error) {
zone := cloudprovider.Zone{}
instance, count, err := cs.client.VirtualMachine.GetVirtualMachineByID(
providerID,
cloudstack.WithProject(cs.projectID),
)
if err != nil {
if count == 0 {
return zone, fmt.Errorf("could not find node by ID: %v", providerID)
}
return zone, fmt.Errorf("error retrieving zone: %v", err)
}
klog.V(2).Infof("Current zone is %v", cs.zone)
zone.FailureDomain = instance.Zonename
zone.Region = instance.Zonename
return zone, nil
}
// GetZoneByNodeName returns the Zone, found by using the node name.
func (cs *CSCloud) GetZoneByNodeName(ctx context.Context, nodeName types.NodeName) (cloudprovider.Zone, error) {
zone := cloudprovider.Zone{}
instance, count, err := cs.client.VirtualMachine.GetVirtualMachineByName(
string(nodeName),
cloudstack.WithProject(cs.projectID),
)
if err != nil {
if count == 0 {
return zone, fmt.Errorf("could not find node: %v", nodeName)
}
return zone, fmt.Errorf("error retrieving zone: %v", err)
}
klog.V(2).Infof("Current zone is %v", cs.zone)
zone.FailureDomain = instance.Zonename
zone.Region = instance.Zonename
return zone, nil
}

View File

@ -1,164 +0,0 @@
/*
Copyright 2016 The Kubernetes Authors.
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 cloudstack
import (
"context"
"errors"
"fmt"
"github.com/xanzy/go-cloudstack/cloudstack"
"k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/types"
cloudprovider "k8s.io/cloud-provider"
"k8s.io/klog"
)
// NodeAddresses returns the addresses of the specified instance.
func (cs *CSCloud) NodeAddresses(ctx context.Context, name types.NodeName) ([]v1.NodeAddress, error) {
instance, count, err := cs.client.VirtualMachine.GetVirtualMachineByName(
string(name),
cloudstack.WithProject(cs.projectID),
)
if err != nil {
if count == 0 {
return nil, cloudprovider.InstanceNotFound
}
return nil, fmt.Errorf("error retrieving node addresses: %v", err)
}
return cs.nodeAddresses(instance)
}
// NodeAddressesByProviderID returns the addresses of the specified instance.
func (cs *CSCloud) NodeAddressesByProviderID(ctx context.Context, providerID string) ([]v1.NodeAddress, error) {
instance, count, err := cs.client.VirtualMachine.GetVirtualMachineByID(
providerID,
cloudstack.WithProject(cs.projectID),
)
if err != nil {
if count == 0 {
return nil, cloudprovider.InstanceNotFound
}
return nil, fmt.Errorf("error retrieving node addresses: %v", err)
}
return cs.nodeAddresses(instance)
}
func (cs *CSCloud) nodeAddresses(instance *cloudstack.VirtualMachine) ([]v1.NodeAddress, error) {
if len(instance.Nic) == 0 {
return nil, errors.New("instance does not have an internal IP")
}
addresses := []v1.NodeAddress{
{Type: v1.NodeInternalIP, Address: instance.Nic[0].Ipaddress},
}
if instance.Hostname != "" {
addresses = append(addresses, v1.NodeAddress{Type: v1.NodeHostName, Address: instance.Hostname})
}
if instance.Publicip != "" {
addresses = append(addresses, v1.NodeAddress{Type: v1.NodeExternalIP, Address: instance.Publicip})
} else {
// Since there is no sane way to determine the external IP if the host isn't
// using static NAT, we will just fire a log message and omit the external IP.
klog.V(4).Infof("Could not determine the public IP of host %v (%v)", instance.Name, instance.Id)
}
return addresses, nil
}
// InstanceID returns the cloud provider ID of the specified instance.
func (cs *CSCloud) InstanceID(ctx context.Context, name types.NodeName) (string, error) {
instance, count, err := cs.client.VirtualMachine.GetVirtualMachineByName(
string(name),
cloudstack.WithProject(cs.projectID),
)
if err != nil {
if count == 0 {
return "", cloudprovider.InstanceNotFound
}
return "", fmt.Errorf("error retrieving instance ID: %v", err)
}
return instance.Id, nil
}
// InstanceType returns the type of the specified instance.
func (cs *CSCloud) InstanceType(ctx context.Context, name types.NodeName) (string, error) {
instance, count, err := cs.client.VirtualMachine.GetVirtualMachineByName(
string(name),
cloudstack.WithProject(cs.projectID),
)
if err != nil {
if count == 0 {
return "", cloudprovider.InstanceNotFound
}
return "", fmt.Errorf("error retrieving instance type: %v", err)
}
return instance.Serviceofferingname, nil
}
// InstanceTypeByProviderID returns the type of the specified instance.
func (cs *CSCloud) InstanceTypeByProviderID(ctx context.Context, providerID string) (string, error) {
instance, count, err := cs.client.VirtualMachine.GetVirtualMachineByID(
providerID,
cloudstack.WithProject(cs.projectID),
)
if err != nil {
if count == 0 {
return "", cloudprovider.InstanceNotFound
}
return "", fmt.Errorf("error retrieving instance type: %v", err)
}
return instance.Serviceofferingname, nil
}
// AddSSHKeyToAllInstances is currently not implemented.
func (cs *CSCloud) AddSSHKeyToAllInstances(ctx context.Context, user string, keyData []byte) error {
return cloudprovider.NotImplemented
}
// CurrentNodeName returns the name of the node we are currently running on.
func (cs *CSCloud) CurrentNodeName(ctx context.Context, hostname string) (types.NodeName, error) {
return types.NodeName(hostname), nil
}
// InstanceExistsByProviderID returns if the instance still exists.
func (cs *CSCloud) InstanceExistsByProviderID(ctx context.Context, providerID string) (bool, error) {
_, count, err := cs.client.VirtualMachine.GetVirtualMachineByID(
providerID,
cloudstack.WithProject(cs.projectID),
)
if err != nil {
if count == 0 {
return false, nil
}
return false, fmt.Errorf("error retrieving instance: %v", err)
}
return true, nil
}
// InstanceShutdownByProviderID returns true if the instance is in safe state to detach volumes
func (cs *CSCloud) InstanceShutdownByProviderID(ctx context.Context, providerID string) (bool, error) {
return false, cloudprovider.NotImplemented
}

View File

@ -1,549 +0,0 @@
/*
Copyright 2016 The Kubernetes Authors.
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 cloudstack
import (
"context"
"fmt"
"strconv"
"github.com/xanzy/go-cloudstack/cloudstack"
"k8s.io/klog"
"k8s.io/api/core/v1"
cloudprovider "k8s.io/cloud-provider"
)
type loadBalancer struct {
*cloudstack.CloudStackClient
name string
algorithm string
hostIDs []string
ipAddr string
ipAddrID string
networkID string
projectID string
rules map[string]*cloudstack.LoadBalancerRule
}
// GetLoadBalancer returns whether the specified load balancer exists, and if so, what its status is.
func (cs *CSCloud) GetLoadBalancer(ctx context.Context, clusterName string, service *v1.Service) (*v1.LoadBalancerStatus, bool, error) {
klog.V(4).Infof("GetLoadBalancer(%v, %v, %v)", clusterName, service.Namespace, service.Name)
// Get the load balancer details and existing rules.
lb, err := cs.getLoadBalancer(service)
if err != nil {
return nil, false, err
}
// If we don't have any rules, the load balancer does not exist.
if len(lb.rules) == 0 {
return nil, false, nil
}
klog.V(4).Infof("Found a load balancer associated with IP %v", lb.ipAddr)
status := &v1.LoadBalancerStatus{}
status.Ingress = append(status.Ingress, v1.LoadBalancerIngress{IP: lb.ipAddr})
return status, true, nil
}
// EnsureLoadBalancer creates a new load balancer, or updates the existing one. Returns the status of the balancer.
func (cs *CSCloud) EnsureLoadBalancer(ctx context.Context, clusterName string, service *v1.Service, nodes []*v1.Node) (status *v1.LoadBalancerStatus, err error) {
klog.V(4).Infof("EnsureLoadBalancer(%v, %v, %v, %v, %v, %v)", clusterName, service.Namespace, service.Name, service.Spec.LoadBalancerIP, service.Spec.Ports, nodes)
if len(service.Spec.Ports) == 0 {
return nil, fmt.Errorf("requested load balancer with no ports")
}
// Get the load balancer details and existing rules.
lb, err := cs.getLoadBalancer(service)
if err != nil {
return nil, err
}
// Set the load balancer algorithm.
switch service.Spec.SessionAffinity {
case v1.ServiceAffinityNone:
lb.algorithm = "roundrobin"
case v1.ServiceAffinityClientIP:
lb.algorithm = "source"
default:
return nil, fmt.Errorf("unsupported load balancer affinity: %v", service.Spec.SessionAffinity)
}
// Verify that all the hosts belong to the same network, and retrieve their ID's.
lb.hostIDs, lb.networkID, err = cs.verifyHosts(nodes)
if err != nil {
return nil, err
}
if !lb.hasLoadBalancerIP() {
// Create or retrieve the load balancer IP.
if err := lb.getLoadBalancerIP(service.Spec.LoadBalancerIP); err != nil {
return nil, err
}
if lb.ipAddr != "" && lb.ipAddr != service.Spec.LoadBalancerIP {
defer func(lb *loadBalancer) {
if err != nil {
if err := lb.releaseLoadBalancerIP(); err != nil {
klog.Errorf(err.Error())
}
}
}(lb)
}
}
klog.V(4).Infof("Load balancer %v is associated with IP %v", lb.name, lb.ipAddr)
for _, port := range service.Spec.Ports {
// All ports have their own load balancer rule, so add the port to lbName to keep the names unique.
lbRuleName := fmt.Sprintf("%s-%d", lb.name, port.Port)
// If the load balancer rule exists and is up-to-date, we move on to the next rule.
exists, needsUpdate, err := lb.checkLoadBalancerRule(lbRuleName, port)
if err != nil {
return nil, err
}
if exists && !needsUpdate {
klog.V(4).Infof("Load balancer rule %v is up-to-date", lbRuleName)
// Delete the rule from the map, to prevent it being deleted.
delete(lb.rules, lbRuleName)
continue
}
if needsUpdate {
klog.V(4).Infof("Updating load balancer rule: %v", lbRuleName)
if err := lb.updateLoadBalancerRule(lbRuleName); err != nil {
return nil, err
}
// Delete the rule from the map, to prevent it being deleted.
delete(lb.rules, lbRuleName)
continue
}
klog.V(4).Infof("Creating load balancer rule: %v", lbRuleName)
lbRule, err := lb.createLoadBalancerRule(lbRuleName, port)
if err != nil {
return nil, err
}
klog.V(4).Infof("Assigning hosts (%v) to load balancer rule: %v", lb.hostIDs, lbRuleName)
if err = lb.assignHostsToRule(lbRule, lb.hostIDs); err != nil {
return nil, err
}
}
// Cleanup any rules that are now still in the rules map, as they are no longer needed.
for _, lbRule := range lb.rules {
klog.V(4).Infof("Deleting obsolete load balancer rule: %v", lbRule.Name)
if err := lb.deleteLoadBalancerRule(lbRule); err != nil {
return nil, err
}
}
status = &v1.LoadBalancerStatus{}
status.Ingress = []v1.LoadBalancerIngress{{IP: lb.ipAddr}}
return status, nil
}
// UpdateLoadBalancer updates hosts under the specified load balancer.
func (cs *CSCloud) UpdateLoadBalancer(ctx context.Context, clusterName string, service *v1.Service, nodes []*v1.Node) error {
klog.V(4).Infof("UpdateLoadBalancer(%v, %v, %v, %v)", clusterName, service.Namespace, service.Name, nodes)
// Get the load balancer details and existing rules.
lb, err := cs.getLoadBalancer(service)
if err != nil {
return err
}
// Verify that all the hosts belong to the same network, and retrieve their ID's.
lb.hostIDs, _, err = cs.verifyHosts(nodes)
if err != nil {
return err
}
for _, lbRule := range lb.rules {
p := lb.LoadBalancer.NewListLoadBalancerRuleInstancesParams(lbRule.Id)
// Retrieve all VMs currently associated to this load balancer rule.
l, err := lb.LoadBalancer.ListLoadBalancerRuleInstances(p)
if err != nil {
return fmt.Errorf("error retrieving associated instances: %v", err)
}
assign, remove := symmetricDifference(lb.hostIDs, l.LoadBalancerRuleInstances)
if len(assign) > 0 {
klog.V(4).Infof("Assigning new hosts (%v) to load balancer rule: %v", assign, lbRule.Name)
if err := lb.assignHostsToRule(lbRule, assign); err != nil {
return err
}
}
if len(remove) > 0 {
klog.V(4).Infof("Removing old hosts (%v) from load balancer rule: %v", assign, lbRule.Name)
if err := lb.removeHostsFromRule(lbRule, remove); err != nil {
return err
}
}
}
return nil
}
// EnsureLoadBalancerDeleted deletes the specified load balancer if it exists, returning
// nil if the load balancer specified either didn't exist or was successfully deleted.
func (cs *CSCloud) EnsureLoadBalancerDeleted(ctx context.Context, clusterName string, service *v1.Service) error {
klog.V(4).Infof("EnsureLoadBalancerDeleted(%v, %v, %v)", clusterName, service.Namespace, service.Name)
// Get the load balancer details and existing rules.
lb, err := cs.getLoadBalancer(service)
if err != nil {
return err
}
for _, lbRule := range lb.rules {
klog.V(4).Infof("Deleting load balancer rule: %v", lbRule.Name)
if err := lb.deleteLoadBalancerRule(lbRule); err != nil {
return err
}
}
if lb.ipAddr != "" && lb.ipAddr != service.Spec.LoadBalancerIP {
klog.V(4).Infof("Releasing load balancer IP: %v", lb.ipAddr)
if err := lb.releaseLoadBalancerIP(); err != nil {
return err
}
}
return nil
}
// GetLoadBalancerName retrieves the name of the LoadBalancer.
func (cs *CSCloud) GetLoadBalancerName(ctx context.Context, clusterName string, service *v1.Service) string {
return cloudprovider.DefaultLoadBalancerName(service)
}
// getLoadBalancer retrieves the IP address and ID and all the existing rules it can find.
func (cs *CSCloud) getLoadBalancer(service *v1.Service) (*loadBalancer, error) {
lb := &loadBalancer{
CloudStackClient: cs.client,
name: cs.GetLoadBalancerName(context.TODO(), "", service),
projectID: cs.projectID,
rules: make(map[string]*cloudstack.LoadBalancerRule),
}
p := cs.client.LoadBalancer.NewListLoadBalancerRulesParams()
p.SetKeyword(lb.name)
p.SetListall(true)
if cs.projectID != "" {
p.SetProjectid(cs.projectID)
}
l, err := cs.client.LoadBalancer.ListLoadBalancerRules(p)
if err != nil {
return nil, fmt.Errorf("error retrieving load balancer rules: %v", err)
}
for _, lbRule := range l.LoadBalancerRules {
lb.rules[lbRule.Name] = lbRule
if lb.ipAddr != "" && lb.ipAddr != lbRule.Publicip {
klog.Warningf("Load balancer for service %v/%v has rules associated with different IP's: %v, %v", service.Namespace, service.Name, lb.ipAddr, lbRule.Publicip)
}
lb.ipAddr = lbRule.Publicip
lb.ipAddrID = lbRule.Publicipid
}
klog.V(4).Infof("Load balancer %v contains %d rule(s)", lb.name, len(lb.rules))
return lb, nil
}
// verifyHosts verifies if all hosts belong to the same network, and returns the host ID's and network ID.
func (cs *CSCloud) verifyHosts(nodes []*v1.Node) ([]string, string, error) {
hostNames := map[string]bool{}
for _, node := range nodes {
hostNames[node.Name] = true
}
p := cs.client.VirtualMachine.NewListVirtualMachinesParams()
p.SetListall(true)
if cs.projectID != "" {
p.SetProjectid(cs.projectID)
}
l, err := cs.client.VirtualMachine.ListVirtualMachines(p)
if err != nil {
return nil, "", fmt.Errorf("error retrieving list of hosts: %v", err)
}
var hostIDs []string
var networkID string
// Check if the virtual machine is in the hosts slice, then add the corresponding ID.
for _, vm := range l.VirtualMachines {
if hostNames[vm.Name] {
if networkID != "" && networkID != vm.Nic[0].Networkid {
return nil, "", fmt.Errorf("found hosts that belong to different networks")
}
networkID = vm.Nic[0].Networkid
hostIDs = append(hostIDs, vm.Id)
}
}
return hostIDs, networkID, nil
}
// hasLoadBalancerIP returns true if we have a load balancer address and ID.
func (lb *loadBalancer) hasLoadBalancerIP() bool {
return lb.ipAddr != "" && lb.ipAddrID != ""
}
// getLoadBalancerIP retieves an existing IP or associates a new IP.
func (lb *loadBalancer) getLoadBalancerIP(loadBalancerIP string) error {
if loadBalancerIP != "" {
return lb.getPublicIPAddress(loadBalancerIP)
}
return lb.associatePublicIPAddress()
}
// getPublicIPAddressID retrieves the ID of the given IP, and sets the address and it's ID.
func (lb *loadBalancer) getPublicIPAddress(loadBalancerIP string) error {
klog.V(4).Infof("Retrieve load balancer IP details: %v", loadBalancerIP)
p := lb.Address.NewListPublicIpAddressesParams()
p.SetIpaddress(loadBalancerIP)
p.SetListall(true)
if lb.projectID != "" {
p.SetProjectid(lb.projectID)
}
l, err := lb.Address.ListPublicIpAddresses(p)
if err != nil {
return fmt.Errorf("error retrieving IP address: %v", err)
}
if l.Count != 1 {
return fmt.Errorf("could not find IP address %v", loadBalancerIP)
}
lb.ipAddr = l.PublicIpAddresses[0].Ipaddress
lb.ipAddrID = l.PublicIpAddresses[0].Id
return nil
}
// associatePublicIPAddress associates a new IP and sets the address and it's ID.
func (lb *loadBalancer) associatePublicIPAddress() error {
klog.V(4).Infof("Allocate new IP for load balancer: %v", lb.name)
// If a network belongs to a VPC, the IP address needs to be associated with
// the VPC instead of with the network.
network, count, err := lb.Network.GetNetworkByID(lb.networkID, cloudstack.WithProject(lb.projectID))
if err != nil {
if count == 0 {
return fmt.Errorf("could not find network %v", lb.networkID)
}
return fmt.Errorf("error retrieving network: %v", err)
}
p := lb.Address.NewAssociateIpAddressParams()
if network.Vpcid != "" {
p.SetVpcid(network.Vpcid)
} else {
p.SetNetworkid(lb.networkID)
}
if lb.projectID != "" {
p.SetProjectid(lb.projectID)
}
// Associate a new IP address
r, err := lb.Address.AssociateIpAddress(p)
if err != nil {
return fmt.Errorf("error associating new IP address: %v", err)
}
lb.ipAddr = r.Ipaddress
lb.ipAddrID = r.Id
return nil
}
// releasePublicIPAddress releases an associated IP.
func (lb *loadBalancer) releaseLoadBalancerIP() error {
p := lb.Address.NewDisassociateIpAddressParams(lb.ipAddrID)
if _, err := lb.Address.DisassociateIpAddress(p); err != nil {
return fmt.Errorf("error releasing load balancer IP %v: %v", lb.ipAddr, err)
}
return nil
}
// checkLoadBalancerRule checks if the rule already exists and if it does, if it can be updated. If
// it does exist but cannot be updated, it will delete the existing rule so it can be created again.
func (lb *loadBalancer) checkLoadBalancerRule(lbRuleName string, port v1.ServicePort) (bool, bool, error) {
lbRule, ok := lb.rules[lbRuleName]
if !ok {
return false, false, nil
}
// Check if any of the values we cannot update (those that require a new load balancer rule) are changed.
if lbRule.Publicip == lb.ipAddr && lbRule.Privateport == strconv.Itoa(int(port.NodePort)) && lbRule.Publicport == strconv.Itoa(int(port.Port)) {
return true, lbRule.Algorithm != lb.algorithm, nil
}
// Delete the load balancer rule so we can create a new one using the new values.
if err := lb.deleteLoadBalancerRule(lbRule); err != nil {
return false, false, err
}
return false, false, nil
}
// updateLoadBalancerRule updates a load balancer rule.
func (lb *loadBalancer) updateLoadBalancerRule(lbRuleName string) error {
lbRule := lb.rules[lbRuleName]
p := lb.LoadBalancer.NewUpdateLoadBalancerRuleParams(lbRule.Id)
p.SetAlgorithm(lb.algorithm)
_, err := lb.LoadBalancer.UpdateLoadBalancerRule(p)
return err
}
// createLoadBalancerRule creates a new load balancer rule and returns it's ID.
func (lb *loadBalancer) createLoadBalancerRule(lbRuleName string, port v1.ServicePort) (*cloudstack.LoadBalancerRule, error) {
p := lb.LoadBalancer.NewCreateLoadBalancerRuleParams(
lb.algorithm,
lbRuleName,
int(port.NodePort),
int(port.Port),
)
p.SetNetworkid(lb.networkID)
p.SetPublicipid(lb.ipAddrID)
switch port.Protocol {
case v1.ProtocolTCP:
p.SetProtocol("TCP")
case v1.ProtocolUDP:
p.SetProtocol("UDP")
default:
return nil, fmt.Errorf("unsupported load balancer protocol: %v", port.Protocol)
}
// Do not create corresponding firewall rule.
p.SetOpenfirewall(false)
// Create a new load balancer rule.
r, err := lb.LoadBalancer.CreateLoadBalancerRule(p)
if err != nil {
return nil, fmt.Errorf("error creating load balancer rule %v: %v", lbRuleName, err)
}
lbRule := &cloudstack.LoadBalancerRule{
Id: r.Id,
Algorithm: r.Algorithm,
Cidrlist: r.Cidrlist,
Name: r.Name,
Networkid: r.Networkid,
Privateport: r.Privateport,
Publicport: r.Publicport,
Publicip: r.Publicip,
Publicipid: r.Publicipid,
}
return lbRule, nil
}
// deleteLoadBalancerRule deletes a load balancer rule.
func (lb *loadBalancer) deleteLoadBalancerRule(lbRule *cloudstack.LoadBalancerRule) error {
p := lb.LoadBalancer.NewDeleteLoadBalancerRuleParams(lbRule.Id)
if _, err := lb.LoadBalancer.DeleteLoadBalancerRule(p); err != nil {
return fmt.Errorf("error deleting load balancer rule %v: %v", lbRule.Name, err)
}
// Delete the rule from the map as it no longer exists
delete(lb.rules, lbRule.Name)
return nil
}
// assignHostsToRule assigns hosts to a load balancer rule.
func (lb *loadBalancer) assignHostsToRule(lbRule *cloudstack.LoadBalancerRule, hostIDs []string) error {
p := lb.LoadBalancer.NewAssignToLoadBalancerRuleParams(lbRule.Id)
p.SetVirtualmachineids(hostIDs)
if _, err := lb.LoadBalancer.AssignToLoadBalancerRule(p); err != nil {
return fmt.Errorf("error assigning hosts to load balancer rule %v: %v", lbRule.Name, err)
}
return nil
}
// removeHostsFromRule removes hosts from a load balancer rule.
func (lb *loadBalancer) removeHostsFromRule(lbRule *cloudstack.LoadBalancerRule, hostIDs []string) error {
p := lb.LoadBalancer.NewRemoveFromLoadBalancerRuleParams(lbRule.Id)
p.SetVirtualmachineids(hostIDs)
if _, err := lb.LoadBalancer.RemoveFromLoadBalancerRule(p); err != nil {
return fmt.Errorf("error removing hosts from load balancer rule %v: %v", lbRule.Name, err)
}
return nil
}
// symmetricDifference returns the symmetric difference between the old (existing) and new (wanted) host ID's.
func symmetricDifference(hostIDs []string, lbInstances []*cloudstack.VirtualMachine) ([]string, []string) {
new := make(map[string]bool)
for _, hostID := range hostIDs {
new[hostID] = true
}
var remove []string
for _, instance := range lbInstances {
if new[instance.Id] {
delete(new, instance.Id)
continue
}
remove = append(remove, instance.Id)
}
var assign []string
for hostID := range new {
assign = append(assign, hostID)
}
return assign, remove
}

View File

@ -1,118 +0,0 @@
/*
Copyright 2016 The Kubernetes Authors.
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 cloudstack
import (
"context"
"os"
"strconv"
"strings"
"testing"
"k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
const testClusterName = "testCluster"
func TestReadConfig(t *testing.T) {
_, err := readConfig(nil)
if err != nil {
t.Fatalf("Should not return an error when no config is provided: %v", err)
}
cfg, err := readConfig(strings.NewReader(`
[Global]
api-url = https://cloudstack.url
api-key = a-valid-api-key
secret-key = a-valid-secret-key
ssl-no-verify = true
project-id = a-valid-project-id
`))
if err != nil {
t.Fatalf("Should succeed when a valid config is provided: %v", err)
}
if cfg.Global.APIURL != "https://cloudstack.url" {
t.Errorf("incorrect api-url: %s", cfg.Global.APIURL)
}
if cfg.Global.APIKey != "a-valid-api-key" {
t.Errorf("incorrect api-key: %s", cfg.Global.APIKey)
}
if cfg.Global.SecretKey != "a-valid-secret-key" {
t.Errorf("incorrect secret-key: %s", cfg.Global.SecretKey)
}
if !cfg.Global.SSLNoVerify {
t.Errorf("incorrect ssl-no-verify: %t", cfg.Global.SSLNoVerify)
}
}
// This allows acceptance testing against an existing CloudStack environment.
func configFromEnv() (*CSConfig, bool) {
cfg := &CSConfig{}
cfg.Global.APIURL = os.Getenv("CS_API_URL")
cfg.Global.APIKey = os.Getenv("CS_API_KEY")
cfg.Global.SecretKey = os.Getenv("CS_SECRET_KEY")
cfg.Global.ProjectID = os.Getenv("CS_PROJECT_ID")
// It is save to ignore the error here. If the input cannot be parsed SSLNoVerify
// will still be a bool with its zero value (false) which is the expected default.
cfg.Global.SSLNoVerify, _ = strconv.ParseBool(os.Getenv("CS_SSL_NO_VERIFY"))
// Check if we have the minimum required info to be able to connect to CloudStack.
ok := cfg.Global.APIURL != "" && cfg.Global.APIKey != "" && cfg.Global.SecretKey != ""
return cfg, ok
}
func TestNewCSCloud(t *testing.T) {
cfg, ok := configFromEnv()
if !ok {
t.Skipf("No config found in environment")
}
_, err := newCSCloud(cfg)
if err != nil {
t.Fatalf("Failed to construct/authenticate CloudStack: %v", err)
}
}
func TestLoadBalancer(t *testing.T) {
cfg, ok := configFromEnv()
if !ok {
t.Skipf("No config found in environment")
}
cs, err := newCSCloud(cfg)
if err != nil {
t.Fatalf("Failed to construct/authenticate CloudStack: %v", err)
}
lb, ok := cs.LoadBalancer()
if !ok {
t.Fatalf("LoadBalancer() returned false")
}
_, exists, err := lb.GetLoadBalancer(context.TODO(), testClusterName, &v1.Service{ObjectMeta: metav1.ObjectMeta{Name: "noexist"}})
if err != nil {
t.Fatalf("GetLoadBalancer(\"noexist\") returned error: %s", err)
}
if exists {
t.Fatalf("GetLoadBalancer(\"noexist\") returned exists")
}
}

View File

@ -1,226 +0,0 @@
/*
Copyright 2016 The Kubernetes Authors.
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 cloudstack
import (
"context"
"errors"
"fmt"
"io/ioutil"
"net"
"net/http"
"github.com/d2g/dhcp4"
"k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/types"
cloudprovider "k8s.io/cloud-provider"
"k8s.io/klog"
)
var _ cloudprovider.Instances = (*metadata)(nil)
var _ cloudprovider.Zones = (*metadata)(nil)
type metadata struct {
dhcpServer string
zone string
}
type metadataType string
const (
metadataTypeHostname metadataType = "local-hostname"
metadataTypeExternalIP metadataType = "public-ipv4"
metadataTypeInternalIP metadataType = "local-ipv4"
metadataTypeInstanceID metadataType = "instance-id"
metadataTypeInstanceType metadataType = "service-offering"
metadataTypeZone metadataType = "availability-zone"
)
// NodeAddresses returns the addresses of the specified instance.
func (m *metadata) NodeAddresses(ctx context.Context, name types.NodeName) ([]v1.NodeAddress, error) {
externalIP, err := m.get(metadataTypeExternalIP)
if err != nil {
return nil, fmt.Errorf("could not get external IP: %v", err)
}
internalIP, err := m.get(metadataTypeInternalIP)
if err != nil {
return nil, fmt.Errorf("could not get internal IP: %v", err)
}
addresses := []v1.NodeAddress{
{Type: v1.NodeExternalIP, Address: externalIP},
{Type: v1.NodeInternalIP, Address: internalIP},
}
hostname, err := m.get(metadataTypeHostname)
if err != nil {
return nil, fmt.Errorf("could not get hostname: %v", err)
}
if hostname != "" {
addresses = append(addresses, v1.NodeAddress{Type: v1.NodeHostName, Address: hostname})
}
return addresses, nil
}
// NodeAddressesByProviderID returns the addresses of the specified instance.
func (m *metadata) NodeAddressesByProviderID(ctx context.Context, providerID string) ([]v1.NodeAddress, error) {
return nil, errors.New("NodeAddressesByProviderID not implemented")
}
// InstanceID returns the cloud provider ID of the specified instance.
func (m *metadata) InstanceID(ctx context.Context, name types.NodeName) (string, error) {
instanceID, err := m.get(metadataTypeInstanceID)
if err != nil {
return "", fmt.Errorf("could not get instance ID: %v", err)
}
zone, err := m.get(metadataTypeZone)
if err != nil {
return "", fmt.Errorf("could not get zone: %v", err)
}
return "/" + zone + "/" + instanceID, nil
}
// InstanceType returns the type of the specified instance.
func (m *metadata) InstanceType(ctx context.Context, name types.NodeName) (string, error) {
instanceType, err := m.get(metadataTypeInstanceType)
if err != nil {
return "", fmt.Errorf("could not get instance type: %v", err)
}
return instanceType, nil
}
// InstanceTypeByProviderID returns the type of the specified instance.
func (m *metadata) InstanceTypeByProviderID(ctx context.Context, providerID string) (string, error) {
return "", errors.New("InstanceTypeByProviderID not implemented")
}
// AddSSHKeyToAllInstances is currently not implemented.
func (m *metadata) AddSSHKeyToAllInstances(ctx context.Context, user string, keyData []byte) error {
return cloudprovider.NotImplemented
}
// CurrentNodeName returns the name of the node we are currently running on.
func (m *metadata) CurrentNodeName(ctx context.Context, hostname string) (types.NodeName, error) {
return types.NodeName(hostname), nil
}
// InstanceExistsByProviderID returns if the instance still exists.
func (m *metadata) InstanceExistsByProviderID(ctx context.Context, providerID string) (bool, error) {
return false, errors.New("InstanceExistsByProviderID not implemented")
}
// InstanceShutdownByProviderID returns if the instance is shutdown.
func (m *metadata) InstanceShutdownByProviderID(ctx context.Context, providerID string) (bool, error) {
return false, cloudprovider.NotImplemented
}
// GetZone returns the Zone containing the region that the program is running in.
func (m *metadata) GetZone(ctx context.Context) (cloudprovider.Zone, error) {
zone := cloudprovider.Zone{}
if m.zone == "" {
zoneName, err := m.get(metadataTypeZone)
if err != nil {
return zone, fmt.Errorf("could not get zone: %v", err)
}
m.zone = zoneName
}
klog.V(2).Infof("Current zone is %v", zone)
zone.FailureDomain = m.zone
zone.Region = m.zone
return zone, nil
}
// GetZoneByProviderID returns the Zone, found by using the provider ID.
func (m *metadata) GetZoneByProviderID(ctx context.Context, providerID string) (cloudprovider.Zone, error) {
return cloudprovider.Zone{}, errors.New("GetZoneByProviderID not implemented")
}
// GetZoneByNodeName returns the Zone, found by using the node name.
func (m *metadata) GetZoneByNodeName(ctx context.Context, nodeName types.NodeName) (cloudprovider.Zone, error) {
return cloudprovider.Zone{}, errors.New("GetZoneByNodeName not implemented")
}
func (m *metadata) get(mdType metadataType) (string, error) {
url := fmt.Sprintf("http://%s/latest/meta-data/%s", m.dhcpServer, mdType)
resp, err := http.Get(url)
if err != nil {
return "", fmt.Errorf("error reading metadata: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("unexpected HTTP status: %d", resp.StatusCode)
}
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", fmt.Errorf("error reading response body: %d", resp.StatusCode)
}
return string(data), nil
}
func findDHCPServer() (string, error) {
nics, err := net.Interfaces()
if err != nil {
return "", fmt.Errorf("could not get interfaces: %v", err)
}
for _, nic := range nics {
if nic.Flags&net.FlagUp == 1 && nic.Flags&net.FlagLoopback == 0 && nic.Flags&net.FlagPointToPoint == 0 {
addrs, err := nic.Addrs()
if err != nil {
return "", fmt.Errorf("error reading IP addresses from interface %v: %v", nic.Name, err)
}
if addrs != nil {
client, err := newDHCPClient(&nic)
if err != nil {
return "", fmt.Errorf("error creating new DHCP client: %v", err)
}
discoverPacket, err := client.SendDiscoverPacket()
if err != nil {
return "", fmt.Errorf("error sending DHCP discover package: %v", err)
}
offerPacket, err := client.GetOffer(&discoverPacket)
if err != nil {
return "", fmt.Errorf("error receiving DHCP offer package: %v", err)
}
offerPacketOptions := offerPacket.ParseOptions()
if ipaddr, ok := offerPacketOptions[dhcp4.OptionServerIdentifier]; ok {
return net.IP(ipaddr).String(), nil
}
}
}
}
return "", errors.New("no server found")
}

View File

@ -1,40 +0,0 @@
// +build linux
/*
Copyright 2016 The Kubernetes Authors.
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 cloudstack
import (
"net"
"time"
"github.com/d2g/dhcp4client"
)
func newDHCPClient(nic *net.Interface) (*dhcp4client.Client, error) {
pktsock, err := dhcp4client.NewPacketSock(nic.Index)
if err != nil {
return nil, err
}
return dhcp4client.New(
dhcp4client.HardwareAddr(nic.HardwareAddr),
dhcp4client.Timeout(2*time.Second),
dhcp4client.Broadcast(false),
dhcp4client.Connection(pktsock),
)
}

View File

@ -1,40 +0,0 @@
// +build !linux
/*
Copyright 2016 The Kubernetes Authors.
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 cloudstack
import (
"net"
"time"
"github.com/d2g/dhcp4client"
)
func newDHCPClient(nic *net.Interface) (*dhcp4client.Client, error) {
inetsock, err := dhcp4client.NewInetSock()
if err != nil {
return nil, err
}
return dhcp4client.New(
dhcp4client.HardwareAddr(nic.HardwareAddr),
dhcp4client.Timeout(2*time.Second),
dhcp4client.Broadcast(false),
dhcp4client.Connection(inetsock),
)
}

View File

@ -1,39 +0,0 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
"go_test",
)
go_library(
name = "go_default_library",
srcs = ["ovirt.go"],
importpath = "k8s.io/kubernetes/pkg/cloudprovider/providers/ovirt",
deps = [
"//staging/src/k8s.io/api/core/v1:go_default_library",
"//staging/src/k8s.io/apimachinery/pkg/types:go_default_library",
"//staging/src/k8s.io/cloud-provider:go_default_library",
"//vendor/gopkg.in/gcfg.v1:go_default_library",
],
)
go_test(
name = "go_default_test",
srcs = ["ovirt_test.go"],
embed = [":go_default_library"],
deps = ["//staging/src/k8s.io/cloud-provider:go_default_library"],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
)

View File

@ -1,329 +0,0 @@
/*
Copyright 2014 The Kubernetes Authors.
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 ovirt
import (
"context"
"encoding/xml"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"net/url"
"path"
"sort"
"strings"
"gopkg.in/gcfg.v1"
"k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/types"
cloudprovider "k8s.io/cloud-provider"
)
// ProviderName is the name of this cloud provider.
const ProviderName = "ovirt"
// Instance specifies UUID, name and IP address of the instance.
type Instance struct {
UUID string
Name string
IPAddress string
}
// InstanceMap provides the map of Ovirt instances.
type InstanceMap map[string]Instance
var _ cloudprovider.Interface = (*Cloud)(nil)
var _ cloudprovider.Instances = (*Cloud)(nil)
// Cloud is an implementation of the cloud provider interface for Ovirt.
type Cloud struct {
VmsRequest *url.URL
HostsRequest *url.URL
}
// APIConfig wraps the api settings for the Ovirt.
type APIConfig struct {
Connection struct {
APIEntry string `gcfg:"uri"`
Username string `gcfg:"username"`
Password string `gcfg:"password"`
}
Filters struct {
VmsQuery string `gcfg:"vms"`
}
}
// XMLVMAddress is an implementation for the Ovirt instance IP address in xml.
type XMLVMAddress struct {
Address string `xml:"address,attr"`
}
// XMLVMInfo is an implementation for the Ovirt instance details in xml.
type XMLVMInfo struct {
UUID string `xml:"id,attr"`
Name string `xml:"name"`
Hostname string `xml:"guest_info>fqdn"`
Addresses []XMLVMAddress `xml:"guest_info>ips>ip"`
State string `xml:"status>state"`
}
// XMLVmsList is an implementation to provide the list of Ovirt instances.
type XMLVmsList struct {
XMLName xml.Name `xml:"vms"`
VM []XMLVMInfo `xml:"vm"`
}
func init() {
cloudprovider.RegisterCloudProvider(ProviderName,
func(config io.Reader) (cloudprovider.Interface, error) {
return newOVirtCloud(config)
})
}
func newOVirtCloud(config io.Reader) (*Cloud, error) {
if config == nil {
return nil, fmt.Errorf("missing configuration file for ovirt cloud provider")
}
oVirtConfig := APIConfig{}
/* defaults */
oVirtConfig.Connection.Username = "admin@internal"
if err := gcfg.ReadInto(&oVirtConfig, config); err != nil {
return nil, err
}
if oVirtConfig.Connection.APIEntry == "" {
return nil, fmt.Errorf("missing ovirt uri in cloud provider configuration")
}
request, err := url.Parse(oVirtConfig.Connection.APIEntry)
if err != nil {
return nil, err
}
request.Path = path.Join(request.Path, "vms")
request.User = url.UserPassword(oVirtConfig.Connection.Username, oVirtConfig.Connection.Password)
request.RawQuery = url.Values{"search": {oVirtConfig.Filters.VmsQuery}}.Encode()
return &Cloud{VmsRequest: request}, nil
}
// Initialize passes a Kubernetes clientBuilder interface to the cloud provider
func (v *Cloud) Initialize(clientBuilder cloudprovider.ControllerClientBuilder, stop <-chan struct{}) {
}
// Clusters returns the list of clusters.
func (v *Cloud) Clusters() (cloudprovider.Clusters, bool) {
return nil, false
}
// ProviderName returns the cloud provider ID.
func (v *Cloud) ProviderName() string {
return ProviderName
}
// HasClusterID returns true if the cluster has a clusterID
func (v *Cloud) HasClusterID() bool {
return true
}
// LoadBalancer returns an implementation of LoadBalancer for oVirt cloud
func (v *Cloud) LoadBalancer() (cloudprovider.LoadBalancer, bool) {
return nil, false
}
// Instances returns an implementation of Instances for oVirt cloud
func (v *Cloud) Instances() (cloudprovider.Instances, bool) {
return v, true
}
// Zones returns an implementation of Zones for oVirt cloud
func (v *Cloud) Zones() (cloudprovider.Zones, bool) {
return nil, false
}
// Routes returns an implementation of Routes for oVirt cloud
func (v *Cloud) Routes() (cloudprovider.Routes, bool) {
return nil, false
}
// NodeAddresses returns the NodeAddresses of the instance with the specified nodeName.
func (v *Cloud) NodeAddresses(ctx context.Context, nodeName types.NodeName) ([]v1.NodeAddress, error) {
name := mapNodeNameToInstanceName(nodeName)
instance, err := v.fetchInstance(name)
if err != nil {
return nil, err
}
var address net.IP
if instance.IPAddress != "" {
address = net.ParseIP(instance.IPAddress)
if address == nil {
return nil, fmt.Errorf("couldn't parse address: %s", instance.IPAddress)
}
} else {
resolved, err := net.LookupIP(name)
if err != nil || len(resolved) < 1 {
return nil, fmt.Errorf("couldn't lookup address: %s", name)
}
address = resolved[0]
}
return []v1.NodeAddress{
{Type: v1.NodeInternalIP, Address: address.String()},
{Type: v1.NodeExternalIP, Address: address.String()},
}, nil
}
// NodeAddressesByProviderID returns the node addresses of an instances with the specified unique providerID
// This method will not be called from the node that is requesting this ID. i.e. metadata service
// and other local methods cannot be used here
func (v *Cloud) NodeAddressesByProviderID(ctx context.Context, providerID string) ([]v1.NodeAddress, error) {
return []v1.NodeAddress{}, cloudprovider.NotImplemented
}
// mapNodeNameToInstanceName maps from a k8s NodeName to an ovirt instance name (the hostname)
// This is a simple string cast
func mapNodeNameToInstanceName(nodeName types.NodeName) string {
return string(nodeName)
}
// InstanceExistsByProviderID returns true if the instance with the given provider id still exists and is running.
// If false is returned with no error, the instance will be immediately deleted by the cloud controller manager.
func (v *Cloud) InstanceExistsByProviderID(ctx context.Context, providerID string) (bool, error) {
return false, cloudprovider.NotImplemented
}
// InstanceShutdownByProviderID returns true if the instance is in safe state to detach volumes
func (v *Cloud) InstanceShutdownByProviderID(ctx context.Context, providerID string) (bool, error) {
return false, cloudprovider.NotImplemented
}
// InstanceID returns the cloud provider ID of the node with the specified NodeName.
func (v *Cloud) InstanceID(ctx context.Context, nodeName types.NodeName) (string, error) {
name := mapNodeNameToInstanceName(nodeName)
instance, err := v.fetchInstance(name)
if err != nil {
return "", err
}
// TODO: define a way to identify the provider instance to complete
// the format <provider_instance_id>/<instance_id>.
return "/" + instance.UUID, err
}
// InstanceTypeByProviderID returns the cloudprovider instance type of the node with the specified unique providerID
// This method will not be called from the node that is requesting this ID. i.e. metadata service
// and other local methods cannot be used here
func (v *Cloud) InstanceTypeByProviderID(ctx context.Context, providerID string) (string, error) {
return "", cloudprovider.NotImplemented
}
// InstanceType returns the type of the specified instance.
func (v *Cloud) InstanceType(ctx context.Context, name types.NodeName) (string, error) {
return "", nil
}
func getInstancesFromXML(body io.Reader) (InstanceMap, error) {
if body == nil {
return nil, fmt.Errorf("ovirt rest-api response body is missing")
}
content, err := ioutil.ReadAll(body)
if err != nil {
return nil, err
}
vmlist := XMLVmsList{}
if err := xml.Unmarshal(content, &vmlist); err != nil {
return nil, err
}
instances := make(InstanceMap)
for _, vm := range vmlist.VM {
// Always return only vms that are up and running
if vm.Hostname != "" && strings.ToLower(vm.State) == "up" {
address := ""
if len(vm.Addresses) > 0 {
address = vm.Addresses[0].Address
}
instances[vm.Hostname] = Instance{
UUID: vm.UUID,
Name: vm.Name,
IPAddress: address,
}
}
}
return instances, nil
}
func (v *Cloud) fetchAllInstances() (InstanceMap, error) {
response, err := http.Get(v.VmsRequest.String())
if err != nil {
return nil, err
}
defer response.Body.Close()
return getInstancesFromXML(response.Body)
}
func (v *Cloud) fetchInstance(name string) (*Instance, error) {
allInstances, err := v.fetchAllInstances()
if err != nil {
return nil, err
}
instance, found := allInstances[name]
if !found {
return nil, fmt.Errorf("cannot find instance: %s", name)
}
return &instance, nil
}
// ListSortedNames returns the list of sorted Ovirt instances name.
func (m *InstanceMap) ListSortedNames() []string {
var names []string
for k := range *m {
names = append(names, k)
}
sort.Strings(names)
return names
}
// CurrentNodeName is implementation of Instances.CurrentNodeName.
func (v *Cloud) CurrentNodeName(ctx context.Context, hostname string) (types.NodeName, error) {
return types.NodeName(hostname), nil
}
// AddSSHKeyToAllInstances is currently not implemented.
func (v *Cloud) AddSSHKeyToAllInstances(ctx context.Context, user string, keyData []byte) error {
return cloudprovider.NotImplemented
}

View File

@ -1,126 +0,0 @@
/*
Copyright 2014 The Kubernetes Authors.
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 ovirt
import (
"io"
"strings"
"testing"
cloudprovider "k8s.io/cloud-provider"
)
func TestOVirtCloudConfiguration(t *testing.T) {
config1 := (io.Reader)(nil)
_, err1 := cloudprovider.GetCloudProvider("ovirt", config1)
if err1 == nil {
t.Fatalf("An error is expected when the configuration is missing")
}
config2 := strings.NewReader("")
_, err2 := cloudprovider.GetCloudProvider("ovirt", config2)
if err2 == nil {
t.Fatalf("An error is expected when the configuration is empty")
}
config3 := strings.NewReader(`
[connection]
`)
_, err3 := cloudprovider.GetCloudProvider("ovirt", config3)
if err3 == nil {
t.Fatalf("An error is expected when the uri is missing")
}
config4 := strings.NewReader(`
[connection]
uri = https://localhost:8443/ovirt-engine/api
`)
_, err4 := cloudprovider.GetCloudProvider("ovirt", config4)
if err4 != nil {
t.Fatalf("Unexpected error creating the provider: %s", err4)
}
}
func TestOVirtCloudXmlParsing(t *testing.T) {
body1 := (io.Reader)(nil)
_, err1 := getInstancesFromXML(body1)
if err1 == nil {
t.Fatalf("An error is expected when body is missing")
}
body2 := strings.NewReader("")
_, err2 := getInstancesFromXML(body2)
if err2 == nil {
t.Fatalf("An error is expected when body is empty")
}
body3 := strings.NewReader(`
<vms>
<vm></vm>
</vms>
`)
instances3, err3 := getInstancesFromXML(body3)
if err3 != nil {
t.Fatalf("Unexpected error listing instances: %s", err3)
}
if len(instances3) > 0 {
t.Fatalf("Unexpected number of instance(s): %d", len(instances3))
}
body4 := strings.NewReader(`
<vms>
<vm>
<status><state>Up</state></status>
<guest_info><fqdn>host1</fqdn></guest_info>
</vm>
<vm>
<!-- empty -->
</vm>
<vm>
<status><state>Up</state></status>
</vm>
<vm>
<status><state>Down</state></status>
<guest_info><fqdn>host2</fqdn></guest_info>
</vm>
<vm>
<status><state>Up</state></status>
<guest_info><fqdn>host3</fqdn></guest_info>
</vm>
</vms>
`)
instances4, err4 := getInstancesFromXML(body4)
if err4 != nil {
t.Fatalf("Unexpected error listing instances: %s", err4)
}
if len(instances4) != 2 {
t.Fatalf("Unexpected number of instance(s): %d", len(instances4))
}
names := instances4.ListSortedNames()
if names[0] != "host1" || names[1] != "host3" {
t.Fatalf("Unexpected instance(s): %s", instances4)
}
}

View File

@ -1,46 +0,0 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
"go_test",
)
go_library(
name = "go_default_library",
srcs = ["photon.go"],
importpath = "k8s.io/kubernetes/pkg/cloudprovider/providers/photon",
deps = [
"//staging/src/k8s.io/api/core/v1:go_default_library",
"//staging/src/k8s.io/apimachinery/pkg/types:go_default_library",
"//staging/src/k8s.io/cloud-provider:go_default_library",
"//staging/src/k8s.io/cloud-provider/node/helpers:go_default_library",
"//vendor/github.com/vmware/photon-controller-go-sdk/photon:go_default_library",
"//vendor/gopkg.in/gcfg.v1:go_default_library",
"//vendor/k8s.io/klog:go_default_library",
],
)
go_test(
name = "go_default_test",
srcs = ["photon_test.go"],
embed = [":go_default_library"],
deps = [
"//staging/src/k8s.io/apimachinery/pkg/types:go_default_library",
"//staging/src/k8s.io/apimachinery/pkg/util/rand:go_default_library",
"//staging/src/k8s.io/cloud-provider:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
)

View File

@ -1,6 +0,0 @@
# See the OWNERS docs at https://go.k8s.io/owners
maintainers:
- luomiao
- kerneltime
- abrarshivani

View File

@ -1,734 +0,0 @@
/*
Copyright 2016 The Kubernetes Authors.
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 version of Photon cloud provider supports the disk interface
// for Photon persistent disk volume plugin. LoadBalancer, Routes, and
// Zones are currently not supported.
// The use of Photon cloud provider requires to start kubelet, kube-apiserver,
// and kube-controller-manager with config flag: '--cloud-provider=photon
// --cloud-config=[path_to_config_file]'. When running multi-node kubernetes
// using docker, the config file should be located inside /etc/kubernetes.
package photon
import (
"bufio"
"context"
"errors"
"fmt"
"io"
"log"
"net"
"os"
"strings"
"github.com/vmware/photon-controller-go-sdk/photon"
"gopkg.in/gcfg.v1"
"k8s.io/api/core/v1"
k8stypes "k8s.io/apimachinery/pkg/types"
cloudprovider "k8s.io/cloud-provider"
nodehelpers "k8s.io/cloud-provider/node/helpers"
"k8s.io/klog"
)
const (
ProviderName = "photon"
DiskSpecKind = "persistent-disk"
MAC_OUI_VC = "00:50:56"
MAC_OUI_ESX = "00:0c:29"
)
// overrideIP indicates if the hostname is overridden by IP address, such as when
// running multi-node kubernetes using docker. In this case the user should set
// overrideIP = true in cloud config file. Default value is false.
var overrideIP = false
var _ cloudprovider.Interface = (*PCCloud)(nil)
var _ cloudprovider.Instances = (*PCCloud)(nil)
var _ cloudprovider.Zones = (*PCCloud)(nil)
// PCCloud is an implementation of the cloud provider interface for Photon Controller.
type PCCloud struct {
cfg *PCConfig
// InstanceID of the server where this PCCloud object is instantiated.
localInstanceID string
// local $HOSTNAME
localHostname string
// hostname from K8S, could be overridden
localK8sHostname string
// Photon project ID. We assume that there is only one Photon Controller project
// in the environment per current Photon Controller deployment methodology.
projID string
cloudprovider.Zone
photonClient *photon.Client
logger *log.Logger
}
type PCConfig struct {
Global struct {
// the Photon Controller endpoint IP address
CloudTarget string `gcfg:"target"`
// Photon Controller project name
Project string `gcfg:"project"`
// when kubelet is started with '--hostname-override=${IP_ADDRESS}', set to true;
// otherwise, set to false.
OverrideIP bool `gcfg:"overrideIP"`
// VM ID for this node
VMID string `gcfg:"vmID"`
// Authentication enabled or not
AuthEnabled bool `gcfg:"authentication"`
}
}
// Disks is interface for manipulation with PhotonController Persistent Disks.
type Disks interface {
// AttachDisk attaches given disk to given node. Current node
// is used when nodeName is empty string.
AttachDisk(ctx context.Context, pdID string, nodeName k8stypes.NodeName) error
// DetachDisk detaches given disk to given node. Current node
// is used when nodeName is empty string.
DetachDisk(ctx context.Context, pdID string, nodeName k8stypes.NodeName) error
// DiskIsAttached checks if a disk is attached to the given node.
DiskIsAttached(ctx context.Context, pdID string, nodeName k8stypes.NodeName) (bool, error)
// DisksAreAttached is a batch function to check if a list of disks are attached
// to the node with the specified NodeName.
DisksAreAttached(ctx context.Context, pdIDs []string, nodeName k8stypes.NodeName) (map[string]bool, error)
// CreateDisk creates a new PD with given properties.
CreateDisk(volumeOptions *VolumeOptions) (pdID string, err error)
// DeleteDisk deletes PD.
DeleteDisk(pdID string) error
}
// VolumeOptions specifies capacity, tags, name and flavorID for a volume.
type VolumeOptions struct {
CapacityGB int
Tags map[string]string
Name string
Flavor string
}
func readConfig(config io.Reader) (PCConfig, error) {
if config == nil {
err := fmt.Errorf("cloud provider config file is missing. Please restart kubelet with --cloud-provider=photon --cloud-config=[path_to_config_file]")
return PCConfig{}, err
}
var cfg PCConfig
err := gcfg.ReadInto(&cfg, config)
return cfg, err
}
func init() {
cloudprovider.RegisterCloudProvider(ProviderName, func(config io.Reader) (cloudprovider.Interface, error) {
cfg, err := readConfig(config)
if err != nil {
klog.Errorf("Photon Cloud Provider: failed to read in cloud provider config file. Error[%v]", err)
return nil, err
}
return newPCCloud(cfg)
})
}
// Retrieve the Photon VM ID from the Photon Controller endpoint based on the node name
func getVMIDbyNodename(pc *PCCloud, nodeName string) (string, error) {
photonClient, err := getPhotonClient(pc)
if err != nil {
klog.Errorf("Photon Cloud Provider: Failed to get photon client for getVMIDbyNodename, error: [%v]", err)
return "", err
}
vmList, err := photonClient.Projects.GetVMs(pc.projID, nil)
if err != nil {
klog.Errorf("Photon Cloud Provider: Failed to GetVMs from project %s with nodeName %s, error: [%v]", pc.projID, nodeName, err)
return "", err
}
for _, vm := range vmList.Items {
if vm.Name == nodeName {
return vm.ID, nil
}
}
return "", fmt.Errorf("No matching started VM is found with name %s", nodeName)
}
// Retrieve the Photon VM ID from the Photon Controller endpoint based on the IP address
func getVMIDbyIP(pc *PCCloud, IPAddress string) (string, error) {
photonClient, err := getPhotonClient(pc)
if err != nil {
klog.Errorf("Photon Cloud Provider: Failed to get photon client for getVMIDbyNodename, error: [%v]", err)
return "", err
}
vmList, err := photonClient.Projects.GetVMs(pc.projID, nil)
if err != nil {
klog.Errorf("Photon Cloud Provider: Failed to GetVMs for project %s. error: [%v]", pc.projID, err)
return "", err
}
for _, vm := range vmList.Items {
task, err := photonClient.VMs.GetNetworks(vm.ID)
if err != nil {
klog.Warningf("Photon Cloud Provider: GetNetworks failed for vm.ID %s, error [%v]", vm.ID, err)
} else {
task, err = photonClient.Tasks.Wait(task.ID)
if err != nil {
klog.Warningf("Photon Cloud Provider: Wait task for GetNetworks failed for vm.ID %s, error [%v]", vm.ID, err)
} else {
networkConnections := task.ResourceProperties.(map[string]interface{})
networks := networkConnections["networkConnections"].([]interface{})
for _, nt := range networks {
network := nt.(map[string]interface{})
if val, ok := network["ipAddress"]; ok && val != nil {
ipAddr := val.(string)
if ipAddr == IPAddress {
return vm.ID, nil
}
}
}
}
}
}
return "", fmt.Errorf("No matching VM is found with IP %s", IPAddress)
}
func getPhotonClient(pc *PCCloud) (*photon.Client, error) {
var err error
if len(pc.cfg.Global.CloudTarget) == 0 {
return nil, fmt.Errorf("Photon Controller endpoint was not specified")
}
options := &photon.ClientOptions{
IgnoreCertificate: true,
}
pc.photonClient = photon.NewClient(pc.cfg.Global.CloudTarget, options, pc.logger)
if pc.cfg.Global.AuthEnabled == true {
// work around before metadata is available
file, err := os.Open("/etc/kubernetes/pc_login_info")
if err != nil {
klog.Errorf("Photon Cloud Provider: Authentication is enabled but found no username/password at /etc/kubernetes/pc_login_info. Error[%v]", err)
return nil, err
}
defer file.Close()
scanner := bufio.NewScanner(file)
if !scanner.Scan() {
klog.Error("Photon Cloud Provider: Empty username inside /etc/kubernetes/pc_login_info.")
return nil, fmt.Errorf("Failed to create authentication enabled client with invalid username")
}
username := scanner.Text()
if !scanner.Scan() {
klog.Error("Photon Cloud Provider: Empty password set inside /etc/kubernetes/pc_login_info.")
return nil, fmt.Errorf("Failed to create authentication enabled client with invalid password")
}
password := scanner.Text()
tokenOptions, err := pc.photonClient.Auth.GetTokensByPassword(username, password)
if err != nil {
klog.Error("Photon Cloud Provider: failed to get tokens by password")
return nil, err
}
options = &photon.ClientOptions{
IgnoreCertificate: true,
TokenOptions: &photon.TokenOptions{
AccessToken: tokenOptions.AccessToken,
},
}
pc.photonClient = photon.NewClient(pc.cfg.Global.CloudTarget, options, pc.logger)
}
status, err := pc.photonClient.Status.Get()
if err != nil {
klog.Errorf("Photon Cloud Provider: new client creation failed. Error[%v]", err)
return nil, err
}
klog.V(2).Infof("Photon Cloud Provider: Status of the new photon controller client: %v", status)
return pc.photonClient, nil
}
func newPCCloud(cfg PCConfig) (*PCCloud, error) {
projID := cfg.Global.Project
vmID := cfg.Global.VMID
// Get local hostname
hostname, err := os.Hostname()
if err != nil {
klog.Errorf("Photon Cloud Provider: get hostname failed. Error[%v]", err)
return nil, err
}
pc := PCCloud{
cfg: &cfg,
localInstanceID: vmID,
localHostname: hostname,
localK8sHostname: "",
projID: projID,
}
overrideIP = cfg.Global.OverrideIP
return &pc, nil
}
// Initialize passes a Kubernetes clientBuilder interface to the cloud provider
func (pc *PCCloud) Initialize(clientBuilder cloudprovider.ControllerClientBuilder, stop <-chan struct{}) {
}
// Instances returns an implementation of Instances for Photon Controller.
func (pc *PCCloud) Instances() (cloudprovider.Instances, bool) {
return pc, true
}
// List is an implementation of Instances.List.
func (pc *PCCloud) List(filter string) ([]k8stypes.NodeName, error) {
return nil, nil
}
// NodeAddresses is an implementation of Instances.NodeAddresses.
func (pc *PCCloud) NodeAddresses(ctx context.Context, nodeName k8stypes.NodeName) ([]v1.NodeAddress, error) {
nodeAddrs := []v1.NodeAddress{}
name := string(nodeName)
if name == pc.localK8sHostname {
ifaces, err := net.Interfaces()
if err != nil {
klog.Errorf("Photon Cloud Provider: net.Interfaces() failed for NodeAddresses. Error[%v]", err)
return nodeAddrs, err
}
for _, i := range ifaces {
addrs, err := i.Addrs()
if err != nil {
klog.Warningf("Photon Cloud Provider: Failed to extract addresses for NodeAddresses. Error[%v]", err)
} else {
for _, addr := range addrs {
if ipnet, ok := addr.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
// Filter external IP by MAC address OUIs from vCenter and from ESX
if strings.HasPrefix(i.HardwareAddr.String(), MAC_OUI_VC) ||
strings.HasPrefix(i.HardwareAddr.String(), MAC_OUI_ESX) {
nodehelpers.AddToNodeAddresses(&nodeAddrs,
v1.NodeAddress{
Type: v1.NodeExternalIP,
Address: ipnet.IP.String(),
},
)
} else {
nodehelpers.AddToNodeAddresses(&nodeAddrs,
v1.NodeAddress{
Type: v1.NodeInternalIP,
Address: ipnet.IP.String(),
},
)
}
}
}
}
}
}
return nodeAddrs, nil
}
// Inquiring IP addresses from photon controller endpoint only for a node other than this node.
// This is assumed to be done by master only.
vmID, err := getInstanceID(pc, name)
if err != nil {
klog.Errorf("Photon Cloud Provider: getInstanceID failed for NodeAddresses. Error[%v]", err)
return nodeAddrs, err
}
photonClient, err := getPhotonClient(pc)
if err != nil {
klog.Errorf("Photon Cloud Provider: Failed to get photon client for NodeAddresses, error: [%v]", err)
return nodeAddrs, err
}
// Retrieve the Photon VM's IP addresses from the Photon Controller endpoint based on the VM ID
vmList, err := photonClient.Projects.GetVMs(pc.projID, nil)
if err != nil {
klog.Errorf("Photon Cloud Provider: Failed to GetVMs for project %s. Error[%v]", pc.projID, err)
return nodeAddrs, err
}
for _, vm := range vmList.Items {
if vm.ID == vmID {
task, err := photonClient.VMs.GetNetworks(vm.ID)
if err != nil {
klog.Errorf("Photon Cloud Provider: GetNetworks failed for node %s with vm.ID %s. Error[%v]", name, vm.ID, err)
return nodeAddrs, err
} else {
task, err = photonClient.Tasks.Wait(task.ID)
if err != nil {
klog.Errorf("Photon Cloud Provider: Wait task for GetNetworks failed for node %s with vm.ID %s. Error[%v]", name, vm.ID, err)
return nodeAddrs, err
} else {
networkConnections := task.ResourceProperties.(map[string]interface{})
networks := networkConnections["networkConnections"].([]interface{})
for _, nt := range networks {
ipAddr := "-"
macAddr := "-"
network := nt.(map[string]interface{})
if val, ok := network["ipAddress"]; ok && val != nil {
ipAddr = val.(string)
}
if val, ok := network["macAddress"]; ok && val != nil {
macAddr = val.(string)
}
if ipAddr != "-" {
if strings.HasPrefix(macAddr, MAC_OUI_VC) ||
strings.HasPrefix(macAddr, MAC_OUI_ESX) {
nodehelpers.AddToNodeAddresses(&nodeAddrs,
v1.NodeAddress{
Type: v1.NodeExternalIP,
Address: ipAddr,
},
)
} else {
nodehelpers.AddToNodeAddresses(&nodeAddrs,
v1.NodeAddress{
Type: v1.NodeInternalIP,
Address: ipAddr,
},
)
}
}
}
return nodeAddrs, nil
}
}
}
}
klog.Errorf("Failed to find the node %s from Photon Controller endpoint", name)
return nodeAddrs, fmt.Errorf("Failed to find the node %s from Photon Controller endpoint", name)
}
// NodeAddressesByProviderID returns the node addresses of an instances with the specified unique providerID
// This method will not be called from the node that is requesting this ID. i.e. metadata service
// and other local methods cannot be used here
func (pc *PCCloud) NodeAddressesByProviderID(ctx context.Context, providerID string) ([]v1.NodeAddress, error) {
return []v1.NodeAddress{}, cloudprovider.NotImplemented
}
func (pc *PCCloud) AddSSHKeyToAllInstances(ctx context.Context, user string, keyData []byte) error {
return cloudprovider.NotImplemented
}
func (pc *PCCloud) CurrentNodeName(ctx context.Context, hostname string) (k8stypes.NodeName, error) {
pc.localK8sHostname = hostname
return k8stypes.NodeName(hostname), nil
}
func getInstanceID(pc *PCCloud, name string) (string, error) {
var vmID string
var err error
if overrideIP == true {
vmID, err = getVMIDbyIP(pc, name)
} else {
vmID, err = getVMIDbyNodename(pc, name)
}
if err != nil {
return "", err
}
if vmID == "" {
err = cloudprovider.InstanceNotFound
}
return vmID, err
}
// InstanceExistsByProviderID returns true if the instance with the given provider id still exists and is running.
// If false is returned with no error, the instance will be immediately deleted by the cloud controller manager.
func (pc *PCCloud) InstanceExistsByProviderID(ctx context.Context, providerID string) (bool, error) {
return false, cloudprovider.NotImplemented
}
// InstanceShutdownByProviderID returns true if the instance is in safe state to detach volumes
func (pc *PCCloud) InstanceShutdownByProviderID(ctx context.Context, providerID string) (bool, error) {
return false, cloudprovider.NotImplemented
}
// InstanceID returns the cloud provider ID of the specified instance.
func (pc *PCCloud) InstanceID(ctx context.Context, nodeName k8stypes.NodeName) (string, error) {
name := string(nodeName)
if name == pc.localK8sHostname {
return pc.localInstanceID, nil
}
// We assume only master need to get InstanceID of a node other than itself
id, err := getInstanceID(pc, name)
if err != nil {
klog.Errorf("Photon Cloud Provider: getInstanceID failed for InstanceID. Error[%v]", err)
}
return id, err
}
// InstanceTypeByProviderID returns the cloudprovider instance type of the node with the specified unique providerID
// This method will not be called from the node that is requesting this ID. i.e. metadata service
// and other local methods cannot be used here
func (pc *PCCloud) InstanceTypeByProviderID(ctx context.Context, providerID string) (string, error) {
return "", cloudprovider.NotImplemented
}
func (pc *PCCloud) InstanceType(ctx context.Context, nodeName k8stypes.NodeName) (string, error) {
return "", nil
}
func (pc *PCCloud) Clusters() (cloudprovider.Clusters, bool) {
return nil, true
}
// ProviderName returns the cloud provider ID.
func (pc *PCCloud) ProviderName() string {
return ProviderName
}
// LoadBalancer returns an implementation of LoadBalancer for Photon Controller.
func (pc *PCCloud) LoadBalancer() (cloudprovider.LoadBalancer, bool) {
return nil, false
}
// Zones returns an implementation of Zones for Photon Controller.
func (pc *PCCloud) Zones() (cloudprovider.Zones, bool) {
return pc, true
}
func (pc *PCCloud) GetZone(ctx context.Context) (cloudprovider.Zone, error) {
return pc.Zone, nil
}
// GetZoneByProviderID implements Zones.GetZoneByProviderID
// This is particularly useful in external cloud providers where the kubelet
// does not initialize node data.
func (pc *PCCloud) GetZoneByProviderID(ctx context.Context, providerID string) (cloudprovider.Zone, error) {
return cloudprovider.Zone{}, errors.New("GetZoneByProviderID not implemented")
}
// GetZoneByNodeName implements Zones.GetZoneByNodeName
// This is particularly useful in external cloud providers where the kubelet
// does not initialize node data.
func (pc *PCCloud) GetZoneByNodeName(ctx context.Context, nodeName k8stypes.NodeName) (cloudprovider.Zone, error) {
return cloudprovider.Zone{}, errors.New("GetZoneByNodeName not imeplemented")
}
// Routes returns a false since the interface is not supported for photon controller.
func (pc *PCCloud) Routes() (cloudprovider.Routes, bool) {
return nil, false
}
// HasClusterID returns true if the cluster has a clusterID
func (pc *PCCloud) HasClusterID() bool {
return true
}
// AttachDisk attaches given virtual disk volume to the compute running kubelet.
func (pc *PCCloud) AttachDisk(ctx context.Context, pdID string, nodeName k8stypes.NodeName) error {
photonClient, err := getPhotonClient(pc)
if err != nil {
klog.Errorf("Photon Cloud Provider: Failed to get photon client for AttachDisk, error: [%v]", err)
return err
}
operation := &photon.VmDiskOperation{
DiskID: pdID,
}
vmID, err := pc.InstanceID(ctx, nodeName)
if err != nil {
klog.Errorf("Photon Cloud Provider: pc.InstanceID failed for AttachDisk. Error[%v]", err)
return err
}
task, err := photonClient.VMs.AttachDisk(vmID, operation)
if err != nil {
klog.Errorf("Photon Cloud Provider: Failed to attach disk with pdID %s. Error[%v]", pdID, err)
return err
}
_, err = photonClient.Tasks.Wait(task.ID)
if err != nil {
klog.Errorf("Photon Cloud Provider: Failed to wait for task to attach disk with pdID %s. Error[%v]", pdID, err)
return err
}
return nil
}
// Detaches given virtual disk volume from the compute running kubelet.
func (pc *PCCloud) DetachDisk(ctx context.Context, pdID string, nodeName k8stypes.NodeName) error {
photonClient, err := getPhotonClient(pc)
if err != nil {
klog.Errorf("Photon Cloud Provider: Failed to get photon client for DetachDisk, error: [%v]", err)
return err
}
operation := &photon.VmDiskOperation{
DiskID: pdID,
}
vmID, err := pc.InstanceID(ctx, nodeName)
if err != nil {
klog.Errorf("Photon Cloud Provider: pc.InstanceID failed for DetachDisk. Error[%v]", err)
return err
}
task, err := photonClient.VMs.DetachDisk(vmID, operation)
if err != nil {
klog.Errorf("Photon Cloud Provider: Failed to detach disk with pdID %s. Error[%v]", pdID, err)
return err
}
_, err = photonClient.Tasks.Wait(task.ID)
if err != nil {
klog.Errorf("Photon Cloud Provider: Failed to wait for task to detach disk with pdID %s. Error[%v]", pdID, err)
return err
}
return nil
}
// DiskIsAttached returns if disk is attached to the VM using controllers supported by the plugin.
func (pc *PCCloud) DiskIsAttached(ctx context.Context, pdID string, nodeName k8stypes.NodeName) (bool, error) {
photonClient, err := getPhotonClient(pc)
if err != nil {
klog.Errorf("Photon Cloud Provider: Failed to get photon client for DiskIsAttached, error: [%v]", err)
return false, err
}
disk, err := photonClient.Disks.Get(pdID)
if err != nil {
klog.Errorf("Photon Cloud Provider: Failed to Get disk with pdID %s. Error[%v]", pdID, err)
return false, err
}
vmID, err := pc.InstanceID(ctx, nodeName)
if err == cloudprovider.InstanceNotFound {
klog.Infof("Instance %q does not exist, disk %s will be detached automatically.", nodeName, pdID)
return false, nil
}
if err != nil {
klog.Errorf("Photon Cloud Provider: pc.InstanceID failed for DiskIsAttached. Error[%v]", err)
return false, err
}
for _, vm := range disk.VMs {
if vm == vmID {
return true, nil
}
}
return false, nil
}
// DisksAreAttached returns if disks are attached to the VM using controllers supported by the plugin.
func (pc *PCCloud) DisksAreAttached(ctx context.Context, pdIDs []string, nodeName k8stypes.NodeName) (map[string]bool, error) {
attached := make(map[string]bool)
photonClient, err := getPhotonClient(pc)
if err != nil {
klog.Errorf("Photon Cloud Provider: Failed to get photon client for DisksAreAttached, error: [%v]", err)
return attached, err
}
for _, pdID := range pdIDs {
attached[pdID] = false
}
vmID, err := pc.InstanceID(ctx, nodeName)
if err == cloudprovider.InstanceNotFound {
klog.Infof("Instance %q does not exist, its disks will be detached automatically.", nodeName)
// make all the disks as detached.
return attached, nil
}
if err != nil {
klog.Errorf("Photon Cloud Provider: pc.InstanceID failed for DiskIsAttached. Error[%v]", err)
return attached, err
}
for _, pdID := range pdIDs {
disk, err := photonClient.Disks.Get(pdID)
if err != nil {
klog.Warningf("Photon Cloud Provider: failed to get VMs for persistent disk %s, err [%v]", pdID, err)
} else {
for _, vm := range disk.VMs {
if vm == vmID {
attached[pdID] = true
}
}
}
}
return attached, nil
}
// Create a volume of given size (in GB).
func (pc *PCCloud) CreateDisk(volumeOptions *VolumeOptions) (pdID string, err error) {
photonClient, err := getPhotonClient(pc)
if err != nil {
klog.Errorf("Photon Cloud Provider: Failed to get photon client for CreateDisk, error: [%v]", err)
return "", err
}
diskSpec := photon.DiskCreateSpec{}
diskSpec.Name = volumeOptions.Name
diskSpec.Flavor = volumeOptions.Flavor
diskSpec.CapacityGB = volumeOptions.CapacityGB
diskSpec.Kind = DiskSpecKind
task, err := photonClient.Projects.CreateDisk(pc.projID, &diskSpec)
if err != nil {
klog.Errorf("Photon Cloud Provider: Failed to CreateDisk. Error[%v]", err)
return "", err
}
waitTask, err := photonClient.Tasks.Wait(task.ID)
if err != nil {
klog.Errorf("Photon Cloud Provider: Failed to wait for task to CreateDisk. Error[%v]", err)
return "", err
}
return waitTask.Entity.ID, nil
}
// DeleteDisk deletes a volume given volume name.
func (pc *PCCloud) DeleteDisk(pdID string) error {
photonClient, err := getPhotonClient(pc)
if err != nil {
klog.Errorf("Photon Cloud Provider: Failed to get photon client for DeleteDisk, error: [%v]", err)
return err
}
task, err := photonClient.Disks.Delete(pdID)
if err != nil {
klog.Errorf("Photon Cloud Provider: Failed to DeleteDisk. Error[%v]", err)
return err
}
_, err = photonClient.Tasks.Wait(task.ID)
if err != nil {
klog.Errorf("Photon Cloud Provider: Failed to wait for task to DeleteDisk. Error[%v]", err)
return err
}
return nil
}

View File

@ -1,202 +0,0 @@
/*
Copyright 2016 The Kubernetes Authors.
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 photon
import (
"context"
"log"
"os"
"strconv"
"strings"
"testing"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/rand"
cloudprovider "k8s.io/cloud-provider"
)
func configFromEnv() (TestVM string, TestFlavor string, cfg PCConfig, ok bool) {
var AuthEnabled bool
var OverrideIP bool
var err error
cfg.Global.CloudTarget = os.Getenv("PHOTON_TARGET")
cfg.Global.Project = os.Getenv("PHOTON_PROJECT")
cfg.Global.VMID = os.Getenv("PHOTON_VMID")
if os.Getenv("PHOTON_AUTH_ENABLED") != "" {
AuthEnabled, err = strconv.ParseBool(os.Getenv("PHOTON_AUTH_ENABLED"))
} else {
AuthEnabled = false
}
if err != nil {
log.Fatal(err)
}
cfg.Global.AuthEnabled = AuthEnabled
if os.Getenv("PHOTON_OVERRIDE_IP") != "" {
OverrideIP, err = strconv.ParseBool(os.Getenv("PHOTON_OVERRIDE_IP"))
} else {
OverrideIP = false
}
if err != nil {
log.Fatal(err)
}
cfg.Global.OverrideIP = OverrideIP
TestVM = os.Getenv("PHOTON_TEST_VM")
if os.Getenv("PHOTON_TEST_FLAVOR") != "" {
TestFlavor = os.Getenv("PHOTON_TEST_FLAVOR")
} else {
TestFlavor = ""
}
if err != nil {
log.Fatal(err)
}
ok = (cfg.Global.CloudTarget != "" &&
cfg.Global.Project != "" &&
cfg.Global.VMID != "" &&
TestVM != "")
return
}
func TestReadConfig(t *testing.T) {
_, err := readConfig(nil)
if err == nil {
t.Errorf("Should fail when no config is provided: %s", err)
}
cfg, err := readConfig(strings.NewReader(`
[Global]
target = 0.0.0.0
project = project
overrideIP = true
vmID = vmid
authentication = false
`))
if err != nil {
t.Fatalf("Should succeed when a valid config is provided: %s", err)
}
if cfg.Global.CloudTarget != "0.0.0.0" {
t.Errorf("incorrect photon target ip: %s", cfg.Global.CloudTarget)
}
if cfg.Global.Project != "project" {
t.Errorf("incorrect project: %s", cfg.Global.Project)
}
if cfg.Global.VMID != "vmid" {
t.Errorf("incorrect vmid: %s", cfg.Global.VMID)
}
}
func TestNewPCCloud(t *testing.T) {
_, _, cfg, ok := configFromEnv()
if !ok {
t.Skipf("No config found in environment")
}
_, err := newPCCloud(cfg)
if err != nil {
t.Fatalf("Failed to create new Photon client: %s", err)
}
}
func TestInstances(t *testing.T) {
testVM, _, cfg, ok := configFromEnv()
if !ok {
t.Skipf("No config found in environment")
}
NodeName := types.NodeName(testVM)
pc, err := newPCCloud(cfg)
if err != nil {
t.Fatalf("Failed to create new Photon client: %s", err)
}
i, ok := pc.Instances()
if !ok {
t.Fatalf("Instances() returned false")
}
nonExistingVM := types.NodeName(rand.String(15))
instanceId, err := i.InstanceID(context.TODO(), NodeName)
if err != nil {
t.Fatalf("Instances.InstanceID(%s) failed: %s", testVM, err)
}
t.Logf("Found InstanceID(%s) = %s\n", testVM, instanceId)
_, err = i.InstanceID(context.TODO(), nonExistingVM)
if err == cloudprovider.InstanceNotFound {
t.Logf("VM %s was not found as expected\n", nonExistingVM)
} else if err == nil {
t.Fatalf("Instances.InstanceID did not fail as expected, VM %s was found", nonExistingVM)
} else {
t.Fatalf("Instances.InstanceID did not fail as expected, err: %v", err)
}
addrs, err := i.NodeAddresses(context.TODO(), NodeName)
if err != nil {
t.Fatalf("Instances.NodeAddresses(%s) failed: %s", testVM, err)
}
t.Logf("Found NodeAddresses(%s) = %s\n", testVM, addrs)
}
func TestVolumes(t *testing.T) {
testVM, testFlavor, cfg, ok := configFromEnv()
if !ok {
t.Skipf("No config found in environment")
}
pc, err := newPCCloud(cfg)
if err != nil {
t.Fatalf("Failed to create new Photon client: %s", err)
}
NodeName := types.NodeName(testVM)
volumeOptions := &VolumeOptions{
CapacityGB: 2,
Tags: nil,
Name: "kubernetes-test-volume-" + rand.String(10),
Flavor: testFlavor}
pdID, err := pc.CreateDisk(volumeOptions)
if err != nil {
t.Fatalf("Cannot create a Photon persistent disk: %v", err)
}
err = pc.AttachDisk(context.TODO(), pdID, NodeName)
if err != nil {
t.Fatalf("Cannot attach persistent disk(%s) to VM(%s): %v", pdID, testVM, err)
}
_, err = pc.DiskIsAttached(context.TODO(), pdID, NodeName)
if err != nil {
t.Fatalf("Cannot attach persistent disk(%s) to VM(%s): %v", pdID, testVM, err)
}
err = pc.DetachDisk(context.TODO(), pdID, NodeName)
if err != nil {
t.Fatalf("Cannot detach persisten disk(%s) from VM(%s): %v", pdID, testVM, err)
}
err = pc.DeleteDisk(pdID)
if err != nil {
t.Fatalf("Cannot delete persisten disk(%s): %v", pdID, err)
}
}

View File

@ -18,10 +18,7 @@ package cloudprovider
import (
// Cloud providers
_ "k8s.io/kubernetes/pkg/cloudprovider/providers/cloudstack"
_ "k8s.io/kubernetes/pkg/cloudprovider/providers/openstack"
_ "k8s.io/kubernetes/pkg/cloudprovider/providers/ovirt"
_ "k8s.io/kubernetes/pkg/cloudprovider/providers/photon"
_ "k8s.io/legacy-cloud-providers/aws"
_ "k8s.io/legacy-cloud-providers/azure"
_ "k8s.io/legacy-cloud-providers/gce"

View File

@ -94,7 +94,6 @@ filegroup(
"//pkg/volume/iscsi:all-srcs",
"//pkg/volume/local:all-srcs",
"//pkg/volume/nfs:all-srcs",
"//pkg/volume/photon_pd:all-srcs",
"//pkg/volume/portworx:all-srcs",
"//pkg/volume/projected:all-srcs",
"//pkg/volume/quobyte:all-srcs",

View File

@ -1,63 +0,0 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
"go_test",
)
go_library(
name = "go_default_library",
srcs = [
"attacher.go",
"photon_pd.go",
"photon_util.go",
],
importpath = "k8s.io/kubernetes/pkg/volume/photon_pd",
deps = [
"//pkg/cloudprovider/providers/photon:go_default_library",
"//pkg/util/mount:go_default_library",
"//pkg/volume:go_default_library",
"//pkg/volume/util:go_default_library",
"//staging/src/k8s.io/api/core/v1:go_default_library",
"//staging/src/k8s.io/apimachinery/pkg/api/resource:go_default_library",
"//staging/src/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library",
"//staging/src/k8s.io/apimachinery/pkg/types:go_default_library",
"//staging/src/k8s.io/cloud-provider:go_default_library",
"//staging/src/k8s.io/cloud-provider/volume/helpers:go_default_library",
"//vendor/k8s.io/klog:go_default_library",
"//vendor/k8s.io/utils/strings:go_default_library",
],
)
go_test(
name = "go_default_test",
srcs = [
"attacher_test.go",
"photon_pd_test.go",
],
embed = [":go_default_library"],
deps = [
"//pkg/cloudprovider/providers/photon:go_default_library",
"//pkg/util/mount:go_default_library",
"//pkg/volume:go_default_library",
"//pkg/volume/testing:go_default_library",
"//staging/src/k8s.io/api/core/v1:go_default_library",
"//staging/src/k8s.io/apimachinery/pkg/types:go_default_library",
"//staging/src/k8s.io/client-go/util/testing:go_default_library",
"//vendor/k8s.io/klog:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
)

View File

@ -1,6 +0,0 @@
# See the OWNERS docs at https://go.k8s.io/owners
maintainers:
- luomiao
- kerneltime
- abrarshivani

View File

@ -1,317 +0,0 @@
/*
Copyright 2016 The Kubernetes Authors.
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 photon_pd
import (
"context"
"fmt"
"os"
"path"
"path/filepath"
"strings"
"time"
"k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/klog"
"k8s.io/kubernetes/pkg/cloudprovider/providers/photon"
"k8s.io/kubernetes/pkg/util/mount"
"k8s.io/kubernetes/pkg/volume"
volumeutil "k8s.io/kubernetes/pkg/volume/util"
)
type photonPersistentDiskAttacher struct {
host volume.VolumeHost
photonDisks photon.Disks
}
var _ volume.Attacher = &photonPersistentDiskAttacher{}
var _ volume.DeviceMounter = &photonPersistentDiskAttacher{}
var _ volume.AttachableVolumePlugin = &photonPersistentDiskPlugin{}
var _ volume.DeviceMountableVolumePlugin = &photonPersistentDiskPlugin{}
func (plugin *photonPersistentDiskPlugin) NewAttacher() (volume.Attacher, error) {
photonCloud, err := getCloudProvider(plugin.host.GetCloudProvider())
if err != nil {
klog.Errorf("Photon Controller attacher: NewAttacher failed to get cloud provider")
return nil, err
}
return &photonPersistentDiskAttacher{
host: plugin.host,
photonDisks: photonCloud,
}, nil
}
func (plugin *photonPersistentDiskPlugin) NewDeviceMounter() (volume.DeviceMounter, error) {
return plugin.NewAttacher()
}
// Attaches the volume specified by the given spec to the given host.
// On success, returns the device path where the device was attached on the
// node.
// Callers are responsible for retryinging on failure.
// Callers are responsible for thread safety between concurrent attach and
// detach operations.
func (attacher *photonPersistentDiskAttacher) Attach(spec *volume.Spec, nodeName types.NodeName) (string, error) {
hostName := string(nodeName)
volumeSource, _, err := getVolumeSource(spec)
if err != nil {
klog.Errorf("Photon Controller attacher: Attach failed to get volume source")
return "", err
}
attached, err := attacher.photonDisks.DiskIsAttached(context.TODO(), volumeSource.PdID, nodeName)
if err != nil {
klog.Warningf("Photon Controller: couldn't check if disk is Attached for host %s, will try attach disk: %+v", hostName, err)
attached = false
}
if !attached {
klog.V(4).Infof("Photon Controller: Attach disk called for host %s", hostName)
err = attacher.photonDisks.AttachDisk(context.TODO(), volumeSource.PdID, nodeName)
if err != nil {
klog.Errorf("Error attaching volume %q to node %q: %+v", volumeSource.PdID, nodeName, err)
return "", err
}
}
PdidWithNoHypens := strings.Replace(volumeSource.PdID, "-", "", -1)
return filepath.Join(diskByIDPath, diskPhotonPrefix+PdidWithNoHypens), nil
}
func (attacher *photonPersistentDiskAttacher) VolumesAreAttached(specs []*volume.Spec, nodeName types.NodeName) (map[*volume.Spec]bool, error) {
volumesAttachedCheck := make(map[*volume.Spec]bool)
volumeSpecMap := make(map[string]*volume.Spec)
pdIDList := []string{}
for _, spec := range specs {
volumeSource, _, err := getVolumeSource(spec)
if err != nil {
klog.Errorf("Error getting volume (%q) source : %v", spec.Name(), err)
continue
}
pdIDList = append(pdIDList, volumeSource.PdID)
volumesAttachedCheck[spec] = true
volumeSpecMap[volumeSource.PdID] = spec
}
attachedResult, err := attacher.photonDisks.DisksAreAttached(context.TODO(), pdIDList, nodeName)
if err != nil {
klog.Errorf(
"Error checking if volumes (%v) are attached to current node (%q). err=%v",
pdIDList, nodeName, err)
return volumesAttachedCheck, err
}
for pdID, attached := range attachedResult {
if !attached {
spec := volumeSpecMap[pdID]
volumesAttachedCheck[spec] = false
klog.V(2).Infof("VolumesAreAttached: check volume %q (specName: %q) is no longer attached", pdID, spec.Name())
}
}
return volumesAttachedCheck, nil
}
func (attacher *photonPersistentDiskAttacher) WaitForAttach(spec *volume.Spec, devicePath string, _ *v1.Pod, timeout time.Duration) (string, error) {
volumeSource, _, err := getVolumeSource(spec)
if err != nil {
klog.Errorf("Photon Controller attacher: WaitForAttach failed to get volume source")
return "", err
}
if devicePath == "" {
return "", fmt.Errorf("WaitForAttach failed for PD %s: devicePath is empty.", volumeSource.PdID)
}
// scan scsi path to discover the new disk
scsiHostScan()
ticker := time.NewTicker(checkSleepDuration)
defer ticker.Stop()
timer := time.NewTimer(timeout)
defer timer.Stop()
for {
select {
case <-ticker.C:
klog.V(4).Infof("Checking PD %s is attached", volumeSource.PdID)
checkPath, err := verifyDevicePath(devicePath)
if err != nil {
// Log error, if any, and continue checking periodically. See issue #11321
klog.Warningf("Photon Controller attacher: WaitForAttach with devicePath %s Checking PD %s Error verify path", devicePath, volumeSource.PdID)
} else if checkPath != "" {
// A device path has successfully been created for the VMDK
klog.V(4).Infof("Successfully found attached PD %s.", volumeSource.PdID)
// map path with spec.Name()
volName := spec.Name()
realPath, _ := filepath.EvalSymlinks(devicePath)
deviceName := path.Base(realPath)
volNameToDeviceName[volName] = deviceName
return devicePath, nil
}
case <-timer.C:
return "", fmt.Errorf("Could not find attached PD %s. Timeout waiting for mount paths to be created.", volumeSource.PdID)
}
}
}
// GetDeviceMountPath returns a path where the device should
// point which should be bind mounted for individual volumes.
func (attacher *photonPersistentDiskAttacher) GetDeviceMountPath(spec *volume.Spec) (string, error) {
volumeSource, _, err := getVolumeSource(spec)
if err != nil {
klog.Errorf("Photon Controller attacher: GetDeviceMountPath failed to get volume source")
return "", err
}
return makeGlobalPDPath(attacher.host, volumeSource.PdID), nil
}
// GetMountDeviceRefs finds all other references to the device referenced
// by deviceMountPath; returns a list of paths.
func (plugin *photonPersistentDiskPlugin) GetDeviceMountRefs(deviceMountPath string) ([]string, error) {
mounter := plugin.host.GetMounter(plugin.GetPluginName())
return mounter.GetMountRefs(deviceMountPath)
}
// MountDevice mounts device to global mount point.
func (attacher *photonPersistentDiskAttacher) MountDevice(spec *volume.Spec, devicePath string, deviceMountPath string) error {
mounter := attacher.host.GetMounter(photonPersistentDiskPluginName)
notMnt, err := mounter.IsLikelyNotMountPoint(deviceMountPath)
if err != nil {
if os.IsNotExist(err) {
if err := os.MkdirAll(deviceMountPath, 0750); err != nil {
klog.Errorf("Failed to create directory at %#v. err: %s", deviceMountPath, err)
return err
}
notMnt = true
} else {
return err
}
}
volumeSource, _, err := getVolumeSource(spec)
if err != nil {
klog.Errorf("Photon Controller attacher: MountDevice failed to get volume source. err: %s", err)
return err
}
options := []string{}
if notMnt {
diskMounter := volumeutil.NewSafeFormatAndMountFromHost(photonPersistentDiskPluginName, attacher.host)
mountOptions := volumeutil.MountOptionFromSpec(spec)
err = diskMounter.FormatAndMount(devicePath, deviceMountPath, volumeSource.FSType, mountOptions)
if err != nil {
os.Remove(deviceMountPath)
return err
}
klog.V(4).Infof("formatting spec %v devicePath %v deviceMountPath %v fs %v with options %+v", spec.Name(), devicePath, deviceMountPath, volumeSource.FSType, options)
}
return nil
}
type photonPersistentDiskDetacher struct {
mounter mount.Interface
photonDisks photon.Disks
}
var _ volume.Detacher = &photonPersistentDiskDetacher{}
var _ volume.DeviceUnmounter = &photonPersistentDiskDetacher{}
func (plugin *photonPersistentDiskPlugin) NewDetacher() (volume.Detacher, error) {
photonCloud, err := getCloudProvider(plugin.host.GetCloudProvider())
if err != nil {
klog.Errorf("Photon Controller attacher: NewDetacher failed to get cloud provider. err: %s", err)
return nil, err
}
return &photonPersistentDiskDetacher{
mounter: plugin.host.GetMounter(plugin.GetPluginName()),
photonDisks: photonCloud,
}, nil
}
func (plugin *photonPersistentDiskPlugin) NewDeviceUnmounter() (volume.DeviceUnmounter, error) {
return plugin.NewDetacher()
}
// Detach the given device from the given host.
func (detacher *photonPersistentDiskDetacher) Detach(volumeName string, nodeName types.NodeName) error {
hostName := string(nodeName)
pdID := volumeName
attached, err := detacher.photonDisks.DiskIsAttached(context.TODO(), pdID, nodeName)
if err != nil {
// Log error and continue with detach
klog.Errorf(
"Error checking if persistent disk (%q) is already attached to current node (%q). Will continue and try detach anyway. err=%v",
pdID, hostName, err)
}
if err == nil && !attached {
// Volume is already detached from node.
klog.V(4).Infof("detach operation was successful. persistent disk %q is already detached from node %q.", pdID, hostName)
return nil
}
if err := detacher.photonDisks.DetachDisk(context.TODO(), pdID, nodeName); err != nil {
klog.Errorf("Error detaching volume %q: %v", pdID, err)
return err
}
return nil
}
func (detacher *photonPersistentDiskDetacher) WaitForDetach(devicePath string, timeout time.Duration) error {
ticker := time.NewTicker(checkSleepDuration)
defer ticker.Stop()
timer := time.NewTimer(timeout)
defer timer.Stop()
for {
select {
case <-ticker.C:
klog.V(4).Infof("Checking device %q is detached.", devicePath)
if pathExists, err := mount.PathExists(devicePath); err != nil {
return fmt.Errorf("Error checking if device path exists: %v", err)
} else if !pathExists {
return nil
}
case <-timer.C:
return fmt.Errorf("Timeout reached; Device %v is still attached", devicePath)
}
}
}
func (detacher *photonPersistentDiskDetacher) UnmountDevice(deviceMountPath string) error {
return mount.CleanupMountPoint(deviceMountPath, detacher.mounter, false)
}
func (plugin *photonPersistentDiskPlugin) CanAttach(spec *volume.Spec) (bool, error) {
return true, nil
}
func (plugin *photonPersistentDiskPlugin) CanDeviceMount(spec *volume.Spec) (bool, error) {
return true, nil
}

View File

@ -1,330 +0,0 @@
/*
Copyright 2016 The Kubernetes Authors.
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 photon_pd
import (
"context"
"errors"
"testing"
"k8s.io/api/core/v1"
"k8s.io/kubernetes/pkg/cloudprovider/providers/photon"
"k8s.io/kubernetes/pkg/volume"
volumetest "k8s.io/kubernetes/pkg/volume/testing"
"k8s.io/apimachinery/pkg/types"
"k8s.io/klog"
)
func TestGetDeviceName_Volume(t *testing.T) {
plugin := newPlugin()
name := "my-photon-volume"
spec := createVolSpec(name, false)
deviceName, err := plugin.GetVolumeName(spec)
if err != nil {
t.Errorf("GetDeviceName error: %v", err)
}
if deviceName != name {
t.Errorf("GetDeviceName error: expected %s, got %s", name, deviceName)
}
}
func TestGetDeviceName_PersistentVolume(t *testing.T) {
plugin := newPlugin()
name := "my-photon-pv"
spec := createPVSpec(name, true)
deviceName, err := plugin.GetVolumeName(spec)
if err != nil {
t.Errorf("GetDeviceName error: %v", err)
}
if deviceName != name {
t.Errorf("GetDeviceName error: expected %s, got %s", name, deviceName)
}
}
// One testcase for TestAttachDetach table test below
type testcase struct {
name string
// For fake Photon cloud provider:
attach attachCall
detach detachCall
diskIsAttached diskIsAttachedCall
t *testing.T
// Actual test to run
test func(test *testcase) (string, error)
// Expected return of the test
expectedDevice string
expectedError error
}
func TestAttachDetach(t *testing.T) {
diskName := "000-000-000"
nodeName := types.NodeName("instance")
readOnly := false
spec := createVolSpec(diskName, readOnly)
detachError := errors.New("Fake detach error")
diskCheckError := errors.New("Fake DiskIsAttached error")
tests := []testcase{
// Successful Attach call
{
name: "Attach_Positive",
diskIsAttached: diskIsAttachedCall{diskName, nodeName, false, diskCheckError},
attach: attachCall{diskName, nodeName, nil},
test: func(testcase *testcase) (string, error) {
attacher := newAttacher(testcase)
return attacher.Attach(spec, nodeName)
},
expectedDevice: "/dev/disk/by-id/wwn-0x000000000",
},
// Disk is already attached
{
name: "Attach_Positive_AlreadyAttached",
diskIsAttached: diskIsAttachedCall{diskName, nodeName, false, diskCheckError},
attach: attachCall{diskName, nodeName, nil},
test: func(testcase *testcase) (string, error) {
attacher := newAttacher(testcase)
return attacher.Attach(spec, nodeName)
},
expectedDevice: "/dev/disk/by-id/wwn-0x000000000",
},
// Detach succeeds
{
name: "Detach_Positive",
diskIsAttached: diskIsAttachedCall{diskName, nodeName, true, nil},
detach: detachCall{diskName, nodeName, nil},
test: func(testcase *testcase) (string, error) {
detacher := newDetacher(testcase)
return "", detacher.Detach(diskName, nodeName)
},
},
// Disk is already detached
{
name: "Detach_Positive_AlreadyDetached",
diskIsAttached: diskIsAttachedCall{diskName, nodeName, false, nil},
test: func(testcase *testcase) (string, error) {
detacher := newDetacher(testcase)
return "", detacher.Detach(diskName, nodeName)
},
},
// Detach succeeds when DiskIsAttached fails
{
name: "Detach_Positive_CheckFails",
diskIsAttached: diskIsAttachedCall{diskName, nodeName, false, diskCheckError},
detach: detachCall{diskName, nodeName, nil},
test: func(testcase *testcase) (string, error) {
detacher := newDetacher(testcase)
return "", detacher.Detach(diskName, nodeName)
},
},
// Detach fails
{
name: "Detach_Negative",
diskIsAttached: diskIsAttachedCall{diskName, nodeName, false, diskCheckError},
detach: detachCall{diskName, nodeName, detachError},
test: func(testcase *testcase) (string, error) {
detacher := newDetacher(testcase)
return "", detacher.Detach(diskName, nodeName)
},
expectedError: detachError,
},
}
for _, testcase := range tests {
testcase.t = t
device, err := testcase.test(&testcase)
if err != testcase.expectedError {
t.Errorf("%s failed: expected err=%q, got %q", testcase.name, testcase.expectedError.Error(), err.Error())
}
if device != testcase.expectedDevice {
t.Errorf("%s failed: expected device=%q, got %q", testcase.name, testcase.expectedDevice, device)
}
t.Logf("Test %q succeeded", testcase.name)
}
}
// newPlugin creates a new gcePersistentDiskPlugin with fake cloud, NewAttacher
// and NewDetacher won't work.
func newPlugin() *photonPersistentDiskPlugin {
host := volumetest.NewFakeVolumeHost("/tmp", nil, nil)
plugins := ProbeVolumePlugins()
plugin := plugins[0]
plugin.Init(host)
return plugin.(*photonPersistentDiskPlugin)
}
func newAttacher(testcase *testcase) *photonPersistentDiskAttacher {
return &photonPersistentDiskAttacher{
host: nil,
photonDisks: testcase,
}
}
func newDetacher(testcase *testcase) *photonPersistentDiskDetacher {
return &photonPersistentDiskDetacher{
photonDisks: testcase,
}
}
func createVolSpec(name string, readOnly bool) *volume.Spec {
return &volume.Spec{
Volume: &v1.Volume{
VolumeSource: v1.VolumeSource{
PhotonPersistentDisk: &v1.PhotonPersistentDiskVolumeSource{
PdID: name,
},
},
},
}
}
func createPVSpec(name string, readOnly bool) *volume.Spec {
return &volume.Spec{
PersistentVolume: &v1.PersistentVolume{
Spec: v1.PersistentVolumeSpec{
PersistentVolumeSource: v1.PersistentVolumeSource{
PhotonPersistentDisk: &v1.PhotonPersistentDiskVolumeSource{
PdID: name,
},
},
},
},
}
}
// Fake PhotonPD implementation
type attachCall struct {
diskName string
nodeName types.NodeName
ret error
}
type detachCall struct {
diskName string
nodeName types.NodeName
ret error
}
type diskIsAttachedCall struct {
diskName string
nodeName types.NodeName
isAttached bool
ret error
}
func (testcase *testcase) AttachDisk(ctx context.Context, diskName string, nodeName types.NodeName) error {
expected := &testcase.attach
if expected.diskName == "" && expected.nodeName == "" {
// testcase.attach looks uninitialized, test did not expect to call
// AttachDisk
testcase.t.Errorf("Unexpected AttachDisk call!")
return errors.New("Unexpected AttachDisk call!")
}
if expected.diskName != diskName {
testcase.t.Errorf("Unexpected AttachDisk call: expected diskName %s, got %s", expected.diskName, diskName)
return errors.New("Unexpected AttachDisk call: wrong diskName")
}
if expected.nodeName != nodeName {
testcase.t.Errorf("Unexpected AttachDisk call: expected nodeName %s, got %s", expected.nodeName, nodeName)
return errors.New("Unexpected AttachDisk call: wrong nodeName")
}
klog.V(4).Infof("AttachDisk call: %s, %s, returning %v", diskName, nodeName, expected.ret)
return expected.ret
}
func (testcase *testcase) DetachDisk(ctx context.Context, diskName string, nodeName types.NodeName) error {
expected := &testcase.detach
if expected.diskName == "" && expected.nodeName == "" {
// testcase.detach looks uninitialized, test did not expect to call
// DetachDisk
testcase.t.Errorf("Unexpected DetachDisk call!")
return errors.New("Unexpected DetachDisk call!")
}
if expected.diskName != diskName {
testcase.t.Errorf("Unexpected DetachDisk call: expected diskName %s, got %s", expected.diskName, diskName)
return errors.New("Unexpected DetachDisk call: wrong diskName")
}
if expected.nodeName != nodeName {
testcase.t.Errorf("Unexpected DetachDisk call: expected nodeName %s, got %s", expected.nodeName, nodeName)
return errors.New("Unexpected DetachDisk call: wrong nodeName")
}
klog.V(4).Infof("DetachDisk call: %s, %s, returning %v", diskName, nodeName, expected.ret)
return expected.ret
}
func (testcase *testcase) DiskIsAttached(ctx context.Context, diskName string, nodeName types.NodeName) (bool, error) {
expected := &testcase.diskIsAttached
if expected.diskName == "" && expected.nodeName == "" {
// testcase.diskIsAttached looks uninitialized, test did not expect to
// call DiskIsAttached
testcase.t.Errorf("Unexpected DiskIsAttached call!")
return false, errors.New("Unexpected DiskIsAttached call!")
}
if expected.diskName != diskName {
testcase.t.Errorf("Unexpected DiskIsAttached call: expected diskName %s, got %s", expected.diskName, diskName)
return false, errors.New("Unexpected DiskIsAttached call: wrong diskName")
}
if expected.nodeName != nodeName {
testcase.t.Errorf("Unexpected DiskIsAttached call: expected nodeName %s, got %s", expected.nodeName, nodeName)
return false, errors.New("Unexpected DiskIsAttached call: wrong nodeName")
}
klog.V(4).Infof("DiskIsAttached call: %s, %s, returning %v, %v", diskName, nodeName, expected.isAttached, expected.ret)
return expected.isAttached, expected.ret
}
func (testcase *testcase) DisksAreAttached(ctx context.Context, diskNames []string, nodeName types.NodeName) (map[string]bool, error) {
return nil, errors.New("Not implemented")
}
func (testcase *testcase) CreateDisk(volumeOptions *photon.VolumeOptions) (volumeName string, err error) {
return "", errors.New("Not implemented")
}
func (testcase *testcase) DeleteDisk(volumeName string) error {
return errors.New("Not implemented")
}
func (testcase *testcase) GetVolumeLabels(volumeName string) (map[string]string, error) {
return map[string]string{}, errors.New("Not implemented")
}
func (testcase *testcase) GetDiskPath(volumeName string) (string, error) {
return "", errors.New("Not implemented")
}

View File

@ -1,409 +0,0 @@
/*
Copyright 2016 The Kubernetes Authors.
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 photon_pd
import (
"fmt"
"os"
"path/filepath"
"k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/klog"
"k8s.io/kubernetes/pkg/util/mount"
"k8s.io/kubernetes/pkg/volume"
"k8s.io/kubernetes/pkg/volume/util"
utilstrings "k8s.io/utils/strings"
)
// This is the primary entrypoint for volume plugins.
func ProbeVolumePlugins() []volume.VolumePlugin {
return []volume.VolumePlugin{&photonPersistentDiskPlugin{}}
}
type photonPersistentDiskPlugin struct {
host volume.VolumeHost
}
var _ volume.VolumePlugin = &photonPersistentDiskPlugin{}
var _ volume.PersistentVolumePlugin = &photonPersistentDiskPlugin{}
var _ volume.DeletableVolumePlugin = &photonPersistentDiskPlugin{}
var _ volume.ProvisionableVolumePlugin = &photonPersistentDiskPlugin{}
const (
photonPersistentDiskPluginName = "kubernetes.io/photon-pd"
)
func (plugin *photonPersistentDiskPlugin) Init(host volume.VolumeHost) error {
plugin.host = host
return nil
}
func (plugin *photonPersistentDiskPlugin) GetPluginName() string {
return photonPersistentDiskPluginName
}
func (plugin *photonPersistentDiskPlugin) GetVolumeName(spec *volume.Spec) (string, error) {
volumeSource, _, err := getVolumeSource(spec)
if err != nil {
klog.Errorf("Photon volume plugin: GetVolumeName failed to get volume source")
return "", err
}
return volumeSource.PdID, nil
}
func (plugin *photonPersistentDiskPlugin) CanSupport(spec *volume.Spec) bool {
return (spec.PersistentVolume != nil && spec.PersistentVolume.Spec.PhotonPersistentDisk != nil) ||
(spec.Volume != nil && spec.Volume.PhotonPersistentDisk != nil)
}
func (plugin *photonPersistentDiskPlugin) IsMigratedToCSI() bool {
return false
}
func (plugin *photonPersistentDiskPlugin) RequiresRemount() bool {
return false
}
func (plugin *photonPersistentDiskPlugin) SupportsMountOption() bool {
return true
}
func (plugin *photonPersistentDiskPlugin) SupportsBulkVolumeVerification() bool {
return false
}
func (plugin *photonPersistentDiskPlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, _ volume.VolumeOptions) (volume.Mounter, error) {
return plugin.newMounterInternal(spec, pod.UID, &PhotonDiskUtil{}, plugin.host.GetMounter(plugin.GetPluginName()))
}
func (plugin *photonPersistentDiskPlugin) NewUnmounter(volName string, podUID types.UID) (volume.Unmounter, error) {
return plugin.newUnmounterInternal(volName, podUID, &PhotonDiskUtil{}, plugin.host.GetMounter(plugin.GetPluginName()))
}
func (plugin *photonPersistentDiskPlugin) newMounterInternal(spec *volume.Spec, podUID types.UID, manager pdManager, mounter mount.Interface) (volume.Mounter, error) {
vvol, _, err := getVolumeSource(spec)
if err != nil {
klog.Errorf("Photon volume plugin: newMounterInternal failed to get volume source")
return nil, err
}
pdID := vvol.PdID
fsType := vvol.FSType
return &photonPersistentDiskMounter{
photonPersistentDisk: &photonPersistentDisk{
podUID: podUID,
volName: spec.Name(),
pdID: pdID,
manager: manager,
mounter: mounter,
plugin: plugin,
},
fsType: fsType,
diskMounter: util.NewSafeFormatAndMountFromHost(plugin.GetPluginName(), plugin.host),
mountOption: util.MountOptionFromSpec(spec),
}, nil
}
func (plugin *photonPersistentDiskPlugin) newUnmounterInternal(volName string, podUID types.UID, manager pdManager, mounter mount.Interface) (volume.Unmounter, error) {
return &photonPersistentDiskUnmounter{
&photonPersistentDisk{
podUID: podUID,
volName: volName,
manager: manager,
mounter: mounter,
plugin: plugin,
}}, nil
}
func (plugin *photonPersistentDiskPlugin) ConstructVolumeSpec(volumeSpecName, mountPath string) (*volume.Spec, error) {
mounter := plugin.host.GetMounter(plugin.GetPluginName())
pluginMntDir := util.GetPluginMountDir(plugin.host, plugin.GetPluginName())
pdID, err := mounter.GetDeviceNameFromMount(mountPath, pluginMntDir)
if err != nil {
return nil, err
}
photonPersistentDisk := &v1.Volume{
Name: volumeSpecName,
VolumeSource: v1.VolumeSource{
PhotonPersistentDisk: &v1.PhotonPersistentDiskVolumeSource{
PdID: pdID,
},
},
}
return volume.NewSpecFromVolume(photonPersistentDisk), nil
}
// Abstract interface to disk operations.
type pdManager interface {
// Creates a volume
CreateVolume(provisioner *photonPersistentDiskProvisioner) (pdID string, volumeSizeGB int, fstype string, err error)
// Deletes a volume
DeleteVolume(deleter *photonPersistentDiskDeleter) error
}
// photonPersistentDisk volumes are disk resources are attached to the kubelet's host machine and exposed to the pod.
type photonPersistentDisk struct {
volName string
podUID types.UID
// Unique identifier of the volume, used to find the disk resource in the provider.
pdID string
// Filesystem type, optional.
fsType string
// Utility interface that provides API calls to the provider to attach/detach disks.
manager pdManager
// Mounter interface that provides system calls to mount the global path to the pod local path.
mounter mount.Interface
plugin *photonPersistentDiskPlugin
volume.MetricsNil
}
var _ volume.Mounter = &photonPersistentDiskMounter{}
type photonPersistentDiskMounter struct {
*photonPersistentDisk
fsType string
diskMounter *mount.SafeFormatAndMount
mountOption []string
}
func (b *photonPersistentDiskMounter) GetAttributes() volume.Attributes {
return volume.Attributes{
SupportsSELinux: true,
}
}
// Checks prior to mount operations to verify that the required components (binaries, etc.)
// to mount the volume are available on the underlying node.
// If not, it returns an error
func (b *photonPersistentDiskMounter) CanMount() error {
return nil
}
// SetUp attaches the disk and bind mounts to the volume path.
func (b *photonPersistentDiskMounter) SetUp(mounterArgs volume.MounterArgs) error {
return b.SetUpAt(b.GetPath(), mounterArgs)
}
// SetUp attaches the disk and bind mounts to the volume path.
func (b *photonPersistentDiskMounter) SetUpAt(dir string, mounterArgs volume.MounterArgs) error {
klog.V(4).Infof("Photon Persistent Disk setup %s to %s", b.pdID, dir)
// TODO: handle failed mounts here.
notmnt, err := b.mounter.IsLikelyNotMountPoint(dir)
if err != nil && !os.IsNotExist(err) {
klog.Errorf("cannot validate mount point: %s %v", dir, err)
return err
}
if !notmnt {
return nil
}
if err := os.MkdirAll(dir, 0750); err != nil {
klog.Errorf("mkdir failed on disk %s (%v)", dir, err)
return err
}
options := []string{"bind"}
// Perform a bind mount to the full path to allow duplicate mounts of the same PD.
globalPDPath := makeGlobalPDPath(b.plugin.host, b.pdID)
klog.V(4).Infof("attempting to mount %s", dir)
mountOptions := util.JoinMountOptions(options, b.mountOption)
err = b.mounter.Mount(globalPDPath, dir, "", mountOptions)
if err != nil {
notmnt, mntErr := b.mounter.IsLikelyNotMountPoint(dir)
if mntErr != nil {
klog.Errorf("IsLikelyNotMountPoint check failed: %v", mntErr)
return err
}
if !notmnt {
if mntErr = b.mounter.Unmount(dir); mntErr != nil {
klog.Errorf("Failed to unmount: %v", mntErr)
return err
}
notmnt, mntErr := b.mounter.IsLikelyNotMountPoint(dir)
if mntErr != nil {
klog.Errorf("IsLikelyNotMountPoint check failed: %v", mntErr)
return err
}
if !notmnt {
klog.Errorf("%s is still mounted, despite call to unmount(). Will try again next sync loop.", b.GetPath())
return err
}
}
os.Remove(dir)
klog.Errorf("Mount of disk %s failed: %v", dir, err)
return err
}
return nil
}
var _ volume.Unmounter = &photonPersistentDiskUnmounter{}
type photonPersistentDiskUnmounter struct {
*photonPersistentDisk
}
// Unmounts the bind mount, and detaches the disk only if the PD
// resource was the last reference to that disk on the kubelet.
func (c *photonPersistentDiskUnmounter) TearDown() error {
err := c.TearDownAt(c.GetPath())
if err != nil {
return err
}
removeFromScsiSubsystem(c.volName)
return nil
}
// Unmounts the bind mount, and detaches the disk only if the PD
// resource was the last reference to that disk on the kubelet.
func (c *photonPersistentDiskUnmounter) TearDownAt(dir string) error {
return mount.CleanupMountPoint(dir, c.mounter, false)
}
func makeGlobalPDPath(host volume.VolumeHost, devName string) string {
return filepath.Join(host.GetPluginDir(photonPersistentDiskPluginName), util.MountsInGlobalPDPath, devName)
}
func (ppd *photonPersistentDisk) GetPath() string {
name := photonPersistentDiskPluginName
return ppd.plugin.host.GetPodVolumeDir(ppd.podUID, utilstrings.EscapeQualifiedName(name), ppd.volName)
}
// TODO: supporting more access mode for PhotonController persistent disk
func (plugin *photonPersistentDiskPlugin) GetAccessModes() []v1.PersistentVolumeAccessMode {
return []v1.PersistentVolumeAccessMode{
v1.ReadWriteOnce,
}
}
type photonPersistentDiskDeleter struct {
*photonPersistentDisk
}
var _ volume.Deleter = &photonPersistentDiskDeleter{}
func (plugin *photonPersistentDiskPlugin) NewDeleter(spec *volume.Spec) (volume.Deleter, error) {
return plugin.newDeleterInternal(spec, &PhotonDiskUtil{})
}
func (plugin *photonPersistentDiskPlugin) newDeleterInternal(spec *volume.Spec, manager pdManager) (volume.Deleter, error) {
if spec.PersistentVolume != nil && spec.PersistentVolume.Spec.PhotonPersistentDisk == nil {
return nil, fmt.Errorf("spec.PersistentVolumeSource.PhotonPersistentDisk is nil")
}
return &photonPersistentDiskDeleter{
&photonPersistentDisk{
volName: spec.Name(),
pdID: spec.PersistentVolume.Spec.PhotonPersistentDisk.PdID,
manager: manager,
plugin: plugin,
}}, nil
}
func (r *photonPersistentDiskDeleter) Delete() error {
return r.manager.DeleteVolume(r)
}
type photonPersistentDiskProvisioner struct {
*photonPersistentDisk
options volume.VolumeOptions
}
var _ volume.Provisioner = &photonPersistentDiskProvisioner{}
func (plugin *photonPersistentDiskPlugin) NewProvisioner(options volume.VolumeOptions) (volume.Provisioner, error) {
return plugin.newProvisionerInternal(options, &PhotonDiskUtil{})
}
func (plugin *photonPersistentDiskPlugin) newProvisionerInternal(options volume.VolumeOptions, manager pdManager) (volume.Provisioner, error) {
return &photonPersistentDiskProvisioner{
photonPersistentDisk: &photonPersistentDisk{
manager: manager,
plugin: plugin,
},
options: options,
}, nil
}
func (p *photonPersistentDiskProvisioner) Provision(selectedNode *v1.Node, allowedTopologies []v1.TopologySelectorTerm) (*v1.PersistentVolume, error) {
if !util.AccessModesContainedInAll(p.plugin.GetAccessModes(), p.options.PVC.Spec.AccessModes) {
return nil, fmt.Errorf("invalid AccessModes %v: only AccessModes %v are supported", p.options.PVC.Spec.AccessModes, p.plugin.GetAccessModes())
}
if util.CheckPersistentVolumeClaimModeBlock(p.options.PVC) {
return nil, fmt.Errorf("%s does not support block volume provisioning", p.plugin.GetPluginName())
}
pdID, sizeGB, fstype, err := p.manager.CreateVolume(p)
if err != nil {
return nil, err
}
if fstype == "" {
fstype = "ext4"
}
pv := &v1.PersistentVolume{
ObjectMeta: metav1.ObjectMeta{
Name: p.options.PVName,
Labels: map[string]string{},
Annotations: map[string]string{
util.VolumeDynamicallyCreatedByKey: "photon-volume-dynamic-provisioner",
},
},
Spec: v1.PersistentVolumeSpec{
PersistentVolumeReclaimPolicy: p.options.PersistentVolumeReclaimPolicy,
AccessModes: p.options.PVC.Spec.AccessModes,
Capacity: v1.ResourceList{
v1.ResourceName(v1.ResourceStorage): resource.MustParse(fmt.Sprintf("%dGi", sizeGB)),
},
PersistentVolumeSource: v1.PersistentVolumeSource{
PhotonPersistentDisk: &v1.PhotonPersistentDiskVolumeSource{
PdID: pdID,
FSType: fstype,
},
},
MountOptions: p.options.MountOptions,
},
}
if len(p.options.PVC.Spec.AccessModes) == 0 {
pv.Spec.AccessModes = p.plugin.GetAccessModes()
}
return pv, nil
}
func getVolumeSource(
spec *volume.Spec) (*v1.PhotonPersistentDiskVolumeSource, bool, error) {
if spec.Volume != nil && spec.Volume.PhotonPersistentDisk != nil {
return spec.Volume.PhotonPersistentDisk, spec.ReadOnly, nil
} else if spec.PersistentVolume != nil &&
spec.PersistentVolume.Spec.PhotonPersistentDisk != nil {
return spec.PersistentVolume.Spec.PhotonPersistentDisk, spec.ReadOnly, nil
}
return nil, false, fmt.Errorf("Spec does not reference a Photon Controller persistent disk type")
}

View File

@ -1,235 +0,0 @@
/*
Copyright 2014 The Kubernetes Authors.
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 photon_pd
import (
"fmt"
"os"
"path/filepath"
"testing"
"k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/types"
utiltesting "k8s.io/client-go/util/testing"
"k8s.io/kubernetes/pkg/util/mount"
"k8s.io/kubernetes/pkg/volume"
volumetest "k8s.io/kubernetes/pkg/volume/testing"
)
func TestCanSupport(t *testing.T) {
tmpDir, err := utiltesting.MkTmpdir("photonpdTest")
if err != nil {
t.Fatalf("can't make a temp dir: %v", err)
}
defer os.RemoveAll(tmpDir)
plugMgr := volume.VolumePluginMgr{}
plugMgr.InitPlugins(ProbeVolumePlugins(), nil /* prober */, volumetest.NewFakeVolumeHost(tmpDir, nil, nil))
plug, err := plugMgr.FindPluginByName("kubernetes.io/photon-pd")
if err != nil {
t.Errorf("Can't find the plugin by name")
}
if plug.GetPluginName() != "kubernetes.io/photon-pd" {
t.Errorf("Wrong name: %s", plug.GetPluginName())
}
if !plug.CanSupport(&volume.Spec{Volume: &v1.Volume{VolumeSource: v1.VolumeSource{PhotonPersistentDisk: &v1.PhotonPersistentDiskVolumeSource{}}}}) {
t.Errorf("Expected true")
}
if !plug.CanSupport(&volume.Spec{PersistentVolume: &v1.PersistentVolume{Spec: v1.PersistentVolumeSpec{PersistentVolumeSource: v1.PersistentVolumeSource{PhotonPersistentDisk: &v1.PhotonPersistentDiskVolumeSource{}}}}}) {
t.Errorf("Expected true")
}
}
func TestGetAccessModes(t *testing.T) {
tmpDir, err := utiltesting.MkTmpdir("photonpdTest")
if err != nil {
t.Fatalf("can't make a temp dir: %v", err)
}
defer os.RemoveAll(tmpDir)
plugMgr := volume.VolumePluginMgr{}
plugMgr.InitPlugins(ProbeVolumePlugins(), nil /* prober */, volumetest.NewFakeVolumeHost(tmpDir, nil, nil))
plug, err := plugMgr.FindPersistentPluginByName("kubernetes.io/photon-pd")
if err != nil {
t.Errorf("Can't find the plugin by name")
}
if !volumetest.ContainsAccessMode(plug.GetAccessModes(), v1.ReadWriteOnce) {
t.Errorf("Expected to support AccessModeTypes: %s", v1.ReadWriteOnce)
}
if volumetest.ContainsAccessMode(plug.GetAccessModes(), v1.ReadOnlyMany) {
t.Errorf("Expected not to support AccessModeTypes: %s", v1.ReadOnlyMany)
}
}
type fakePDManager struct {
}
func (fake *fakePDManager) CreateVolume(c *photonPersistentDiskProvisioner) (pdID string, volumeSizeGB int, fstype string, err error) {
return "test-photon-pd-id", 10, "ext4", nil
}
func (fake *fakePDManager) DeleteVolume(cd *photonPersistentDiskDeleter) error {
if cd.pdID != "test-photon-pd-id" {
return fmt.Errorf("Deleter got unexpected volume name: %s", cd.pdID)
}
return nil
}
func TestPlugin(t *testing.T) {
tmpDir, err := utiltesting.MkTmpdir("photonpdTest")
if err != nil {
t.Fatalf("can't make a temp dir: %v", err)
}
defer os.RemoveAll(tmpDir)
plugMgr := volume.VolumePluginMgr{}
plugMgr.InitPlugins(ProbeVolumePlugins(), nil /* prober */, volumetest.NewFakeVolumeHost(tmpDir, nil, nil))
plug, err := plugMgr.FindPluginByName("kubernetes.io/photon-pd")
if err != nil {
t.Errorf("Can't find the plugin by name")
}
spec := &v1.Volume{
Name: "vol1",
VolumeSource: v1.VolumeSource{
PhotonPersistentDisk: &v1.PhotonPersistentDiskVolumeSource{
PdID: "pdid",
FSType: "ext4",
},
},
}
fakeManager := &fakePDManager{}
fakeMounter := &mount.FakeMounter{}
mounter, err := plug.(*photonPersistentDiskPlugin).newMounterInternal(volume.NewSpecFromVolume(spec), types.UID("poduid"), fakeManager, fakeMounter)
if err != nil {
t.Errorf("Failed to make a new Mounter: %v", err)
}
if mounter == nil {
t.Errorf("Got a nil Mounter")
}
volPath := filepath.Join(tmpDir, "pods/poduid/volumes/kubernetes.io~photon-pd/vol1")
path := mounter.GetPath()
if path != volPath {
t.Errorf("Got unexpected path: %s", path)
}
if err := mounter.SetUp(volume.MounterArgs{}); err != nil {
t.Errorf("Expected success, got: %v", err)
}
if _, err := os.Stat(path); err != nil {
if os.IsNotExist(err) {
t.Errorf("SetUp() failed, volume path not created: %s", path)
} else {
t.Errorf("SetUp() failed: %v", err)
}
}
fakeManager = &fakePDManager{}
unmounter, err := plug.(*photonPersistentDiskPlugin).newUnmounterInternal("vol1", types.UID("poduid"), fakeManager, fakeMounter)
if err != nil {
t.Errorf("Failed to make a new Unmounter: %v", err)
}
if unmounter == nil {
t.Errorf("Got a nil Unmounter")
}
if err := unmounter.TearDown(); err != nil {
t.Errorf("Expected success, got: %v", err)
}
if _, err := os.Stat(path); err == nil {
t.Errorf("TearDown() failed, volume path still exists: %s", path)
} else if !os.IsNotExist(err) {
t.Errorf("TearDown() failed: %v", err)
}
// Test Provisioner
options := volume.VolumeOptions{
PVC: volumetest.CreateTestPVC("10Gi", []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}),
PersistentVolumeReclaimPolicy: v1.PersistentVolumeReclaimDelete,
}
provisioner, err := plug.(*photonPersistentDiskPlugin).newProvisionerInternal(options, &fakePDManager{})
if err != nil {
t.Fatalf("Error creating new provisioner:%v", err)
}
persistentSpec, err := provisioner.Provision(nil, nil)
if err != nil {
t.Errorf("Provision() failed: %v", err)
}
if persistentSpec.Spec.PersistentVolumeSource.PhotonPersistentDisk.PdID != "test-photon-pd-id" {
t.Errorf("Provision() returned unexpected persistent disk ID: %s", persistentSpec.Spec.PersistentVolumeSource.PhotonPersistentDisk.PdID)
}
cap := persistentSpec.Spec.Capacity[v1.ResourceStorage]
size := cap.Value()
if size != 10*1024*1024*1024 {
t.Errorf("Provision() returned unexpected volume size: %v", size)
}
// Test Deleter
volSpec := &volume.Spec{
PersistentVolume: persistentSpec,
}
deleter, err := plug.(*photonPersistentDiskPlugin).newDeleterInternal(volSpec, &fakePDManager{})
if err != nil {
t.Fatalf("Error creating new deleter:%v", err)
}
err = deleter.Delete()
if err != nil {
t.Errorf("Deleter() failed: %v", err)
}
}
func TestMounterAndUnmounterTypeAssert(t *testing.T) {
tmpDir, err := utiltesting.MkTmpdir("photonpdTest")
if err != nil {
t.Fatalf("can't make a temp dir: %v", err)
}
defer os.RemoveAll(tmpDir)
plugMgr := volume.VolumePluginMgr{}
plugMgr.InitPlugins(ProbeVolumePlugins(), nil /* prober */, volumetest.NewFakeVolumeHost(tmpDir, nil, nil))
plug, err := plugMgr.FindPluginByName("kubernetes.io/photon-pd")
if err != nil {
t.Errorf("Can't find the plugin by name")
}
spec := &v1.Volume{
Name: "vol1",
VolumeSource: v1.VolumeSource{
PhotonPersistentDisk: &v1.PhotonPersistentDiskVolumeSource{
PdID: "pdid",
FSType: "ext4",
},
},
}
mounter, err := plug.(*photonPersistentDiskPlugin).newMounterInternal(volume.NewSpecFromVolume(spec), types.UID("poduid"), &fakePDManager{}, &mount.FakeMounter{})
if err != nil {
t.Fatalf("Error creating new mounter:%v", err)
}
if _, ok := mounter.(volume.Unmounter); ok {
t.Errorf("Volume Mounter can be type-assert to Unmounter")
}
unmounter, err := plug.(*photonPersistentDiskPlugin).newUnmounterInternal("vol1", types.UID("poduid"), &fakePDManager{}, &mount.FakeMounter{})
if err != nil {
t.Fatalf("Error creating new unmounter:%v", err)
}
if _, ok := unmounter.(volume.Mounter); ok {
t.Errorf("Volume Unmounter can be type-assert to Mounter")
}
}

View File

@ -1,157 +0,0 @@
/*
Copyright 2016 The Kubernetes Authors.
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 photon_pd
import (
"errors"
"fmt"
"io/ioutil"
"strings"
"time"
"k8s.io/api/core/v1"
cloudprovider "k8s.io/cloud-provider"
volumehelpers "k8s.io/cloud-provider/volume/helpers"
"k8s.io/klog"
"k8s.io/kubernetes/pkg/cloudprovider/providers/photon"
"k8s.io/kubernetes/pkg/util/mount"
"k8s.io/kubernetes/pkg/volume"
volumeutil "k8s.io/kubernetes/pkg/volume/util"
)
const (
maxRetries = 10
checkSleepDuration = time.Second
diskByIDPath = "/dev/disk/by-id/"
diskPhotonPrefix = "wwn-0x"
)
var ErrProbeVolume = errors.New("Error scanning attached volumes")
// volNameToDeviceName is a mapping between spec.Name from detacher
// and the device name inside scsi path. Once pvscsi controller is
// supported, this won't be needed.
var volNameToDeviceName = make(map[string]string)
type PhotonDiskUtil struct{}
func removeFromScsiSubsystem(volName string) {
// TODO: if using pvscsi controller, this won't be needed
deviceName := volNameToDeviceName[volName]
fileName := "/sys/block/" + deviceName + "/device/delete"
data := []byte("1")
ioutil.WriteFile(fileName, data, 0666)
}
func scsiHostScan() {
// TODO: if using pvscsi controller, this won't be needed
scsi_path := "/sys/class/scsi_host/"
if dirs, err := ioutil.ReadDir(scsi_path); err == nil {
for _, f := range dirs {
name := scsi_path + f.Name() + "/scan"
data := []byte("- - -")
ioutil.WriteFile(name, data, 0666)
klog.Errorf("scsiHostScan scan for %s", name)
}
}
}
func verifyDevicePath(path string) (string, error) {
if pathExists, err := mount.PathExists(path); err != nil {
return "", fmt.Errorf("Error checking if path exists: %v", err)
} else if pathExists {
return path, nil
}
klog.V(4).Infof("verifyDevicePath: path not exists yet")
return "", nil
}
// CreateVolume creates a PhotonController persistent disk.
func (util *PhotonDiskUtil) CreateVolume(p *photonPersistentDiskProvisioner) (pdID string, capacityGB int, fstype string, err error) {
cloud, err := getCloudProvider(p.plugin.host.GetCloudProvider())
if err != nil {
klog.Errorf("Photon Controller Util: CreateVolume failed to get cloud provider. Error [%v]", err)
return "", 0, "", err
}
capacity := p.options.PVC.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)]
// PhotonController works with GiB, convert to GiB with rounding up
volSizeGB, err := volumehelpers.RoundUpToGiBInt(capacity)
if err != nil {
return "", 0, "", err
}
name := volumeutil.GenerateVolumeName(p.options.ClusterName, p.options.PVName, 255)
volumeOptions := &photon.VolumeOptions{
CapacityGB: volSizeGB,
Tags: *p.options.CloudTags,
Name: name,
}
for parameter, value := range p.options.Parameters {
switch strings.ToLower(parameter) {
case "flavor":
volumeOptions.Flavor = value
case volume.VolumeParameterFSType:
fstype = value
klog.V(4).Infof("Photon Controller Util: Setting fstype to %s", fstype)
default:
klog.Errorf("Photon Controller Util: invalid option %s for volume plugin %s.", parameter, p.plugin.GetPluginName())
return "", 0, "", fmt.Errorf("Photon Controller Util: invalid option %s for volume plugin %s.", parameter, p.plugin.GetPluginName())
}
}
pdID, err = cloud.CreateDisk(volumeOptions)
if err != nil {
klog.Errorf("Photon Controller Util: failed to CreateDisk. Error [%v]", err)
return "", 0, "", err
}
klog.V(4).Infof("Successfully created Photon Controller persistent disk %s", name)
return pdID, volSizeGB, "", nil
}
// DeleteVolume deletes a vSphere volume.
func (util *PhotonDiskUtil) DeleteVolume(pd *photonPersistentDiskDeleter) error {
cloud, err := getCloudProvider(pd.plugin.host.GetCloudProvider())
if err != nil {
klog.Errorf("Photon Controller Util: DeleteVolume failed to get cloud provider. Error [%v]", err)
return err
}
if err = cloud.DeleteDisk(pd.pdID); err != nil {
klog.Errorf("Photon Controller Util: failed to DeleteDisk for pdID %s. Error [%v]", pd.pdID, err)
return err
}
klog.V(4).Infof("Successfully deleted PhotonController persistent disk %s", pd.pdID)
return nil
}
func getCloudProvider(cloud cloudprovider.Interface) (*photon.PCCloud, error) {
if cloud == nil {
klog.Errorf("Photon Controller Util: Cloud provider not initialized properly")
return nil, fmt.Errorf("Photon Controller Util: Cloud provider not initialized properly")
}
pcc := cloud.(*photon.PCCloud)
if pcc == nil {
klog.Errorf("Invalid cloud provider: expected Photon Controller")
return nil, fmt.Errorf("Invalid cloud provider: expected Photon Controller")
}
return pcc, nil
}

View File

@ -42,11 +42,8 @@ var (
}{
{"aws", false, "The AWS provider is deprecated and will be removed in a future release"},
{"azure", false, "The Azure provider is deprecated and will be removed in a future release"},
{"cloudstack", false, "The CloudStack Controller project is no longer maintained."},
{"gce", false, "The GCE provider is deprecated and will be removed in a future release"},
{"openstack", true, "https://github.com/kubernetes/cloud-provider-openstack"},
{"ovirt", false, "The ovirt Controller project is no longer maintained."},
{"photon", false, "The Photon Controller project is no longer maintained."},
{"vsphere", false, "The vSphere provider is deprecated and will be removed in a future release"},
}
)

View File

@ -583,12 +583,8 @@ k8s.io/kubernetes/pkg/client/tests,Q-Lee,1,
k8s.io/kubernetes/pkg/client/unversioned,justinsb,1,
k8s.io/kubernetes/pkg/cloudprovider/providers/aws,eparis,1,
k8s.io/kubernetes/pkg/cloudprovider/providers/azure,saad-ali,1,
k8s.io/kubernetes/pkg/cloudprovider/providers/cloudstack,roberthbailey,1,
k8s.io/kubernetes/pkg/cloudprovider/providers/gce,yifan-gu,1,
k8s.io/kubernetes/pkg/cloudprovider/providers/mesos,mml,1,
k8s.io/kubernetes/pkg/cloudprovider/providers/openstack,Q-Lee,1,
k8s.io/kubernetes/pkg/cloudprovider/providers/ovirt,dchen1107,1,
k8s.io/kubernetes/pkg/cloudprovider/providers/photon,luomiao,0,
k8s.io/kubernetes/pkg/cloudprovider/providers/vsphere,apelisse,1,
k8s.io/kubernetes/pkg/controller,mikedanese,1,
k8s.io/kubernetes/pkg/controller/bootstrap,mikedanese,0,
@ -821,7 +817,6 @@ k8s.io/kubernetes/pkg/volume/glusterfs,tallclair,1,
k8s.io/kubernetes/pkg/volume/hostpath,jbeda,1,
k8s.io/kubernetes/pkg/volume/iscsi,cjcullen,1,
k8s.io/kubernetes/pkg/volume/nfs,justinsb,1,
k8s.io/kubernetes/pkg/volume/photon_pd,luomiao,0,
k8s.io/kubernetes/pkg/volume/projected,kevin-wangzefeng,1,
k8s.io/kubernetes/pkg/volume/quobyte,yujuhong,1,
k8s.io/kubernetes/pkg/volume/rbd,piosz,1,

1 name owner auto-assigned sig
583 k8s.io/kubernetes/pkg/client/unversioned justinsb 1
584 k8s.io/kubernetes/pkg/cloudprovider/providers/aws eparis 1
585 k8s.io/kubernetes/pkg/cloudprovider/providers/azure saad-ali 1
k8s.io/kubernetes/pkg/cloudprovider/providers/cloudstack roberthbailey 1
586 k8s.io/kubernetes/pkg/cloudprovider/providers/gce yifan-gu 1
k8s.io/kubernetes/pkg/cloudprovider/providers/mesos mml 1
587 k8s.io/kubernetes/pkg/cloudprovider/providers/openstack Q-Lee 1
k8s.io/kubernetes/pkg/cloudprovider/providers/ovirt dchen1107 1
k8s.io/kubernetes/pkg/cloudprovider/providers/photon luomiao 0
588 k8s.io/kubernetes/pkg/cloudprovider/providers/vsphere apelisse 1
589 k8s.io/kubernetes/pkg/controller mikedanese 1
590 k8s.io/kubernetes/pkg/controller/bootstrap mikedanese 0
817 k8s.io/kubernetes/pkg/volume/hostpath jbeda 1
818 k8s.io/kubernetes/pkg/volume/iscsi cjcullen 1
819 k8s.io/kubernetes/pkg/volume/nfs justinsb 1
k8s.io/kubernetes/pkg/volume/photon_pd luomiao 0
820 k8s.io/kubernetes/pkg/volume/projected kevin-wangzefeng 1
821 k8s.io/kubernetes/pkg/volume/quobyte yujuhong 1
822 k8s.io/kubernetes/pkg/volume/rbd piosz 1

5
vendor/BUILD vendored
View File

@ -151,8 +151,6 @@ filegroup(
"//vendor/github.com/coreos/pkg/dlopen:all-srcs",
"//vendor/github.com/cpuguy83/go-md2man/md2man:all-srcs",
"//vendor/github.com/cyphar/filepath-securejoin:all-srcs",
"//vendor/github.com/d2g/dhcp4:all-srcs",
"//vendor/github.com/d2g/dhcp4client:all-srcs",
"//vendor/github.com/davecgh/go-spew/spew:all-srcs",
"//vendor/github.com/daviddengcn/go-colortext:all-srcs",
"//vendor/github.com/dgrijalva/jwt-go:all-srcs",
@ -352,9 +350,6 @@ filegroup(
"//vendor/github.com/vishvananda/netlink:all-srcs",
"//vendor/github.com/vishvananda/netns:all-srcs",
"//vendor/github.com/vmware/govmomi:all-srcs",
"//vendor/github.com/vmware/photon-controller-go-sdk/SSPI:all-srcs",
"//vendor/github.com/vmware/photon-controller-go-sdk/photon:all-srcs",
"//vendor/github.com/xanzy/go-cloudstack/cloudstack:all-srcs",
"//vendor/github.com/xiang90/probing:all-srcs",
"//vendor/go.uber.org/atomic:all-srcs",
"//vendor/go.uber.org/multierr:all-srcs",

28
vendor/github.com/d2g/dhcp4/BUILD generated vendored
View File

@ -1,28 +0,0 @@
load("@io_bazel_rules_go//go:def.bzl", "go_library")
go_library(
name = "go_default_library",
srcs = [
"constants.go",
"helpers.go",
"option.go",
"packet.go",
],
importmap = "k8s.io/kubernetes/vendor/github.com/d2g/dhcp4",
importpath = "github.com/d2g/dhcp4",
visibility = ["//visibility:public"],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)

27
vendor/github.com/d2g/dhcp4/LICENSE generated vendored
View File

@ -1,27 +0,0 @@
Copyright (c) 2013 Skagerrak Software Limited. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Skagerrak Software Limited nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View File

@ -1,5 +0,0 @@
# DHCP4 - A DHCP library written in Go.
Warning: This library is still being developed. Function calls will change.
I've removed Server Functionality, for me this project supports the underlying DHCP format not the implementation.

View File

@ -1,121 +0,0 @@
package dhcp4
// OpCodes
const (
BootRequest OpCode = 1 // From Client
BootReply OpCode = 2 // From Server
)
// DHCP Message Type 53
const (
Discover MessageType = 1 // Broadcast Packet From Client - Can I have an IP?
Offer MessageType = 2 // Broadcast From Server - Here's an IP
Request MessageType = 3 // Broadcast From Client - I'll take that IP (Also start for renewals)
Decline MessageType = 4 // Broadcast From Client - Sorry I can't use that IP
ACK MessageType = 5 // From Server, Yes you can have that IP
NAK MessageType = 6 // From Server, No you cannot have that IP
Release MessageType = 7 // From Client, I don't need that IP anymore
Inform MessageType = 8 // From Client, I have this IP and there's nothing you can do about it
)
// DHCP Options
const (
End OptionCode = 255
Pad OptionCode = 0
OptionSubnetMask OptionCode = 1
OptionTimeOffset OptionCode = 2
OptionRouter OptionCode = 3
OptionTimeServer OptionCode = 4
OptionNameServer OptionCode = 5
OptionDomainNameServer OptionCode = 6
OptionLogServer OptionCode = 7
OptionCookieServer OptionCode = 8
OptionLPRServer OptionCode = 9
OptionImpressServer OptionCode = 10
OptionResourceLocationServer OptionCode = 11
OptionHostName OptionCode = 12
OptionBootFileSize OptionCode = 13
OptionMeritDumpFile OptionCode = 14
OptionDomainName OptionCode = 15
OptionSwapServer OptionCode = 16
OptionRootPath OptionCode = 17
OptionExtensionsPath OptionCode = 18
// IP Layer Parameters per Host
OptionIPForwardingEnableDisable OptionCode = 19
OptionNonLocalSourceRoutingEnableDisable OptionCode = 20
OptionPolicyFilter OptionCode = 21
OptionMaximumDatagramReassemblySize OptionCode = 22
OptionDefaultIPTimeToLive OptionCode = 23
OptionPathMTUAgingTimeout OptionCode = 24
OptionPathMTUPlateauTable OptionCode = 25
// IP Layer Parameters per Interface
OptionInterfaceMTU OptionCode = 26
OptionAllSubnetsAreLocal OptionCode = 27
OptionBroadcastAddress OptionCode = 28
OptionPerformMaskDiscovery OptionCode = 29
OptionMaskSupplier OptionCode = 30
OptionPerformRouterDiscovery OptionCode = 31
OptionRouterSolicitationAddress OptionCode = 32
OptionStaticRoute OptionCode = 33
// Link Layer Parameters per Interface
OptionTrailerEncapsulation OptionCode = 34
OptionARPCacheTimeout OptionCode = 35
OptionEthernetEncapsulation OptionCode = 36
// TCP Parameters
OptionTCPDefaultTTL OptionCode = 37
OptionTCPKeepaliveInterval OptionCode = 38
OptionTCPKeepaliveGarbage OptionCode = 39
// Application and Service Parameters
OptionNetworkInformationServiceDomain OptionCode = 40
OptionNetworkInformationServers OptionCode = 41
OptionNetworkTimeProtocolServers OptionCode = 42
OptionVendorSpecificInformation OptionCode = 43
OptionNetBIOSOverTCPIPNameServer OptionCode = 44
OptionNetBIOSOverTCPIPDatagramDistributionServer OptionCode = 45
OptionNetBIOSOverTCPIPNodeType OptionCode = 46
OptionNetBIOSOverTCPIPScope OptionCode = 47
OptionXWindowSystemFontServer OptionCode = 48
OptionXWindowSystemDisplayManager OptionCode = 49
OptionNetworkInformationServicePlusDomain OptionCode = 64
OptionNetworkInformationServicePlusServers OptionCode = 65
OptionMobileIPHomeAgent OptionCode = 68
OptionSimpleMailTransportProtocol OptionCode = 69
OptionPostOfficeProtocolServer OptionCode = 70
OptionNetworkNewsTransportProtocol OptionCode = 71
OptionDefaultWorldWideWebServer OptionCode = 72
OptionDefaultFingerServer OptionCode = 73
OptionDefaultInternetRelayChatServer OptionCode = 74
OptionStreetTalkServer OptionCode = 75
OptionStreetTalkDirectoryAssistance OptionCode = 76
// DHCP Extensions
OptionRequestedIPAddress OptionCode = 50
OptionIPAddressLeaseTime OptionCode = 51
OptionOverload OptionCode = 52
OptionDHCPMessageType OptionCode = 53
OptionServerIdentifier OptionCode = 54
OptionParameterRequestList OptionCode = 55
OptionMessage OptionCode = 56
OptionMaximumDHCPMessageSize OptionCode = 57
OptionRenewalTimeValue OptionCode = 58
OptionRebindingTimeValue OptionCode = 59
OptionVendorClassIdentifier OptionCode = 60
OptionClientIdentifier OptionCode = 61
OptionTFTPServerName OptionCode = 66
OptionBootFileName OptionCode = 67
OptionUserClass OptionCode = 77
OptionClientArchitecture OptionCode = 93
OptionTZPOSIXString OptionCode = 100
OptionTZDatabaseString OptionCode = 101
OptionClasslessRouteFormat OptionCode = 121
)

View File

@ -1,58 +0,0 @@
package dhcp4
import (
"encoding/binary"
"net"
"time"
)
// IPRange returns how many ips in the ip range from start to stop (inclusive)
func IPRange(start, stop net.IP) int {
//return int(Uint([]byte(stop))-Uint([]byte(start))) + 1
return int(binary.BigEndian.Uint32(stop.To4())) - int(binary.BigEndian.Uint32(start.To4())) + 1
}
// IPAdd returns a copy of start + add.
// IPAdd(net.IP{192,168,1,1},30) returns net.IP{192.168.1.31}
func IPAdd(start net.IP, add int) net.IP { // IPv4 only
start = start.To4()
//v := Uvarint([]byte(start))
result := make(net.IP, 4)
binary.BigEndian.PutUint32(result, binary.BigEndian.Uint32(start)+uint32(add))
//PutUint([]byte(result), v+uint64(add))
return result
}
// IPLess returns where IP a is less than IP b.
func IPLess(a, b net.IP) bool {
b = b.To4()
for i, ai := range a.To4() {
if ai != b[i] {
return ai < b[i]
}
}
return false
}
// IPInRange returns true if ip is between (inclusive) start and stop.
func IPInRange(start, stop, ip net.IP) bool {
return !(IPLess(ip, start) || IPLess(stop, ip))
}
// OptionsLeaseTime - converts a time.Duration to a 4 byte slice, compatible
// with OptionIPAddressLeaseTime.
func OptionsLeaseTime(d time.Duration) []byte {
leaseBytes := make([]byte, 4)
binary.BigEndian.PutUint32(leaseBytes, uint32(d/time.Second))
//PutUvarint(leaseBytes, uint64(d/time.Second))
return leaseBytes
}
// JoinIPs returns a byte slice of IP addresses, one immediately after the other
// This may be useful for creating multiple IP options such as OptionRouter.
func JoinIPs(ips []net.IP) (b []byte) {
for _, v := range ips {
b = append(b, v.To4()...)
}
return
}

View File

@ -1,40 +0,0 @@
package dhcp4
type OptionCode byte
type Option struct {
Code OptionCode
Value []byte
}
// Map of DHCP options
type Options map[OptionCode][]byte
// SelectOrderOrAll has same functionality as SelectOrder, except if the order
// param is nil, whereby all options are added (in arbitrary order).
func (o Options) SelectOrderOrAll(order []byte) []Option {
if order == nil {
opts := make([]Option, 0, len(o))
for i, v := range o {
opts = append(opts, Option{Code: i, Value: v})
}
return opts
}
return o.SelectOrder(order)
}
// SelectOrder returns a slice of options ordered and selected by a byte array
// usually defined by OptionParameterRequestList. This result is expected to be
// used in ReplyPacket()'s []Option parameter.
func (o Options) SelectOrder(order []byte) []Option {
opts := make([]Option, 0, len(order))
for _, v := range order {
if data, ok := o[OptionCode(v)]; ok {
opts = append(opts, Option{Code: OptionCode(v), Value: data})
}
}
return opts
}
type OpCode byte
type MessageType byte // Option 53

150
vendor/github.com/d2g/dhcp4/packet.go generated vendored
View File

@ -1,150 +0,0 @@
package dhcp4
import (
"net"
"time"
)
// A DHCP packet
type Packet []byte
func (p Packet) OpCode() OpCode { return OpCode(p[0]) }
func (p Packet) HType() byte { return p[1] }
func (p Packet) HLen() byte { return p[2] }
func (p Packet) Hops() byte { return p[3] }
func (p Packet) XId() []byte { return p[4:8] }
func (p Packet) Secs() []byte { return p[8:10] } // Never Used?
func (p Packet) Flags() []byte { return p[10:12] }
func (p Packet) CIAddr() net.IP { return net.IP(p[12:16]) }
func (p Packet) YIAddr() net.IP { return net.IP(p[16:20]) }
func (p Packet) SIAddr() net.IP { return net.IP(p[20:24]) }
func (p Packet) GIAddr() net.IP { return net.IP(p[24:28]) }
func (p Packet) CHAddr() net.HardwareAddr {
hLen := p.HLen()
if hLen > 16 { // Prevent chaddr exceeding p boundary
hLen = 16
}
return net.HardwareAddr(p[28 : 28+hLen]) // max endPos 44
}
// 192 bytes of zeros BOOTP legacy
func (p Packet) Cookie() []byte { return p[236:240] }
func (p Packet) Options() []byte {
if len(p) > 240 {
return p[240:]
}
return nil
}
func (p Packet) Broadcast() bool { return p.Flags()[0] > 127 }
func (p Packet) SetBroadcast(broadcast bool) {
if p.Broadcast() != broadcast {
p.Flags()[0] ^= 128
}
}
func (p Packet) SetOpCode(c OpCode) { p[0] = byte(c) }
func (p Packet) SetCHAddr(a net.HardwareAddr) {
copy(p[28:44], a)
p[2] = byte(len(a))
}
func (p Packet) SetHType(hType byte) { p[1] = hType }
func (p Packet) SetCookie(cookie []byte) { copy(p.Cookie(), cookie) }
func (p Packet) SetHops(hops byte) { p[3] = hops }
func (p Packet) SetXId(xId []byte) { copy(p.XId(), xId) }
func (p Packet) SetSecs(secs []byte) { copy(p.Secs(), secs) }
func (p Packet) SetFlags(flags []byte) { copy(p.Flags(), flags) }
func (p Packet) SetCIAddr(ip net.IP) { copy(p.CIAddr(), ip.To4()) }
func (p Packet) SetYIAddr(ip net.IP) { copy(p.YIAddr(), ip.To4()) }
func (p Packet) SetSIAddr(ip net.IP) { copy(p.SIAddr(), ip.To4()) }
func (p Packet) SetGIAddr(ip net.IP) { copy(p.GIAddr(), ip.To4()) }
// Parses the packet's options into an Options map
func (p Packet) ParseOptions() Options {
opts := p.Options()
options := make(Options, 10)
for len(opts) >= 2 && OptionCode(opts[0]) != End {
if OptionCode(opts[0]) == Pad {
opts = opts[1:]
continue
}
size := int(opts[1])
if len(opts) < 2+size {
break
}
options[OptionCode(opts[0])] = opts[2 : 2+size]
opts = opts[2+size:]
}
return options
}
func NewPacket(opCode OpCode) Packet {
p := make(Packet, 241)
p.SetOpCode(opCode)
p.SetHType(1) // Ethernet
p.SetCookie([]byte{99, 130, 83, 99})
p[240] = byte(End)
return p
}
// Appends a DHCP option to the end of a packet
func (p *Packet) AddOption(o OptionCode, value []byte) {
*p = append((*p)[:len(*p)-1], []byte{byte(o), byte(len(value))}...) // Strip off End, Add OptionCode and Length
*p = append(*p, value...) // Add Option Value
*p = append(*p, byte(End)) // Add on new End
}
// Removes all options from packet.
func (p *Packet) StripOptions() {
*p = append((*p)[:240], byte(End))
}
// Creates a request packet that a Client would send to a server.
func RequestPacket(mt MessageType, chAddr net.HardwareAddr, cIAddr net.IP, xId []byte, broadcast bool, options []Option) Packet {
p := NewPacket(BootRequest)
p.SetCHAddr(chAddr)
p.SetXId(xId)
if cIAddr != nil {
p.SetCIAddr(cIAddr)
}
p.SetBroadcast(broadcast)
p.AddOption(OptionDHCPMessageType, []byte{byte(mt)})
for _, o := range options {
p.AddOption(o.Code, o.Value)
}
p.PadToMinSize()
return p
}
// ReplyPacket creates a reply packet that a Server would send to a client.
// It uses the req Packet param to copy across common/necessary fields to
// associate the reply the request.
func ReplyPacket(req Packet, mt MessageType, serverId, yIAddr net.IP, leaseDuration time.Duration, options []Option) Packet {
p := NewPacket(BootReply)
p.SetXId(req.XId())
p.SetFlags(req.Flags())
p.SetYIAddr(yIAddr)
p.SetGIAddr(req.GIAddr())
p.SetCHAddr(req.CHAddr())
p.AddOption(OptionDHCPMessageType, []byte{byte(mt)})
p.AddOption(OptionServerIdentifier, []byte(serverId))
if leaseDuration > 0 {
p.AddOption(OptionIPAddressLeaseTime, OptionsLeaseTime(leaseDuration))
}
for _, o := range options {
p.AddOption(o.Code, o.Value)
}
p.PadToMinSize()
return p
}
// PadToMinSize pads a packet so that when sent over UDP, the entire packet,
// is 300 bytes (BOOTP min), to be compatible with really old devices.
var padder [272]byte
func (p *Packet) PadToMinSize() {
if n := len(*p); n < 272 {
*p = append(*p, padder[:272-n]...)
}
}

View File

@ -1,36 +0,0 @@
load("@io_bazel_rules_go//go:def.bzl", "go_library")
go_library(
name = "go_default_library",
srcs = [
"client.go",
"generatexid.go",
"inetsock.go",
"pktsock_linux.go",
],
importmap = "k8s.io/kubernetes/vendor/github.com/d2g/dhcp4client",
importpath = "github.com/d2g/dhcp4client",
visibility = ["//visibility:public"],
deps = [
"//vendor/github.com/d2g/dhcp4:go_default_library",
] + select({
"@io_bazel_rules_go//go/platform:linux": [
"//vendor/golang.org/x/sys/unix:go_default_library",
],
"//conditions:default": [],
}),
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)

View File

@ -1,354 +0,0 @@
Mozilla Public License, version 2.0
1. Definitions
1.1. “Contributor”
means each individual or legal entity that creates, contributes to the
creation of, or owns Covered Software.
1.2. “Contributor Version”
means the combination of the Contributions of others (if any) used by a
Contributor and that particular Contributors Contribution.
1.3. “Contribution”
means Covered Software of a particular Contributor.
1.4. “Covered Software”
means Source Code Form to which the initial Contributor has attached the
notice in Exhibit A, the Executable Form of such Source Code Form, and
Modifications of such Source Code Form, in each case including portions
thereof.
1.5. “Incompatible With Secondary Licenses”
means
a. that the initial Contributor has attached the notice described in
Exhibit B to the Covered Software; or
b. that the Covered Software was made available under the terms of version
1.1 or earlier of the License, but not also under the terms of a
Secondary License.
1.6. “Executable Form”
means any form of the work other than Source Code Form.
1.7. “Larger Work”
means a work that combines Covered Software with other material, in a separate
file or files, that is not Covered Software.
1.8. “License”
means this document.
1.9. “Licensable”
means having the right to grant, to the maximum extent possible, whether at the
time of the initial grant or subsequently, any and all of the rights conveyed by
this License.
1.10. “Modifications”
means any of the following:
a. any file in Source Code Form that results from an addition to, deletion
from, or modification of the contents of Covered Software; or
b. any new file in Source Code Form that contains any Covered Software.
1.11. “Patent Claims” of a Contributor
means any patent claim(s), including without limitation, method, process,
and apparatus claims, in any patent Licensable by such Contributor that
would be infringed, but for the grant of the License, by the making,
using, selling, offering for sale, having made, import, or transfer of
either its Contributions or its Contributor Version.
1.12. “Secondary License”
means either the GNU General Public License, Version 2.0, the GNU Lesser
General Public License, Version 2.1, the GNU Affero General Public
License, Version 3.0, or any later versions of those licenses.
1.13. “Source Code Form”
means the form of the work preferred for making modifications.
1.14. “You” (or “Your”)
means an individual or a legal entity exercising rights under this
License. For legal entities, “You” includes any entity that controls, is
controlled by, or is under common control with You. For purposes of this
definition, “control” means (a) the power, direct or indirect, to cause
the direction or management of such entity, whether by contract or
otherwise, or (b) ownership of more than fifty percent (50%) of the
outstanding shares or beneficial ownership of such entity.
2. License Grants and Conditions
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
a. under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or as
part of a Larger Work; and
b. under Patent Claims of such Contributor to make, use, sell, offer for
sale, have made, import, and otherwise transfer either its Contributions
or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution become
effective for each Contribution on the date the Contributor first distributes
such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under this
License. No additional rights or licenses will be implied from the distribution
or licensing of Covered Software under this License. Notwithstanding Section
2.1(b) above, no patent license is granted by a Contributor:
a. for any code that a Contributor has removed from Covered Software; or
b. for infringements caused by: (i) Your and any other third partys
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
c. under Patent Claims infringed by Covered Software in the absence of its
Contributions.
This License does not grant any rights in the trademarks, service marks, or
logos of any Contributor (except as may be necessary to comply with the
notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this License
(see Section 10.2) or under the terms of a Secondary License (if permitted
under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its Contributions
are its original creation(s) or it has sufficient rights to grant the
rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under applicable
copyright doctrines of fair use, fair dealing, or other equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in
Section 2.1.
3. Responsibilities
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under the
terms of this License. You must inform recipients that the Source Code Form
of the Covered Software is governed by the terms of this License, and how
they can obtain a copy of this License. You may not attempt to alter or
restrict the recipients rights in the Source Code Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
a. such Covered Software must also be made available in Source Code Form,
as described in Section 3.1, and You must inform recipients of the
Executable Form how they can obtain a copy of such Source Code Form by
reasonable means in a timely manner, at a charge no more than the cost
of distribution to the recipient; and
b. You may distribute such Executable Form under the terms of this License,
or sublicense it under different terms, provided that the license for
the Executable Form does not attempt to limit or alter the recipients
rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for the
Covered Software. If the Larger Work is a combination of Covered Software
with a work governed by one or more Secondary Licenses, and the Covered
Software is not Incompatible With Secondary Licenses, this License permits
You to additionally distribute such Covered Software under the terms of
such Secondary License(s), so that the recipient of the Larger Work may, at
their option, further distribute the Covered Software under the terms of
either this License or such Secondary License(s).
3.4. Notices
You may not remove or alter the substance of any license notices (including
copyright notices, patent notices, disclaimers of warranty, or limitations
of liability) contained within the Source Code Form of the Covered
Software, except that You may alter any license notices to the extent
required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on behalf
of any Contributor. You must make it absolutely clear that any such
warranty, support, indemnity, or liability obligation is offered by You
alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
If it is impossible for You to comply with any of the terms of this License
with respect to some or all of the Covered Software due to statute, judicial
order, or regulation then You must: (a) comply with the terms of this License
to the maximum extent possible; and (b) describe the limitations and the code
they affect. Such description must be placed in a text file included with all
distributions of the Covered Software under this License. Except to the
extent prohibited by statute or regulation, such description must be
sufficiently detailed for a recipient of ordinary skill to be able to
understand it.
5. Termination
5.1. The rights granted under this License will terminate automatically if You
fail to comply with any of its terms. However, if You become compliant,
then the rights granted under this License from a particular Contributor
are reinstated (a) provisionally, unless and until such Contributor
explicitly and finally terminates Your grants, and (b) on an ongoing basis,
if such Contributor fails to notify You of the non-compliance by some
reasonable means prior to 60 days after You have come back into compliance.
Moreover, Your grants from a particular Contributor are reinstated on an
ongoing basis if such Contributor notifies You of the non-compliance by
some reasonable means, this is the first time You have received notice of
non-compliance with this License from such Contributor, and You become
compliant prior to 30 days after Your receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions, counter-claims,
and cross-claims) alleging that a Contributor Version directly or
indirectly infringes any patent, then the rights granted to You by any and
all Contributors for the Covered Software under Section 2.1 of this License
shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user
license agreements (excluding distributors and resellers) which have been
validly granted by You or Your distributors under this License prior to
termination shall survive termination.
6. Disclaimer of Warranty
Covered Software is provided under this License on an “as is” basis, without
warranty of any kind, either expressed, implied, or statutory, including,
without limitation, warranties that the Covered Software is free of defects,
merchantable, fit for a particular purpose or non-infringing. The entire
risk as to the quality and performance of the Covered Software is with You.
Should any Covered Software prove defective in any respect, You (not any
Contributor) assume the cost of any necessary servicing, repair, or
correction. This disclaimer of warranty constitutes an essential part of this
License. No use of any Covered Software is authorized under this License
except under this disclaimer.
7. Limitation of Liability
Under no circumstances and under no legal theory, whether tort (including
negligence), contract, or otherwise, shall any Contributor, or anyone who
distributes Covered Software as permitted above, be liable to You for any
direct, indirect, special, incidental, or consequential damages of any
character including, without limitation, damages for lost profits, loss of
goodwill, work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses, even if such party shall have been
informed of the possibility of such damages. This limitation of liability
shall not apply to liability for death or personal injury resulting from such
partys negligence to the extent applicable law prohibits such limitation.
Some jurisdictions do not allow the exclusion or limitation of incidental or
consequential damages, so this exclusion and limitation may not apply to You.
8. Litigation
Any litigation relating to this License may be brought only in the courts of
a jurisdiction where the defendant maintains its principal place of business
and such litigation shall be governed by laws of that jurisdiction, without
reference to its conflict-of-law provisions. Nothing in this Section shall
prevent a partys ability to bring cross-claims or counter-claims.
9. Miscellaneous
This License represents the complete agreement concerning the subject matter
hereof. If any provision of this License is held to be unenforceable, such
provision shall be reformed only to the extent necessary to make it
enforceable. Any law or regulation which provides that the language of a
contract shall be construed against the drafter shall not be used to construe
this License against a Contributor.
10. Versions of the License
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version of
the License under which You originally received the Covered Software, or
under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a modified
version of this License if you rename the license and remove any
references to the name of the license steward (except to note that such
modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
Exhibit A - Source Code Form License Notice
This Source Code Form is subject to the
terms of the Mozilla Public License, v.
2.0. If a copy of the MPL was not
distributed with this file, You can
obtain one at
http://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular file, then
You may include the notice in a location (such as a LICENSE file in a relevant
directory) where a recipient would be likely to look for such a notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - “Incompatible With Secondary Licenses” Notice
This Source Code Form is “Incompatible
With Secondary Licenses”, as defined by
the Mozilla Public License, v. 2.0.

View File

@ -1,8 +0,0 @@
dhcp4client [![GoDoc](https://godoc.org/github.com/d2g/dhcp4client?status.svg)](http://godoc.org/github.com/d2g/dhcp4client) [![Coverage Status](https://coveralls.io/repos/d2g/dhcp4client/badge.svg?branch=HEAD)](https://coveralls.io/r/d2g/dhcp4client?branch=HEAD) [![Codeship Status for d2g/dhcp4client](https://codeship.com/projects/d75d9860-b364-0132-bc79-7e1d8cf367b9/status?branch=master)](https://codeship.com/projects/70187)
===========
DHCP Client
###### Thanks to:
@eyakubovich For AF_PACKET support.

View File

@ -1,364 +0,0 @@
package dhcp4client
import (
"bytes"
"net"
"time"
"github.com/d2g/dhcp4"
)
const (
MaxDHCPLen = 576
)
type Client struct {
hardwareAddr net.HardwareAddr //The HardwareAddr to send in the request.
ignoreServers []net.IP //List of Servers to Ignore requests from.
timeout time.Duration //Time before we timeout.
broadcast bool //Set the Bcast flag in BOOTP Flags
connection connection //The Connection Method to use
generateXID func([]byte) //Function Used to Generate a XID
}
//Abstracts the type of underlying socket used
type connection interface {
Close() error
Write(packet []byte) error
ReadFrom() ([]byte, net.IP, error)
SetReadTimeout(t time.Duration) error
}
func New(options ...func(*Client) error) (*Client, error) {
c := Client{
timeout: time.Second * 10,
broadcast: true,
generateXID: CryptoGenerateXID,
}
err := c.SetOption(options...)
if err != nil {
return nil, err
}
//if connection hasn't been set as an option create the default.
if c.connection == nil {
conn, err := NewInetSock()
if err != nil {
return nil, err
}
c.connection = conn
}
return &c, nil
}
func (c *Client) SetOption(options ...func(*Client) error) error {
for _, opt := range options {
if err := opt(c); err != nil {
return err
}
}
return nil
}
func Timeout(t time.Duration) func(*Client) error {
return func(c *Client) error {
c.timeout = t
return nil
}
}
func IgnoreServers(s []net.IP) func(*Client) error {
return func(c *Client) error {
c.ignoreServers = s
return nil
}
}
func HardwareAddr(h net.HardwareAddr) func(*Client) error {
return func(c *Client) error {
c.hardwareAddr = h
return nil
}
}
func Broadcast(b bool) func(*Client) error {
return func(c *Client) error {
c.broadcast = b
return nil
}
}
func Connection(conn connection) func(*Client) error {
return func(c *Client) error {
c.connection = conn
return nil
}
}
func GenerateXID(g func([]byte)) func(*Client) error {
return func(c *Client) error {
c.generateXID = g
return nil
}
}
//Close Connections
func (c *Client) Close() error {
if c.connection != nil {
return c.connection.Close()
}
return nil
}
//Send the Discovery Packet to the Broadcast Channel
func (c *Client) SendDiscoverPacket() (dhcp4.Packet, error) {
discoveryPacket := c.DiscoverPacket()
discoveryPacket.PadToMinSize()
return discoveryPacket, c.SendPacket(discoveryPacket)
}
//Retreive Offer...
//Wait for the offer for a specific Discovery Packet.
func (c *Client) GetOffer(discoverPacket *dhcp4.Packet) (dhcp4.Packet, error) {
for {
c.connection.SetReadTimeout(c.timeout)
readBuffer, source, err := c.connection.ReadFrom()
if err != nil {
return dhcp4.Packet{}, err
}
offerPacket := dhcp4.Packet(readBuffer)
offerPacketOptions := offerPacket.ParseOptions()
// Ignore Servers in my Ignore list
for _, ignoreServer := range c.ignoreServers {
if source.Equal(ignoreServer) {
continue
}
if offerPacket.SIAddr().Equal(ignoreServer) {
continue
}
}
if len(offerPacketOptions[dhcp4.OptionDHCPMessageType]) < 1 || dhcp4.MessageType(offerPacketOptions[dhcp4.OptionDHCPMessageType][0]) != dhcp4.Offer || !bytes.Equal(discoverPacket.XId(), offerPacket.XId()) {
continue
}
return offerPacket, nil
}
}
//Send Request Based On the offer Received.
func (c *Client) SendRequest(offerPacket *dhcp4.Packet) (dhcp4.Packet, error) {
requestPacket := c.RequestPacket(offerPacket)
requestPacket.PadToMinSize()
return requestPacket, c.SendPacket(requestPacket)
}
//Retreive Acknowledgement
//Wait for the offer for a specific Request Packet.
func (c *Client) GetAcknowledgement(requestPacket *dhcp4.Packet) (dhcp4.Packet, error) {
for {
c.connection.SetReadTimeout(c.timeout)
readBuffer, source, err := c.connection.ReadFrom()
if err != nil {
return dhcp4.Packet{}, err
}
acknowledgementPacket := dhcp4.Packet(readBuffer)
acknowledgementPacketOptions := acknowledgementPacket.ParseOptions()
// Ignore Servers in my Ignore list
for _, ignoreServer := range c.ignoreServers {
if source.Equal(ignoreServer) {
continue
}
if acknowledgementPacket.SIAddr().Equal(ignoreServer) {
continue
}
}
if !bytes.Equal(requestPacket.XId(), acknowledgementPacket.XId()) || len(acknowledgementPacketOptions[dhcp4.OptionDHCPMessageType]) < 1 || (dhcp4.MessageType(acknowledgementPacketOptions[dhcp4.OptionDHCPMessageType][0]) != dhcp4.ACK && dhcp4.MessageType(acknowledgementPacketOptions[dhcp4.OptionDHCPMessageType][0]) != dhcp4.NAK) {
continue
}
return acknowledgementPacket, nil
}
}
//Send Decline to the received acknowledgement.
func (c *Client) SendDecline(acknowledgementPacket *dhcp4.Packet) (dhcp4.Packet, error) {
declinePacket := c.DeclinePacket(acknowledgementPacket)
declinePacket.PadToMinSize()
return declinePacket, c.SendPacket(declinePacket)
}
//Send a DHCP Packet.
func (c *Client) SendPacket(packet dhcp4.Packet) error {
return c.connection.Write(packet)
}
//Create Discover Packet
func (c *Client) DiscoverPacket() dhcp4.Packet {
messageid := make([]byte, 4)
c.generateXID(messageid)
packet := dhcp4.NewPacket(dhcp4.BootRequest)
packet.SetCHAddr(c.hardwareAddr)
packet.SetXId(messageid)
packet.SetBroadcast(c.broadcast)
packet.AddOption(dhcp4.OptionDHCPMessageType, []byte{byte(dhcp4.Discover)})
//packet.PadToMinSize()
return packet
}
//Create Request Packet
func (c *Client) RequestPacket(offerPacket *dhcp4.Packet) dhcp4.Packet {
offerOptions := offerPacket.ParseOptions()
packet := dhcp4.NewPacket(dhcp4.BootRequest)
packet.SetCHAddr(c.hardwareAddr)
packet.SetXId(offerPacket.XId())
packet.SetCIAddr(offerPacket.CIAddr())
packet.SetSIAddr(offerPacket.SIAddr())
packet.SetBroadcast(c.broadcast)
packet.AddOption(dhcp4.OptionDHCPMessageType, []byte{byte(dhcp4.Request)})
packet.AddOption(dhcp4.OptionRequestedIPAddress, (offerPacket.YIAddr()).To4())
packet.AddOption(dhcp4.OptionServerIdentifier, offerOptions[dhcp4.OptionServerIdentifier])
return packet
}
//Create Request Packet For a Renew
func (c *Client) RenewalRequestPacket(acknowledgement *dhcp4.Packet) dhcp4.Packet {
messageid := make([]byte, 4)
c.generateXID(messageid)
acknowledgementOptions := acknowledgement.ParseOptions()
packet := dhcp4.NewPacket(dhcp4.BootRequest)
packet.SetCHAddr(acknowledgement.CHAddr())
packet.SetXId(messageid)
packet.SetCIAddr(acknowledgement.YIAddr())
packet.SetSIAddr(acknowledgement.SIAddr())
packet.SetBroadcast(c.broadcast)
packet.AddOption(dhcp4.OptionDHCPMessageType, []byte{byte(dhcp4.Request)})
packet.AddOption(dhcp4.OptionRequestedIPAddress, (acknowledgement.YIAddr()).To4())
packet.AddOption(dhcp4.OptionServerIdentifier, acknowledgementOptions[dhcp4.OptionServerIdentifier])
return packet
}
//Create Release Packet For a Release
func (c *Client) ReleasePacket(acknowledgement *dhcp4.Packet) dhcp4.Packet {
messageid := make([]byte, 4)
c.generateXID(messageid)
acknowledgementOptions := acknowledgement.ParseOptions()
packet := dhcp4.NewPacket(dhcp4.BootRequest)
packet.SetCHAddr(acknowledgement.CHAddr())
packet.SetXId(messageid)
packet.SetCIAddr(acknowledgement.YIAddr())
packet.AddOption(dhcp4.OptionDHCPMessageType, []byte{byte(dhcp4.Release)})
packet.AddOption(dhcp4.OptionServerIdentifier, acknowledgementOptions[dhcp4.OptionServerIdentifier])
return packet
}
//Create Decline Packet
func (c *Client) DeclinePacket(acknowledgement *dhcp4.Packet) dhcp4.Packet {
messageid := make([]byte, 4)
c.generateXID(messageid)
acknowledgementOptions := acknowledgement.ParseOptions()
packet := dhcp4.NewPacket(dhcp4.BootRequest)
packet.SetCHAddr(acknowledgement.CHAddr())
packet.SetXId(messageid)
packet.AddOption(dhcp4.OptionDHCPMessageType, []byte{byte(dhcp4.Decline)})
packet.AddOption(dhcp4.OptionRequestedIPAddress, (acknowledgement.YIAddr()).To4())
packet.AddOption(dhcp4.OptionServerIdentifier, acknowledgementOptions[dhcp4.OptionServerIdentifier])
return packet
}
//Lets do a Full DHCP Request.
func (c *Client) Request() (bool, dhcp4.Packet, error) {
discoveryPacket, err := c.SendDiscoverPacket()
if err != nil {
return false, discoveryPacket, err
}
offerPacket, err := c.GetOffer(&discoveryPacket)
if err != nil {
return false, offerPacket, err
}
requestPacket, err := c.SendRequest(&offerPacket)
if err != nil {
return false, requestPacket, err
}
acknowledgement, err := c.GetAcknowledgement(&requestPacket)
if err != nil {
return false, acknowledgement, err
}
acknowledgementOptions := acknowledgement.ParseOptions()
if dhcp4.MessageType(acknowledgementOptions[dhcp4.OptionDHCPMessageType][0]) != dhcp4.ACK {
return false, acknowledgement, nil
}
return true, acknowledgement, nil
}
//Renew a lease backed on the Acknowledgement Packet.
//Returns Sucessfull, The AcknoledgementPacket, Any Errors
func (c *Client) Renew(acknowledgement dhcp4.Packet) (bool, dhcp4.Packet, error) {
renewRequest := c.RenewalRequestPacket(&acknowledgement)
renewRequest.PadToMinSize()
err := c.SendPacket(renewRequest)
if err != nil {
return false, renewRequest, err
}
newAcknowledgement, err := c.GetAcknowledgement(&renewRequest)
if err != nil {
return false, newAcknowledgement, err
}
newAcknowledgementOptions := newAcknowledgement.ParseOptions()
if dhcp4.MessageType(newAcknowledgementOptions[dhcp4.OptionDHCPMessageType][0]) != dhcp4.ACK {
return false, newAcknowledgement, nil
}
return true, newAcknowledgement, nil
}
//Release a lease backed on the Acknowledgement Packet.
//Returns Any Errors
func (c *Client) Release(acknowledgement dhcp4.Packet) error {
release := c.ReleasePacket(&acknowledgement)
release.PadToMinSize()
return c.SendPacket(release)
}

View File

@ -1,18 +0,0 @@
package dhcp4client
import (
cryptorand "crypto/rand"
mathrand "math/rand"
)
func CryptoGenerateXID(b []byte) {
if _, err := cryptorand.Read(b); err != nil {
panic(err)
}
}
func MathGenerateXID(b []byte) {
if _, err := mathrand.Read(b); err != nil {
panic(err)
}
}

View File

@ -1,75 +0,0 @@
package dhcp4client
import (
"net"
"time"
)
type inetSock struct {
*net.UDPConn
laddr net.UDPAddr
raddr net.UDPAddr
}
func NewInetSock(options ...func(*inetSock) error) (*inetSock, error) {
c := &inetSock{
laddr: net.UDPAddr{IP: net.IPv4(0, 0, 0, 0), Port: 68},
raddr: net.UDPAddr{IP: net.IPv4bcast, Port: 67},
}
err := c.setOption(options...)
if err != nil {
return nil, err
}
conn, err := net.ListenUDP("udp4", &c.laddr)
if err != nil {
return nil, err
}
c.UDPConn = conn
return c, err
}
func (c *inetSock) setOption(options ...func(*inetSock) error) error {
for _, opt := range options {
if err := opt(c); err != nil {
return err
}
}
return nil
}
func SetLocalAddr(l net.UDPAddr) func(*inetSock) error {
return func(c *inetSock) error {
c.laddr = l
return nil
}
}
func SetRemoteAddr(r net.UDPAddr) func(*inetSock) error {
return func(c *inetSock) error {
c.raddr = r
return nil
}
}
func (c *inetSock) Write(packet []byte) error {
_, err := c.WriteToUDP(packet, &c.raddr)
return err
}
func (c *inetSock) ReadFrom() ([]byte, net.IP, error) {
readBuffer := make([]byte, MaxDHCPLen)
n, source, err := c.ReadFromUDP(readBuffer)
if source != nil {
return readBuffer[:n], source.IP, err
} else {
return readBuffer[:n], net.IP{}, err
}
}
func (c *inetSock) SetReadTimeout(t time.Duration) error {
return c.SetReadDeadline(time.Now().Add(t))
}

View File

@ -1,147 +0,0 @@
package dhcp4client
import (
"crypto/rand"
"encoding/binary"
"net"
"time"
"golang.org/x/sys/unix"
)
const (
minIPHdrLen = 20
maxIPHdrLen = 60
udpHdrLen = 8
ip4Ver = 0x40
ttl = 16
srcPort = 68
dstPort = 67
)
var (
bcastMAC = []byte{255, 255, 255, 255, 255, 255}
)
// abstracts AF_PACKET
type packetSock struct {
fd int
ifindex int
}
func NewPacketSock(ifindex int) (*packetSock, error) {
fd, err := unix.Socket(unix.AF_PACKET, unix.SOCK_DGRAM, int(swap16(unix.ETH_P_IP)))
if err != nil {
return nil, err
}
addr := unix.SockaddrLinklayer{
Ifindex: ifindex,
Protocol: swap16(unix.ETH_P_IP),
}
if err = unix.Bind(fd, &addr); err != nil {
return nil, err
}
return &packetSock{
fd: fd,
ifindex: ifindex,
}, nil
}
func (pc *packetSock) Close() error {
return unix.Close(pc.fd)
}
func (pc *packetSock) Write(packet []byte) error {
lladdr := unix.SockaddrLinklayer{
Ifindex: pc.ifindex,
Protocol: swap16(unix.ETH_P_IP),
Halen: uint8(len(bcastMAC)),
}
copy(lladdr.Addr[:], bcastMAC)
pkt := make([]byte, minIPHdrLen+udpHdrLen+len(packet))
fillIPHdr(pkt[0:minIPHdrLen], udpHdrLen+uint16(len(packet)))
fillUDPHdr(pkt[minIPHdrLen:minIPHdrLen+udpHdrLen], uint16(len(packet)))
// payload
copy(pkt[minIPHdrLen+udpHdrLen:len(pkt)], packet)
return unix.Sendto(pc.fd, pkt, 0, &lladdr)
}
func (pc *packetSock) ReadFrom() ([]byte, net.IP, error) {
pkt := make([]byte, maxIPHdrLen+udpHdrLen+MaxDHCPLen)
n, _, err := unix.Recvfrom(pc.fd, pkt, 0)
if err != nil {
return nil, nil, err
}
// IP hdr len
ihl := int(pkt[0]&0x0F) * 4
// Source IP address
src := net.IP(pkt[12:16])
return pkt[ihl+udpHdrLen : n], src, nil
}
func (pc *packetSock) SetReadTimeout(t time.Duration) error {
tv := unix.NsecToTimeval(t.Nanoseconds())
return unix.SetsockoptTimeval(pc.fd, unix.SOL_SOCKET, unix.SO_RCVTIMEO, &tv)
}
// compute's 1's complement checksum
func chksum(p []byte, csum []byte) {
cklen := len(p)
s := uint32(0)
for i := 0; i < (cklen - 1); i += 2 {
s += uint32(p[i+1])<<8 | uint32(p[i])
}
if cklen&1 == 1 {
s += uint32(p[cklen-1])
}
s = (s >> 16) + (s & 0xffff)
s = s + (s >> 16)
s = ^s
csum[0] = uint8(s & 0xff)
csum[1] = uint8(s >> 8)
}
func fillIPHdr(hdr []byte, payloadLen uint16) {
// version + IHL
hdr[0] = ip4Ver | (minIPHdrLen / 4)
// total length
binary.BigEndian.PutUint16(hdr[2:4], uint16(len(hdr))+payloadLen)
// identification
if _, err := rand.Read(hdr[4:5]); err != nil {
panic(err)
}
// TTL
hdr[8] = 16
// Protocol
hdr[9] = unix.IPPROTO_UDP
// dst IP
copy(hdr[16:20], net.IPv4bcast.To4())
// compute IP hdr checksum
chksum(hdr[0:len(hdr)], hdr[10:12])
}
func fillUDPHdr(hdr []byte, payloadLen uint16) {
// src port
binary.BigEndian.PutUint16(hdr[0:2], srcPort)
// dest port
binary.BigEndian.PutUint16(hdr[2:4], dstPort)
// length
binary.BigEndian.PutUint16(hdr[4:6], udpHdrLen+payloadLen)
}
func swap16(x uint16) uint16 {
var b [2]byte
binary.BigEndian.PutUint16(b[:], x)
return binary.LittleEndian.Uint16(b[:])
}

View File

@ -1,74 +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,26 +0,0 @@
load("@io_bazel_rules_go//go:def.bzl", "go_library")
go_library(
name = "go_default_library",
srcs = [
"sspi.go",
"sspi_unsupported.go",
],
importmap = "k8s.io/kubernetes/vendor/github.com/vmware/photon-controller-go-sdk/SSPI",
importpath = "github.com/vmware/photon-controller-go-sdk/SSPI",
visibility = ["//visibility:public"],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)

View File

@ -1,27 +0,0 @@
Copyright (c) 2012 The Go Authors. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google Inc. nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View File

@ -1,3 +0,0 @@
SSPI implementation in this directory is taken from https://github.com/WillHipschman/sspi-prototype (git commit: 4feee8f2e75857bb51345fdfc8e3c091edc959b4)
Implementation is modified to make sure that it only compiles on Windows.
For non-Windows platforms, please look at sspi_unspported.go

View File

@ -1,276 +0,0 @@
// +build windows
package SSPI
import (
"fmt"
"strings"
"syscall"
"unsafe"
)
var (
secur32_dll = syscall.NewLazyDLL("secur32.dll")
initSecurityInterface = secur32_dll.NewProc("InitSecurityInterfaceW")
sec_fn *SecurityFunctionTable
)
func init() {
ptr, _, _ := initSecurityInterface.Call()
sec_fn = (*SecurityFunctionTable)(unsafe.Pointer(ptr))
}
const (
SEC_E_OK = 0
SECPKG_CRED_OUTBOUND = 2
SEC_WINNT_AUTH_IDENTITY_UNICODE = 2
ISC_REQ_DELEGATE = 0x00000001
ISC_REQ_REPLAY_DETECT = 0x00000004
ISC_REQ_SEQUENCE_DETECT = 0x00000008
ISC_REQ_CONFIDENTIALITY = 0x00000010
ISC_REQ_CONNECTION = 0x00000800
SECURITY_NETWORK_DREP = 0
SEC_I_CONTINUE_NEEDED = 0x00090312
SEC_I_COMPLETE_NEEDED = 0x00090313
SEC_I_COMPLETE_AND_CONTINUE = 0x00090314
SECBUFFER_VERSION = 0
SECBUFFER_TOKEN = 2
NTLMBUF_LEN = 12000
)
const ISC_REQ = ISC_REQ_CONFIDENTIALITY |
ISC_REQ_REPLAY_DETECT |
ISC_REQ_SEQUENCE_DETECT |
ISC_REQ_CONNECTION |
ISC_REQ_DELEGATE
type SecurityFunctionTable struct {
dwVersion uint32
EnumerateSecurityPackages uintptr
QueryCredentialsAttributes uintptr
AcquireCredentialsHandle uintptr
FreeCredentialsHandle uintptr
Reserved2 uintptr
InitializeSecurityContext uintptr
AcceptSecurityContext uintptr
CompleteAuthToken uintptr
DeleteSecurityContext uintptr
ApplyControlToken uintptr
QueryContextAttributes uintptr
ImpersonateSecurityContext uintptr
RevertSecurityContext uintptr
MakeSignature uintptr
VerifySignature uintptr
FreeContextBuffer uintptr
QuerySecurityPackageInfo uintptr
Reserved3 uintptr
Reserved4 uintptr
Reserved5 uintptr
Reserved6 uintptr
Reserved7 uintptr
Reserved8 uintptr
QuerySecurityContextToken uintptr
EncryptMessage uintptr
DecryptMessage uintptr
}
type SEC_WINNT_AUTH_IDENTITY struct {
User *uint16
UserLength uint32
Domain *uint16
DomainLength uint32
Password *uint16
PasswordLength uint32
Flags uint32
}
type TimeStamp struct {
LowPart uint32
HighPart int32
}
type SecHandle struct {
dwLower uintptr
dwUpper uintptr
}
type SecBuffer struct {
cbBuffer uint32
BufferType uint32
pvBuffer *byte
}
type SecBufferDesc struct {
ulVersion uint32
cBuffers uint32
pBuffers *SecBuffer
}
type SSPIAuth struct {
Domain string
UserName string
Password string
Service string
cred SecHandle
ctxt SecHandle
}
type Auth interface {
InitialBytes() ([]byte, error)
NextBytes([]byte) ([]byte, error)
Free()
}
// GetAuth returns SSPI auth object initialized with given params and true for success
// In case of error, it will return nil SSPI object and false for failure
func GetAuth(user, password, service, workstation string) (Auth, bool) {
if user == "" {
return &SSPIAuth{Service: service}, true
}
if !strings.ContainsRune(user, '\\') {
return nil, false
}
domain_user := strings.SplitN(user, "\\", 2)
return &SSPIAuth{
Domain: domain_user[0],
UserName: domain_user[1],
Password: password,
Service: service,
}, true
}
func (auth *SSPIAuth) InitialBytes() ([]byte, error) {
var identity *SEC_WINNT_AUTH_IDENTITY
if auth.UserName != "" {
identity = &SEC_WINNT_AUTH_IDENTITY{
Flags: SEC_WINNT_AUTH_IDENTITY_UNICODE,
Password: syscall.StringToUTF16Ptr(auth.Password),
PasswordLength: uint32(len(auth.Password)),
Domain: syscall.StringToUTF16Ptr(auth.Domain),
DomainLength: uint32(len(auth.Domain)),
User: syscall.StringToUTF16Ptr(auth.UserName),
UserLength: uint32(len(auth.UserName)),
}
}
var ts TimeStamp
sec_ok, _, _ := syscall.Syscall9(sec_fn.AcquireCredentialsHandle,
9,
0,
uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr("Negotiate"))),
SECPKG_CRED_OUTBOUND,
0,
uintptr(unsafe.Pointer(identity)),
0,
0,
uintptr(unsafe.Pointer(&auth.cred)),
uintptr(unsafe.Pointer(&ts)))
if sec_ok != SEC_E_OK {
return nil, fmt.Errorf("AcquireCredentialsHandle failed %x", sec_ok)
}
var buf SecBuffer
var desc SecBufferDesc
desc.ulVersion = SECBUFFER_VERSION
desc.cBuffers = 1
desc.pBuffers = &buf
outbuf := make([]byte, NTLMBUF_LEN)
buf.cbBuffer = NTLMBUF_LEN
buf.BufferType = SECBUFFER_TOKEN
buf.pvBuffer = &outbuf[0]
var attrs uint32
sec_ok, _, _ = syscall.Syscall12(sec_fn.InitializeSecurityContext,
12,
uintptr(unsafe.Pointer(&auth.cred)),
0,
uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(auth.Service))),
ISC_REQ,
0,
SECURITY_NETWORK_DREP,
0,
0,
uintptr(unsafe.Pointer(&auth.ctxt)),
uintptr(unsafe.Pointer(&desc)),
uintptr(unsafe.Pointer(&attrs)),
uintptr(unsafe.Pointer(&ts)))
if sec_ok == SEC_I_COMPLETE_AND_CONTINUE ||
sec_ok == SEC_I_COMPLETE_NEEDED {
syscall.Syscall6(sec_fn.CompleteAuthToken,
2,
uintptr(unsafe.Pointer(&auth.ctxt)),
uintptr(unsafe.Pointer(&desc)),
0, 0, 0, 0)
} else if sec_ok != SEC_E_OK &&
sec_ok != SEC_I_CONTINUE_NEEDED {
syscall.Syscall6(sec_fn.FreeCredentialsHandle,
1,
uintptr(unsafe.Pointer(&auth.cred)),
0, 0, 0, 0, 0)
return nil, fmt.Errorf("InitialBytes InitializeSecurityContext failed %x", sec_ok)
}
return outbuf[:buf.cbBuffer], nil
}
func (auth *SSPIAuth) NextBytes(bytes []byte) ([]byte, error) {
var in_buf, out_buf SecBuffer
var in_desc, out_desc SecBufferDesc
in_desc.ulVersion = SECBUFFER_VERSION
in_desc.cBuffers = 1
in_desc.pBuffers = &in_buf
out_desc.ulVersion = SECBUFFER_VERSION
out_desc.cBuffers = 1
out_desc.pBuffers = &out_buf
in_buf.BufferType = SECBUFFER_TOKEN
in_buf.pvBuffer = &bytes[0]
in_buf.cbBuffer = uint32(len(bytes))
outbuf := make([]byte, NTLMBUF_LEN)
out_buf.BufferType = SECBUFFER_TOKEN
out_buf.pvBuffer = &outbuf[0]
out_buf.cbBuffer = NTLMBUF_LEN
var attrs uint32
var ts TimeStamp
sec_ok, _, _ := syscall.Syscall12(sec_fn.InitializeSecurityContext,
12,
uintptr(unsafe.Pointer(&auth.cred)),
uintptr(unsafe.Pointer(&auth.ctxt)),
uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(auth.Service))),
ISC_REQ,
0,
SECURITY_NETWORK_DREP,
uintptr(unsafe.Pointer(&in_desc)),
0,
uintptr(unsafe.Pointer(&auth.ctxt)),
uintptr(unsafe.Pointer(&out_desc)),
uintptr(unsafe.Pointer(&attrs)),
uintptr(unsafe.Pointer(&ts)))
if sec_ok == SEC_I_COMPLETE_AND_CONTINUE ||
sec_ok == SEC_I_COMPLETE_NEEDED {
syscall.Syscall6(sec_fn.CompleteAuthToken,
2,
uintptr(unsafe.Pointer(&auth.ctxt)),
uintptr(unsafe.Pointer(&out_desc)),
0, 0, 0, 0)
} else if sec_ok != SEC_E_OK &&
sec_ok != SEC_I_CONTINUE_NEEDED {
return nil, fmt.Errorf("NextBytes InitializeSecurityContext failed %x", sec_ok)
}
return outbuf[:out_buf.cbBuffer], nil
}
func (auth *SSPIAuth) Free() {
syscall.Syscall6(sec_fn.DeleteSecurityContext,
1,
uintptr(unsafe.Pointer(&auth.ctxt)),
0, 0, 0, 0, 0)
syscall.Syscall6(sec_fn.FreeCredentialsHandle,
1,
uintptr(unsafe.Pointer(&auth.cred)),
0, 0, 0, 0, 0)
}

View File

@ -1,12 +0,0 @@
// Copyright (c) 2017 VMware, Inc. All Rights Reserved.
//
// This product is licensed to you under the Apache License, Version 2.0 (the "License").
// You may not use this product except in compliance with the License.
//
// This product may include a number of subcomponents with separate copyright notices and
// license terms. Your use of these subcomponents is subject to the terms and conditions
// of the subcomponent's license, as noted in the LICENSE file.
// +build !windows
package SSPI

View File

@ -1,51 +0,0 @@
load("@io_bazel_rules_go//go:def.bzl", "go_library")
go_library(
name = "go_default_library",
srcs = [
"apitypes.go",
"auth.go",
"availabilityzones.go",
"client.go",
"deployments.go",
"disks.go",
"flavors.go",
"hosts.go",
"images.go",
"info.go",
"networks.go",
"projects.go",
"resourcetickets.go",
"restclient.go",
"routers.go",
"services.go",
"status.go",
"subnets.go",
"tasks.go",
"tenants.go",
"util.go",
"virtualnetworks.go",
"vms.go",
],
importmap = "k8s.io/kubernetes/vendor/github.com/vmware/photon-controller-go-sdk/photon",
importpath = "github.com/vmware/photon-controller-go-sdk/photon",
visibility = ["//visibility:public"],
deps = ["//vendor/github.com/vmware/photon-controller-go-sdk/photon/lightwave:go_default_library"],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [
":package-srcs",
"//vendor/github.com/vmware/photon-controller-go-sdk/photon/lightwave:all-srcs",
],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)

View File

@ -1,802 +0,0 @@
// Copyright (c) 2016 VMware, Inc. All Rights Reserved.
//
// This product is licensed to you under the Apache License, Version 2.0 (the "License").
// You may not use this product except in compliance with the License.
//
// This product may include a number of subcomponents with separate copyright notices and
// license terms. Your use of these subcomponents is subject to the terms and conditions
// of the subcomponent's license, as noted in the LICENSE file.
package photon
import (
"fmt"
)
type Entity struct {
ID string `json:"id"`
Kind string `json:"kind"`
}
// Implement a generic sdk error
type SdkError struct {
Message string
}
func (e SdkError) Error() string {
return fmt.Sprintf("photon: %v", e.Message)
}
// Represents an error from the Photon API.
type ApiError struct {
Code string `json:"code"`
Data map[string]interface{} `json:"data"`
Message string `json:"message"`
HttpStatusCode int `json:"-"` // Not part of API contract
}
// Implement Go error interface for ApiError
func (e ApiError) Error() string {
return fmt.Sprintf(
"photon: { HTTP status: '%v', code: '%v', message: '%v', data: '%v' }",
e.HttpStatusCode,
e.Code,
e.Message,
e.Data)
}
// Used to represent a generic HTTP error, i.e. an unexpected HTTP 500.
type HttpError struct {
StatusCode int
Message string
}
// Implementation of error interface for HttpError
func (e HttpError) Error() string {
return fmt.Sprintf("photon: HTTP %d: %v", e.StatusCode, e.Message)
}
// Represents an Photon task that has entered into an error state.
// Photon task errors can be caught and type-checked against with
// the usual Go idiom.
type TaskError struct {
ID string `json:"id"`
Step Step `json:"step,omitempty"`
}
// Implement Go error interface for TaskError.
func (e TaskError) Error() string {
return fmt.Sprintf("photon: Task '%s' is in error state: {@step==%s}", e.ID, GetStep(e.Step))
}
// An error representing a timeout while waiting for a task to complete.
type TaskTimeoutError struct {
ID string
}
// Implement Go error interface for TaskTimeoutError.
func (e TaskTimeoutError) Error() string {
return fmt.Sprintf("photon: Timed out waiting for task '%s'. "+
"Task may not be in error state, examine task for full details.", e.ID)
}
// Represents an operation (Step) within a Task.
type Step struct {
ID string `json:"id"`
Operation string `json:"operation,omitempty"`
State string `json:"state"`
StartedTime int64 `json:"startedTime"`
EndTime int64 `json:"endTime,omitempty"`
QueuedTime int64 `json:"queuedTime"`
Sequence int `json:"sequence,omitempty"`
ResourceProperties map[string]interface{} `json:"resourceProperties,omitempty"`
Errors []ApiError `json:"errors,omitempty"`
Warnings []ApiError `json:"warnings,omitempty"`
Options map[string]interface{} `json:"options,omitempty"`
SelfLink string `json:"selfLink,omitempty"`
}
// Implement Go error interface for Step.
func GetStep(s Step) string {
return fmt.Sprintf("{\"sequence\"=>\"%d\",\"state\"=>\"%s\",\"errors\"=>%s,\"warnings\"=>%s,\"operation\"=>\"%s\","+
"\"startedTime\"=>\"%d\",\"queuedTime\"=>\"%d\",\"endTime\"=>\"%d\",\"options\"=>%s}",
s.Sequence, s.State, s.Errors, s.Warnings, s.Operation, s.StartedTime, s.QueuedTime,
s.EndTime, s.Options)
}
// Represents an asynchronous task.
type Task struct {
ID string `json:"id"`
Operation string `json:"operation,omitempty"`
State string `json:"state"`
StartedTime int64 `json:"startedTime"`
EndTime int64 `json:"endTime,omitempty"`
QueuedTime int64 `json:"queuedTime"`
Entity Entity `json:"entity,omitempty"`
SelfLink string `json:"selfLink,omitempty"`
Steps []Step `json:"steps,omitempty"`
ResourceProperties interface{} `json:"resourceProperties,omitempty"`
}
// Represents multiple tasks returned by the API.
type TaskList struct {
Items []Task `json:"items"`
}
// Options for GetTasks API.
type TaskGetOptions struct {
State string `urlParam:"state"`
Kind string `urlParam:"kind"`
EntityID string `urlParam:"entityId"`
EntityKind string `urlParam:"entityKind"`
}
type BaseCompact struct {
Name string `json:"name"`
ID string `json:"id"`
}
type QuotaLineItem struct {
Unit string `json:"unit"`
Value float64 `json:"value"`
Key string `json:"key"`
}
// Creation spec for locality.
type LocalitySpec struct {
Kind string `json:"kind"`
ID string `json:"id"`
}
// Creation spec for disks.
type DiskCreateSpec struct {
Flavor string `json:"flavor"`
Kind string `json:"kind"`
CapacityGB int `json:"capacityGb"`
Affinities []LocalitySpec `json:"affinities,omitempty"`
Name string `json:"name"`
Tags []string `json:"tags,omitempty"`
}
// Represents a persistent disk.
type PersistentDisk struct {
Flavor string `json:"flavor"`
Cost []QuotaLineItem `json:"cost"`
Kind string `json:"kind"`
Datastore string `json:"datastore,omitempty"`
CapacityGB int `json:"capacityGb,omitempty"`
Name string `json:"name"`
State string `json:"state"`
ID string `json:"id"`
VMs []string `json:"vms"`
Tags []string `json:"tags,omitempty"`
SelfLink string `json:"selfLink,omitempty"`
}
// Represents multiple persistent disks returned by the API.
type DiskList struct {
Items []PersistentDisk `json:"items"`
}
// Creation spec for projects.
type ProjectCreateSpec struct {
ResourceTicket ResourceTicketReservation `json:"resourceTicket"`
Name string `json:"name"`
SecurityGroups []string `json:"securityGroups,omitempty"`
}
// Represents multiple projects returned by the API.
type ProjectList struct {
Items []ProjectCompact `json:"items"`
}
// Compact representation of projects.
type ProjectCompact struct {
Kind string `json:"kind"`
ResourceTicket ProjectTicket `json:"resourceTicket"`
Name string `json:"name"`
ID string `json:"id"`
Tags []string `json:"tags"`
SelfLink string `json:"selfLink"`
SecurityGroups []SecurityGroup `json:"securityGroups"`
}
type ProjectTicket struct {
TenantTicketID string `json:"tenantTicketId"`
Usage []QuotaLineItem `json:"usage"`
TenantTicketName string `json:"tenantTicketName"`
Limits []QuotaLineItem `json:"limits"`
}
// Represents an image.
type Image struct {
Size int64 `json:"size"`
Kind string `json:"kind"`
Name string `json:"name"`
State string `json:"state"`
ID string `json:"id"`
Tags []string `json:"tags"`
SelfLink string `json:"selfLink"`
Settings []ImageSetting `json:"settings"`
ReplicationType string `json:"replicationType"`
ReplicationProgress string `json:"replicationProgress"`
SeedingProgress string `json:"seedingProgress"`
}
// Represents an image setting
type ImageSetting struct {
Name string `json:"name"`
DefaultValue string `json:"defaultValue"`
}
// Creation spec for images.
type ImageCreateOptions struct {
ReplicationType string
}
// Represents multiple images returned by the API.
type Images struct {
Items []Image `json:"items"`
}
// Represents a component with status.
type Component struct {
Component string
Message string
Status string
}
// Represents status of the photon system.
type Status struct {
Status string
Components []Component
}
// Represents a single tenant.
type Tenant struct {
Projects []BaseCompact `json:"projects"`
ResourceTickets []BaseCompact `json:"resourceTickets"`
Kind string `json:"kind"`
Name string `json:"name"`
ID string `json:"id"`
SelfLink string `json:"selfLink"`
Tags []string `json:"tags"`
SecurityGroups []SecurityGroup `json:"securityGroups"`
}
// Represents multiple tenants returned by the API.
type Tenants struct {
Items []Tenant `json:"items"`
}
// Creation spec for tenants.
type TenantCreateSpec struct {
Name string `json:"name"`
SecurityGroups []string `json:"securityGroups,omitempty"`
}
// Creation spec for resource tickets.
type ResourceTicketCreateSpec struct {
Name string `json:"name"`
Limits []QuotaLineItem `json:"limits"`
}
// Represents a single resource ticket.
type ResourceTicket struct {
Kind string `json:"kind"`
Usage []QuotaLineItem `json:"usage"`
TenantId string `json:"tenantId"`
Name string `json:"name"`
ID string `json:"id"`
Limits []QuotaLineItem `json:"limits"`
Tags []string `json:"tags"`
SelfLink string `json:"selfLink"`
}
// Represents multiple resource tickets returned by the API.
type ResourceList struct {
Items []ResourceTicket `json:"items"`
}
// Represents a resource reservation on a resource ticket.
type ResourceTicketReservation struct {
Name string `json:"name"`
Limits []QuotaLineItem `json:"limits"`
}
// Creation spec for VMs.
type VmCreateSpec struct {
Flavor string `json:"flavor"`
SourceImageID string `json:"sourceImageId"`
AttachedDisks []AttachedDisk `json:"attachedDisks"`
Affinities []LocalitySpec `json:"affinities,omitempty"`
Name string `json:"name"`
Tags []string `json:"tags,omitempty"`
Subnets []string `json:"subnets,omitempty"`
Environment map[string]string `json:"environment,omitempty"`
}
// Represents possible operations for VMs. Valid values include:
// START_VM, STOP_VM, RESTART_VM, SUSPEND_VM, RESUME_VM
type VmOperation struct {
Operation string `json:"operation"`
Arguments map[string]interface{} `json:"arguments,omitempty"`
}
// Represents metadata that can be set on a VM.
type VmMetadata struct {
Metadata map[string]string `json:"metadata"`
}
// Represents tags that can be set on a VM.
type VmTag struct {
Tag string `json:"value"`
}
// Represents a single attached disk.
type AttachedDisk struct {
Flavor string `json:"flavor"`
Kind string `json:"kind"`
CapacityGB int `json:"capacityGb,omitempty"`
Name string `json:"name"`
State string `json:"state"`
ID string `json:"id,omitempty"`
BootDisk bool `json:"bootDisk"`
}
// Represents a single VM.
type VM struct {
SourceImageID string `json:"sourceImageId,omitempty"`
Cost []QuotaLineItem `json:"cost"`
Kind string `json:"kind"`
AttachedDisks []AttachedDisk `json:"attachedDisks"`
Datastore string `json:"datastore,omitempty"`
AttachedISOs []ISO `json:"attachedIsos,omitempty"`
Tags []string `json:"tags,omitempty"`
Metadata map[string]string `json:"metadata,omitempty"`
SelfLink string `json:"selfLink,omitempty"`
Flavor string `json:"flavor"`
Host string `json:"host,omitempty"`
Name string `json:"name"`
State string `json:"state"`
ID string `json:"id"`
FloatingIp string `json:"floatingIp"`
}
// Represents multiple VMs returned by the API.
type VMs struct {
Items []VM `json:"items"`
}
// Represents an ISO.
type ISO struct {
Size int64 `json:"size,omitempty"`
Kind string `json:"kind,omitempty"`
Name string `json:"name"`
ID string `json:"id"`
}
// Represents operations for disks.
type VmDiskOperation struct {
DiskID string `json:"diskId"`
Arguments map[string]interface{} `json:"arguments,omitempty"`
}
// Represents a floating IP operation related to a VM.
type VmFloatingIpSpec struct {
NetworkId string `json:"networkId"`
}
// Creation spec for flavors.
type FlavorCreateSpec struct {
Cost []QuotaLineItem `json:"cost"`
Kind string `json:"kind"`
Name string `json:"name"`
}
// Represents a single flavor.
type Flavor struct {
Cost []QuotaLineItem `json:"cost"`
Kind string `json:"kind"`
Name string `json:"name"`
ID string `json:"id"`
Tags []string `json:"tags"`
SelfLink string `json:"selfLink"`
State string `json:"state"`
}
// Represents multiple flavors returned by the API.
type FlavorList struct {
Items []Flavor `json:"items"`
}
// Creation spec for hosts.
type HostCreateSpec struct {
Username string `json:"username"`
Password string `json:"password"`
AvailabilityZone string `json:"availabilityZone,omitempty"`
Metadata map[string]string `json:"metadata,omitempty"`
Address string `json:"address"`
Tags []string `json:"usageTags"`
}
// Represents a host
type Host struct {
Username string `json:"username"`
Password string `json:"password"`
Address string `json:"address"`
Kind string `json:"kind"`
ID string `json:"id"`
AvailabilityZone string `json:"availabilityZone,omitempty"`
Tags []string `json:"usageTags"`
Metadata map[string]string `json:"metadata,omitempty"`
SelfLink string `json:"selfLink"`
State string `json:"state"`
EsxVersion string `json:"esxVersion"`
}
// Represents multiple hosts returned by the API.
type Hosts struct {
Items []Host `json:"items"`
}
// Creation spec for deployments.
type DeploymentCreateSpec struct {
NTPEndpoint interface{} `json:"ntpEndpoint"`
UseImageDatastoreForVms bool `json:"useImageDatastoreForVms"`
SyslogEndpoint interface{} `json:"syslogEndpoint"`
Stats *StatsInfo `json:"stats"`
ImageDatastores []string `json:"imageDatastores"`
Auth *AuthInfo `json:"auth"`
NetworkConfiguration *NetworkConfigurationCreateSpec `json:"networkConfiguration"`
LoadBalancerEnabled bool `json:"loadBalancerEnabled"`
}
// Deployment deploy config.
type DeploymentDeployOperation struct {
DesiredState string `json:"desiredState"`
}
type MigrationStatus struct {
CompletedDataMigrationCycles int `json:"completedDataMigrationCycles"`
DataMigrationCycleProgress int `json:"dataMigrationCycleProgress"`
DataMigrationCycleSize int `json:"dataMigrationCycleSize"`
VibsUploaded int `json:"vibsUploaded"`
VibsUploading int `json:"vibsUploading"`
}
// Represents a deployment
type Deployment struct {
NTPEndpoint string `json:"ntpEndpoint,omitempty"`
UseImageDatastoreForVms bool `json:"useImageDatastoreForVms,omitempty"`
Auth *AuthInfo `json:"auth"`
NetworkConfiguration *NetworkConfiguration `json:"networkConfiguration"`
Kind string `json:"kind"`
SyslogEndpoint string `json:"syslogEndpoint,omitempty"`
Stats *StatsInfo `json:"stats,omitempty"`
State string `json:"state"`
ID string `json:"id"`
ImageDatastores []string `json:"imageDatastores"`
SelfLink string `json:"selfLink"`
Migration *MigrationStatus `json:"migrationStatus,omitempty"`
ServiceConfigurations []ServiceConfiguration `json:"serviceConfigurations,omitempty"`
LoadBalancerEnabled bool `json:"loadBalancerEnabled"`
LoadBalancerAddress string `json:"loadBalancerAddress"`
}
// Represents multiple deployments returned by the API.
type Deployments struct {
Items []Deployment `json:"items"`
}
// Represents source load balacer address to migrate deployment
type InitializeMigrationOperation struct {
SourceNodeGroupReference string `json:"sourceNodeGroupReference"`
}
// Represents source load balacer address to finish migration of deployment
type FinalizeMigrationOperation struct {
SourceNodeGroupReference string `json:"sourceNodeGroupReference"`
}
// Represents stats information
type StatsInfo struct {
Enabled bool `json:"enabled,omitempty"`
StoreEndpoint string `json:"storeEndpoint,omitempty"`
StorePort int `json:"storePort,omitempty"`
}
// Represents authentication information
type AuthInfo struct {
Password string `json:"password,omitempty"`
Endpoint string `json:"endpoint,omitempty"`
Tenant string `json:"tenant,omitempty"`
Port int `json:"port,omitempty"`
SecurityGroups []string `json:"securityGroups,omitempty"`
Username string `json:"username,omitempty"`
}
// Represents ip range
type IpRange struct {
Start string `json:"start,omitempty"`
End string `json:"end,omitempty"`
}
// Represents creation spec for network configuration.
type NetworkConfigurationCreateSpec struct {
Enabled bool `json:"sdnEnabled,omitempty"`
Address string `json:"networkManagerAddress,omitempty"`
Username string `json:"networkManagerUsername,omitempty"`
Password string `json:"networkManagerPassword,omitempty"`
NetworkZoneId string `json:"networkZoneId,omitempty"`
TopRouterId string `json:"networkTopRouterId,omitempty"`
EdgeIpPoolId string `json:"networkEdgeIpPoolId,omitempty"`
HostUplinkPnic string `json:"networkHostUplinkPnic,omitempty"`
IpRange string `json:"ipRange,omitempty"`
ExternalIpRange *IpRange `json:"externalIpRange,omitempty"`
DhcpServers []string `json:"dhcpServers,omitempty"`
}
// Represents network configuration.
type NetworkConfiguration struct {
Enabled bool `json:"sdnEnabled,omitempty"`
Address string `json:"networkManagerAddress,omitempty"`
Username string `json:"networkManagerUsername,omitempty"`
Password string `json:"networkManagerPassword,omitempty"`
NetworkZoneId string `json:"networkZoneId,omitempty"`
TopRouterId string `json:"networkTopRouterId,omitempty"`
EdgeIpPoolId string `json:"networkEdgeIpPoolId,omitempty"`
HostUplinkPnic string `json:"networkHostUplinkPnic,omitempty"`
IpRange string `json:"ipRange,omitempty"`
FloatingIpRange *IpRange `json:"floatingIpRange,omitempty"`
SnatIp string `json:"snatIp,omitempty"`
DhcpServers []string `json:"dhcpServers,omitempty"`
}
// Creation spec for networks.
type NetworkCreateSpec struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
PortGroups []string `json:"portGroups"`
}
// Represents a subnet
type Network struct {
Kind string `json:"kind"`
Name string `json:"name"`
Description string `json:"description,omitempty"`
State string `json:"state"`
ID string `json:"id"`
PortGroups []string `json:"portGroups"`
Tags []string `json:"tags,omitempty"`
SelfLink string `json:"selfLink"`
IsDefault bool `json:"isDefault"`
}
// Represents multiple subnets returned by the API
type Networks struct {
Items []Network `json:"items"`
}
// Create spec for virtual subnet
type VirtualSubnetCreateSpec struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
RoutingType string `json:"routingType"`
Size int `json:"size"`
ReservedStaticIpSize int `json:"reservedStaticIpSize,omitempty"`
}
// Represents a virtual network
type VirtualSubnet struct {
ID string `json:"id"`
Name string `json:"name"`
Description string `json:"description,omitempty"`
State string `json:"state"`
RoutingType string `json:"routingType"`
IsDefault bool `json:"isDefault"`
Cidr string `json:"cidr,omitempty"`
LowIpDynamic string `json:"lowIpDynamic,omitempty"`
HighIpDynamic string `json:"highIpDynamic,omitempty"`
LowIpStatic string `json:"lowIpStatic,omitempty"`
HighIpStatic string `json:"highIpStatic,omitempty"`
ReservedIpList []string `json:"reservedIpList"`
SelfLink string `json:"selfLink"`
}
// Represents multiple virtual subnets returned
type VirtualSubnets struct {
Items []VirtualSubnet `json:"items"`
}
// Represents a router
type Router struct {
ID string `json:"id"`
Kind string `json:"kind"`
Name string `json:"name"`
PrivateIpCidr string `json:"privateIpCidr"`
}
// Represents multiple routers returned by the API.
type Routers struct {
Items []Router `json:"items"`
}
type RouterCreateSpec struct {
Name string `json:"name"`
PrivateIpCidr string `json:"privateIpCidr"`
}
// Represents name that can be set for router
type RouterUpdateSpec struct {
RouterName string `json:"name"`
}
// Creation spec for Service Configuration.
type ServiceConfigurationSpec struct {
Type string `json:"type"`
ImageID string `json:"imageId"`
}
// Represnts a Service configuration.
type ServiceConfiguration struct {
Kind string `json:"kind"`
Type string `json:"type"`
ImageID string `json:"imageId"`
}
// Creation spec for services.
type ServiceCreateSpec struct {
Name string `json:"name"`
Type string `json:"type"`
VMFlavor string `json:"vmFlavor,omitempty"`
MasterVmFlavor string `json:"masterVmFlavor,omitempty"`
WorkerVmFlavor string `json:"workerVmFlavor,omitempty"`
DiskFlavor string `json:"diskFlavor,omitempty"`
NetworkID string `json:"vmNetworkId,omitempty"`
ImageID string `json:"imageId,omitempty"`
WorkerCount int `json:"workerCount"`
BatchSizeWorker int `json:"workerBatchExpansionSize,omitempty"`
ExtendedProperties map[string]string `json:"extendedProperties"`
}
// Represents a service
type Service struct {
Kind string `json:"kind"`
Name string `json:"name"`
State string `json:"state"`
ID string `json:"id"`
Type string `json:"type"`
ProjectID string `json:"projectID,omitempty"`
WorkerCount int `json:"workerCount"`
SelfLink string `json:"selfLink,omitempty"`
ErrorReason string `json:"errorReason,omitempty"`
ExtendedProperties map[string]string `json:"extendedProperties"`
}
// Represents multiple services returned by the API
type Services struct {
Items []Service `json:"items"`
}
// Represents service size that can be resized for service
type ServiceResizeOperation struct {
NewWorkerCount int `json:"newWorkerCount"`
}
// Represents service imageId that can be updated during change version
type ServiceChangeVersionOperation struct {
NewImageID string `json:"newImageId"`
}
// Represents a security group
type SecurityGroup struct {
Name string `json:"name"`
Inherited bool `json:"inherited"`
}
// Represents set_security_groups spec
type SecurityGroupsSpec struct {
Items []string `json:"items"`
}
// Represents single availability zone.
type AvailabilityZone struct {
Kind string `json:"kind"`
Name string `json:"name"`
State string `json:"state"`
ID string `json:"id"`
SelfLink string `json:"selfLink"`
}
// Represents multiple availability zones returned by the API.
type AvailabilityZones struct {
Items []AvailabilityZone `json:"items"`
}
// Creation spec for availability zones.
type AvailabilityZoneCreateSpec struct {
Name string `json:"name"`
}
// Represents availability zone that can be set for host
type HostSetAvailabilityZoneOperation struct {
AvailabilityZoneId string `json:"availabilityZoneId"`
}
// Represents the list of image datastores.
type ImageDatastores struct {
Items []string `json:"items"`
}
// Image creation spec.
type ImageCreateSpec struct {
Name string `json:"name"`
ReplicationType string `json:"replicationType"`
}
// Represents deployment info
type Info struct {
BaseVersion string `json:"baseVersion"`
FullVersion string `json:"fullVersion"`
GitCommitHash string `json:"gitCommitHash"`
NetworkType string `json:"networkType"`
}
// NSX configuration spec
type NsxConfigurationSpec struct {
NsxAddress string `json:"nsxAddress"`
NsxUsername string `json:"nsxUsername"`
NsxPassword string `json:"nsxPassword"`
DhcpServerAddresses map[string]string `json:"dhcpServerAddresses"`
PrivateIpRootCidr string `json:"privateIpRootCidr"`
FloatingIpRootRange IpRange `json:"floatingIpRootRange"`
T0RouterId string `json:"t0RouterId"`
EdgeClusterId string `json:"edgeClusterId"`
OverlayTransportZoneId string `json:"overlayTransportZoneId"`
TunnelIpPoolId string `json:"tunnelIpPoolId"`
HostUplinkPnic string `json:"hostUplinkPnic"`
HostUplinkVlanId int `json:"hostUplinkVlanId"`
}
// Represents a subnet
type Subnet struct {
ID string `json:"id"`
Kind string `json:"kind"`
Name string `json:"name"`
Description string `json:"description,omitempty"`
PrivateIpCidr string `json:"privateIpCidr"`
ReservedIps map[string]string `json:"reservedIps"`
State string `json:"state"`
}
// Represents multiple subnets returned by the API.
type Subnets struct {
Items []Subnet `json:"items"`
}
// Creation spec for subnets.
type SubnetCreateSpec struct {
Name string `json:"name"`
Description string `json:"description"`
PrivateIpCidr string `json:"privateIpCidr"`
}
// Represents name that can be set for subnet
type SubnetUpdateSpec struct {
SubnetName string `json:"name"`
}
// Identity and Access Management (IAM)
// IAM Policy entry
type PolicyEntry struct {
Principal string `json:"principal"`
Roles []string `json:"roles"`
}
type PolicyDelta struct {
Principal string `json:"principal"`
Action string `json:"action"`
Role string `json:"role"`
}

View File

@ -1,143 +0,0 @@
// Copyright (c) 2016 VMware, Inc. All Rights Reserved.
//
// This product is licensed to you under the Apache License, Version 2.0 (the "License").
// You may not use this product except in compliance with the License.
//
// This product may include a number of subcomponents with separate copyright notices and
// license terms. Your use of these subcomponents is subject to the terms and conditions
// of the subcomponent's license, as noted in the LICENSE file.
package photon
import (
"encoding/json"
"fmt"
"github.com/vmware/photon-controller-go-sdk/photon/lightwave"
)
// Contains functionality for auth API.
type AuthAPI struct {
client *Client
}
const authUrl string = rootUrl + "/auth"
// Gets authentication info.
func (api *AuthAPI) Get() (info *AuthInfo, err error) {
res, err := api.client.restClient.Get(api.client.Endpoint+authUrl, nil)
if err != nil {
return
}
defer res.Body.Close()
res, err = getError(res)
if err != nil {
return
}
info = &AuthInfo{}
err = json.NewDecoder(res.Body).Decode(info)
return
}
// Gets Tokens from username/password.
func (api *AuthAPI) GetTokensByPassword(username string, password string) (tokenOptions *TokenOptions, err error) {
oidcClient, err := api.buildOIDCClient()
if err != nil {
return
}
tokenResponse, err := oidcClient.GetTokenByPasswordGrant(username, password)
if err != nil {
return
}
return api.toTokenOptions(tokenResponse), nil
}
// GetTokensFromWindowsLogInContext gets tokens based on Windows logged in context
// In case of running on platform other than Windows, it returns error
func (api *AuthAPI) GetTokensFromWindowsLogInContext() (tokenOptions *TokenOptions, err error) {
oidcClient, err := api.buildOIDCClient()
if err != nil {
return
}
tokenResponse, err := oidcClient.GetTokensFromWindowsLogInContext()
if err != nil {
return
}
return api.toTokenOptions(tokenResponse), nil
}
// Gets tokens from refresh token.
func (api *AuthAPI) GetTokensByRefreshToken(refreshtoken string) (tokenOptions *TokenOptions, err error) {
oidcClient, err := api.buildOIDCClient()
if err != nil {
return
}
tokenResponse, err := oidcClient.GetTokenByRefreshTokenGrant(refreshtoken)
if err != nil {
return
}
return api.toTokenOptions(tokenResponse), nil
}
func (api *AuthAPI) getAuthEndpoint() (endpoint string, err error) {
authInfo, err := api.client.Auth.Get()
if err != nil {
return
}
if authInfo.Port == 0 {
authInfo.Port = 443
}
return fmt.Sprintf("https://%s:%d", authInfo.Endpoint, authInfo.Port), nil
}
func (api *AuthAPI) buildOIDCClient() (client *lightwave.OIDCClient, err error) {
authEndPoint, err := api.getAuthEndpoint()
if err != nil {
return
}
return lightwave.NewOIDCClient(
authEndPoint,
api.buildOIDCClientOptions(&api.client.options),
api.client.restClient.logger), nil
}
const tokenScope string = "openid offline_access rs_photon_platform at_groups"
func (api *AuthAPI) buildOIDCClientOptions(options *ClientOptions) *lightwave.OIDCClientOptions {
return &lightwave.OIDCClientOptions{
IgnoreCertificate: api.client.options.IgnoreCertificate,
RootCAs: api.client.options.RootCAs,
TokenScope: tokenScope,
}
}
func (api *AuthAPI) toTokenOptions(response *lightwave.OIDCTokenResponse) *TokenOptions {
return &TokenOptions{
AccessToken: response.AccessToken,
ExpiresIn: response.ExpiresIn,
RefreshToken: response.RefreshToken,
IdToken: response.IdToken,
TokenType: response.TokenType,
}
}
// Parse the given token details.
func (api *AuthAPI) parseTokenDetails(token string) (jwtToken *lightwave.JWTToken, err error) {
jwtToken = lightwave.ParseTokenDetails(token)
return jwtToken, nil
}
// Parse the given token raw details.
func (api *AuthAPI) parseRawTokenDetails(token string) (jwtToken []string, err error) {
jwtToken, err = lightwave.ParseRawTokenDetails(token)
return jwtToken, err
}

View File

@ -1,102 +0,0 @@
// Copyright (c) 2016 VMware, Inc. All Rights Reserved.
//
// This product is licensed to you under the Apache License, Version 2.0 (the "License").
// You may not use this product except in compliance with the License.
//
// This product may include a number of subcomponents with separate copyright notices and
// license terms. Your use of these subcomponents is subject to the terms and conditions
// of the subcomponent's license, as noted in the LICENSE file.
package photon
import (
"bytes"
"encoding/json"
)
// Contains functionality for availability zones API.
type AvailabilityZonesAPI struct {
client *Client
}
var availabilityzoneUrl string = rootUrl + "/availabilityzones"
// Creates availability zone.
func (api *AvailabilityZonesAPI) Create(availabilityzoneSpec *AvailabilityZoneCreateSpec) (task *Task, err error) {
body, err := json.Marshal(availabilityzoneSpec)
if err != nil {
return
}
res, err := api.client.restClient.Post(
api.client.Endpoint+availabilityzoneUrl,
"application/json",
bytes.NewReader(body),
api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}
// Gets availability zone with the specified ID.
func (api *AvailabilityZonesAPI) Get(id string) (availabilityzone *AvailabilityZone, err error) {
res, err := api.client.restClient.Get(api.getEntityUrl(id), api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
res, err = getError(res)
if err != nil {
return
}
availabilityzone = &AvailabilityZone{}
err = json.NewDecoder(res.Body).Decode(availabilityzone)
return
}
// Returns all availability zones on an photon instance.
func (api *AvailabilityZonesAPI) GetAll() (result *AvailabilityZones, err error) {
uri := api.client.Endpoint + availabilityzoneUrl
res, err := api.client.restClient.GetList(api.client.Endpoint, uri, api.client.options.TokenOptions)
if err != nil {
return
}
result = &AvailabilityZones{}
err = json.Unmarshal(res, result)
return
}
// Deletes the availability zone with specified ID.
func (api *AvailabilityZonesAPI) Delete(id string) (task *Task, err error) {
res, err := api.client.restClient.Delete(api.client.Endpoint+availabilityzoneUrl+"/"+id, api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}
// Gets all tasks with the specified availability zone ID, using options to filter the results.
// If options is nil, no filtering will occur.
func (api *AvailabilityZonesAPI) GetTasks(id string, options *TaskGetOptions) (result *TaskList, err error) {
uri := api.client.Endpoint + availabilityzoneUrl + "/" + id + "/tasks"
if options != nil {
uri += getQueryString(options)
}
res, err := api.client.restClient.GetList(api.client.Endpoint, uri, api.client.options.TokenOptions)
if err != nil {
return
}
result = &TaskList{}
err = json.Unmarshal(res, result)
return
}
func (api *AvailabilityZonesAPI) getEntityUrl(id string) (url string) {
return api.client.Endpoint + availabilityzoneUrl + "/" + id
}

View File

@ -1,193 +0,0 @@
// Copyright (c) 2016 VMware, Inc. All Rights Reserved.
//
// This product is licensed to you under the Apache License, Version 2.0 (the "License").
// You may not use this product except in compliance with the License.
//
// This product may include a number of subcomponents with separate copyright notices and
// license terms. Your use of these subcomponents is subject to the terms and conditions
// of the subcomponent's license, as noted in the LICENSE file.
package photon
import (
"crypto/tls"
"crypto/x509"
"io/ioutil"
"log"
"net/http"
"strings"
"time"
)
// Represents stateless context needed to call photon APIs.
type Client struct {
options ClientOptions
restClient *restClient
logger *log.Logger
Endpoint string
Status *StatusAPI
Tenants *TenantsAPI
Tasks *TasksAPI
Projects *ProjectsAPI
Flavors *FlavorsAPI
Images *ImagesAPI
Disks *DisksAPI
VMs *VmAPI
Hosts *HostsAPI
Deployments *DeploymentsAPI
ResourceTickets *ResourceTicketsAPI
Networks *NetworksAPI
VirtualSubnets *VirtualSubnetsAPI
Services *ServicesAPI
Auth *AuthAPI
AvailabilityZones *AvailabilityZonesAPI
Info *InfoAPI
Routers *RoutersAPI
Subnets *SubnetsAPI
}
// Represents Tokens
type TokenOptions struct {
AccessToken string `json:"access_token"`
ExpiresIn int `json:"expires_in"`
RefreshToken string `json:"refresh_token,omitempty"`
IdToken string `json:"id_token"`
TokenType string `json:"token_type"`
}
type TokenCallback func(string)
// Options for Client
type ClientOptions struct {
// When using the Tasks.Wait APIs, defines the duration of how long
// the SDK should continue to poll the server. Default is 30 minutes.
// TasksAPI.WaitTimeout() can be used to specify timeout on
// individual calls.
TaskPollTimeout time.Duration
// Whether or not to ignore any TLS errors when talking to photon,
// false by default.
IgnoreCertificate bool
// List of root CA's to use for server validation
// nil by default.
RootCAs *x509.CertPool
// For tasks APIs, defines the delay between each polling attempt.
// Default is 100 milliseconds.
TaskPollDelay time.Duration
// For tasks APIs, defines the number of retries to make in the event
// of an error. Default is 3.
TaskRetryCount int
// Tokens for user authentication. Default is empty.
TokenOptions *TokenOptions
// A function to be called if the access token was refreshed
// The client can save the new access token for future API
// calls so that it doesn't need to be refreshed again.
UpdateAccessTokenCallback TokenCallback
}
// Creates a new photon client with specified options. If options
// is nil, default options will be used.
func NewClient(endpoint string, options *ClientOptions, logger *log.Logger) (c *Client) {
defaultOptions := &ClientOptions{
TaskPollTimeout: 30 * time.Minute,
TaskPollDelay: 100 * time.Millisecond,
TaskRetryCount: 3,
TokenOptions: &TokenOptions{},
IgnoreCertificate: false,
RootCAs: nil,
}
if options != nil {
if options.TaskPollTimeout != 0 {
defaultOptions.TaskPollTimeout = options.TaskPollTimeout
}
if options.TaskPollDelay != 0 {
defaultOptions.TaskPollDelay = options.TaskPollDelay
}
if options.TaskRetryCount != 0 {
defaultOptions.TaskRetryCount = options.TaskRetryCount
}
if options.TokenOptions != nil {
defaultOptions.TokenOptions = options.TokenOptions
}
if options.RootCAs != nil {
defaultOptions.RootCAs = options.RootCAs
}
defaultOptions.IgnoreCertificate = options.IgnoreCertificate
defaultOptions.UpdateAccessTokenCallback = options.UpdateAccessTokenCallback
}
if logger == nil {
logger = createPassThroughLogger()
}
tr := &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: defaultOptions.IgnoreCertificate,
RootCAs: defaultOptions.RootCAs},
}
endpoint = strings.TrimRight(endpoint, "/")
tokenCallback := func(newToken string) {
c.options.TokenOptions.AccessToken = newToken
if c.options.UpdateAccessTokenCallback != nil {
c.options.UpdateAccessTokenCallback(newToken)
}
}
restClient := &restClient{
httpClient: &http.Client{Transport: tr},
logger: logger,
UpdateAccessTokenCallback: tokenCallback,
}
c = &Client{Endpoint: endpoint, restClient: restClient, logger: logger}
// Ensure a copy of options is made, rather than using a pointer
// which may change out from underneath if misused by the caller.
c.options = *defaultOptions
c.Status = &StatusAPI{c}
c.Tenants = &TenantsAPI{c}
c.Tasks = &TasksAPI{c}
c.Projects = &ProjectsAPI{c}
c.Flavors = &FlavorsAPI{c}
c.Images = &ImagesAPI{c}
c.Disks = &DisksAPI{c}
c.VMs = &VmAPI{c}
c.Hosts = &HostsAPI{c}
c.Deployments = &DeploymentsAPI{c}
c.ResourceTickets = &ResourceTicketsAPI{c}
c.Networks = &NetworksAPI{c}
c.VirtualSubnets = &VirtualSubnetsAPI{c}
c.Services = &ServicesAPI{c}
c.Auth = &AuthAPI{c}
c.AvailabilityZones = &AvailabilityZonesAPI{c}
c.Info = &InfoAPI{c}
c.Routers = &RoutersAPI{c}
c.Subnets = &SubnetsAPI{c}
// Tell the restClient about the Auth API so it can request new
// acces tokens when they expire
restClient.Auth = c.Auth
return
}
// Creates a new photon client with specified options and http.Client.
// Useful for functional testing where http calls must be mocked out.
// If options is nil, default options will be used.
func NewTestClient(endpoint string, options *ClientOptions, httpClient *http.Client) (c *Client) {
c = NewClient(endpoint, options, nil)
c.restClient.httpClient = httpClient
return
}
func createPassThroughLogger() (l *log.Logger) {
// ioutil.Discard makes all logging operation be a no-op.
return log.New(ioutil.Discard, "", log.LstdFlags)
}

View File

@ -1,337 +0,0 @@
// Copyright (c) 2016 VMware, Inc. All Rights Reserved.
//
// This product is licensed to you under the Apache License, Version 2.0 (the "License").
// You may not use this product except in compliance with the License.
//
// This product may include a number of subcomponents with separate copyright notices and
// license terms. Your use of these subcomponents is subject to the terms and conditions
// of the subcomponent's license, as noted in the LICENSE file.
package photon
import (
"bytes"
"encoding/json"
)
// Contains functionality for deployments API.
type DeploymentsAPI struct {
client *Client
}
var deploymentUrl string = rootUrl + "/deployments"
// Creates a deployment
func (api *DeploymentsAPI) Create(deploymentSpec *DeploymentCreateSpec) (task *Task, err error) {
body, err := json.Marshal(deploymentSpec)
if err != nil {
return
}
res, err := api.client.restClient.Post(
api.client.Endpoint+deploymentUrl,
"application/json",
bytes.NewReader(body),
api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}
// Deletes a deployment with specified ID.
func (api *DeploymentsAPI) Delete(id string) (task *Task, err error) {
res, err := api.client.restClient.Delete(api.getEntityUrl(id), api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}
// Deploys a deployment with specified ID.
func (api *DeploymentsAPI) Deploy(id string, config *DeploymentDeployOperation) (task *Task, err error) {
body, err := json.Marshal(config)
if err != nil {
return
}
res, err := api.client.restClient.Post(
api.getEntityUrl(id)+"/deploy",
"application/json",
bytes.NewReader(body),
api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}
// Destroys a deployment with specified ID.
func (api *DeploymentsAPI) Destroy(id string) (task *Task, err error) {
res, err := api.client.restClient.Post(
api.getEntityUrl(id)+"/destroy",
"application/json",
bytes.NewReader([]byte("")),
api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}
// Returns all deployments.
func (api *DeploymentsAPI) GetAll() (result *Deployments, err error) {
res, err := api.client.restClient.Get(api.client.Endpoint+deploymentUrl, api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
res, err = getError(res)
if err != nil {
return
}
result = &Deployments{}
err = json.NewDecoder(res.Body).Decode(result)
return
}
// Gets a deployment with the specified ID.
func (api *DeploymentsAPI) Get(id string) (deployment *Deployment, err error) {
res, err := api.client.restClient.Get(api.getEntityUrl(id), api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
res, err = getError(res)
if err != nil {
return
}
var result Deployment
err = json.NewDecoder(res.Body).Decode(&result)
return &result, nil
}
// Gets all hosts with the specified deployment ID.
func (api *DeploymentsAPI) GetHosts(id string) (result *Hosts, err error) {
uri := api.getEntityUrl(id) + "/hosts"
res, err := api.client.restClient.GetList(api.client.Endpoint, uri, api.client.options.TokenOptions)
if err != nil {
return
}
result = &Hosts{}
err = json.Unmarshal(res, result)
return
}
// Gets all the vms with the specified deployment ID.
func (api *DeploymentsAPI) GetVms(id string) (result *VMs, err error) {
uri := api.getEntityUrl(id) + "/vms"
res, err := api.client.restClient.GetList(api.client.Endpoint, uri, api.client.options.TokenOptions)
if err != nil {
return
}
result = &VMs{}
err = json.Unmarshal(res, result)
return
}
// Initialize deployment migration from source to destination
func (api *DeploymentsAPI) InitializeDeploymentMigration(sourceAddress *InitializeMigrationOperation, id string) (task *Task, err error) {
body, err := json.Marshal(sourceAddress)
if err != nil {
return
}
res, err := api.client.restClient.Post(
api.getEntityUrl(id)+"/initialize_migration",
"application/json",
bytes.NewReader(body),
api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}
// Finalize deployment migration from source to destination
func (api *DeploymentsAPI) FinalizeDeploymentMigration(sourceAddress *FinalizeMigrationOperation, id string) (task *Task, err error) {
body, err := json.Marshal(sourceAddress)
if err != nil {
return
}
res, err := api.client.restClient.Post(
api.getEntityUrl(id)+"/finalize_migration",
"application/json",
bytes.NewReader(body),
api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}
func (api *DeploymentsAPI) SetSecurityGroups(id string, securityGroups *SecurityGroupsSpec) (*Task, error) {
return setSecurityGroups(api.client, api.getEntityUrl(id), securityGroups)
}
// Update image datastores of a deployment.
func (api *DeploymentsAPI) SetImageDatastores(id string, imageDatastores *ImageDatastores) (task *Task, err error) {
body, err := json.Marshal(imageDatastores)
if err != nil {
return
}
res, err := api.client.restClient.Post(
api.getEntityUrl(id)+"/set_image_datastores",
"application/json",
bytes.NewReader(body),
api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}
// Synchronizes hosts configurations
func (api *DeploymentsAPI) SyncHostsConfig(id string) (task *Task, err error) {
res, err := api.client.restClient.Post(
api.getEntityUrl(id)+"/sync_hosts_config",
"application/json",
bytes.NewReader([]byte("")),
api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}
// Pause system with specified deployment ID.
func (api *DeploymentsAPI) PauseSystem(id string) (task *Task, err error) {
res, err := api.client.restClient.Post(
api.getEntityUrl(id)+"/pause_system",
"application/json",
bytes.NewReader([]byte("")),
api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}
// Pause background tasks of system with specified deployment ID.
func (api *DeploymentsAPI) PauseBackgroundTasks(id string) (task *Task, err error) {
res, err := api.client.restClient.Post(
api.getEntityUrl(id)+"/pause_background_tasks",
"application/json",
bytes.NewReader([]byte("")),
api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}
// Pause background tasks of system with specified deployment ID.
func (api *DeploymentsAPI) ResumeSystem(id string) (task *Task, err error) {
res, err := api.client.restClient.Post(
api.getEntityUrl(id)+"/resume_system",
"application/json",
bytes.NewReader([]byte("")),
api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}
// Enable service type with specified deployment ID.
func (api *DeploymentsAPI) EnableServiceType(id string, serviceConfigSpec *ServiceConfigurationSpec) (task *Task, err error) {
body, err := json.Marshal(serviceConfigSpec)
if err != nil {
return
}
res, err := api.client.restClient.Post(
api.getEntityUrl(id)+"/enable_service_type",
"application/json",
bytes.NewReader(body),
api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}
// Disable service type with specified deployment ID.
func (api *DeploymentsAPI) DisableServiceType(id string, serviceConfigSpec *ServiceConfigurationSpec) (task *Task, err error) {
body, err := json.Marshal(serviceConfigSpec)
if err != nil {
return
}
res, err := api.client.restClient.Post(
api.getEntityUrl(id)+"/disable_service_type",
"application/json",
bytes.NewReader(body),
api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}
// Configure NSX.
func (api *DeploymentsAPI) ConfigureNsx(id string, nsxConfigSpec *NsxConfigurationSpec) (task *Task, err error) {
body, err := json.Marshal(nsxConfigSpec)
if err != nil {
return
}
res, err := api.client.restClient.Post(
api.getEntityUrl(id)+"/configure_nsx",
"application/json",
bytes.NewReader(body),
api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}
func (api *DeploymentsAPI) getEntityUrl(id string) (url string) {
return api.client.Endpoint + deploymentUrl + "/" + id
}

View File

@ -1,65 +0,0 @@
// Copyright (c) 2016 VMware, Inc. All Rights Reserved.
//
// This product is licensed to you under the Apache License, Version 2.0 (the "License").
// You may not use this product except in compliance with the License.
//
// This product may include a number of subcomponents with separate copyright notices and
// license terms. Your use of these subcomponents is subject to the terms and conditions
// of the subcomponent's license, as noted in the LICENSE file.
package photon
import (
"encoding/json"
)
// Contains functionality for disks API.
type DisksAPI struct {
client *Client
}
var diskUrl string = rootUrl + "/disks/"
// Gets a PersistentDisk for the disk with specified ID.
func (api *DisksAPI) Get(diskID string) (disk *PersistentDisk, err error) {
res, err := api.client.restClient.Get(api.client.Endpoint+diskUrl+diskID, api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
res, err = getError(res)
if err != nil {
return
}
disk = &PersistentDisk{}
err = json.NewDecoder(res.Body).Decode(disk)
return
}
// Deletes a disk with the specified ID.
func (api *DisksAPI) Delete(diskID string) (task *Task, err error) {
res, err := api.client.restClient.Delete(api.client.Endpoint+diskUrl+diskID, api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}
// Gets all tasks with the specified disk ID, using options to filter the results.
// If options is nil, no filtering will occur.
func (api *DisksAPI) GetTasks(id string, options *TaskGetOptions) (result *TaskList, err error) {
uri := api.client.Endpoint + diskUrl + id + "/tasks"
if options != nil {
uri += getQueryString(options)
}
res, err := api.client.restClient.GetList(api.client.Endpoint, uri, api.client.options.TokenOptions)
if err != nil {
return
}
result = &TaskList{}
err = json.Unmarshal(res, result)
return
}

View File

@ -1,108 +0,0 @@
// Copyright (c) 2016 VMware, Inc. All Rights Reserved.
//
// This product is licensed to you under the Apache License, Version 2.0 (the "License").
// You may not use this product except in compliance with the License.
//
// This product may include a number of subcomponents with separate copyright notices and
// license terms. Your use of these subcomponents is subject to the terms and conditions
// of the subcomponent's license, as noted in the LICENSE file.
package photon
import (
"bytes"
"encoding/json"
)
// Contains functionality for flavors API.
type FlavorsAPI struct {
client *Client
}
// Options used for find/get APIs
type FlavorGetOptions struct {
Name string `urlParam:"name"`
Kind string `urlParam:"kind"`
}
var flavorUrl string = rootUrl + "/flavors"
// Creates a flavor.
func (api *FlavorsAPI) Create(spec *FlavorCreateSpec) (task *Task, err error) {
body, err := json.Marshal(spec)
if err != nil {
return
}
res, err := api.client.restClient.Post(
api.client.Endpoint+flavorUrl,
"application/json",
bytes.NewReader(body),
api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}
// Gets details of flavor with specified ID.
func (api *FlavorsAPI) Get(flavorID string) (flavor *Flavor, err error) {
res, err := api.client.restClient.Get(api.client.Endpoint+flavorUrl+"/"+flavorID, api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
res, err = getError(res)
if err != nil {
return
}
flavor = &Flavor{}
err = json.NewDecoder(res.Body).Decode(flavor)
return
}
// Gets flavors using options to filter results. Returns all flavors if options is nil.
func (api *FlavorsAPI) GetAll(options *FlavorGetOptions) (flavors *FlavorList, err error) {
uri := api.client.Endpoint + flavorUrl
if options != nil {
uri += getQueryString(options)
}
res, err := api.client.restClient.GetList(api.client.Endpoint, uri, api.client.options.TokenOptions)
if err != nil {
return
}
flavors = &FlavorList{}
err = json.Unmarshal(res, flavors)
return
}
// Deletes flavor with specified ID.
func (api *FlavorsAPI) Delete(flavorID string) (task *Task, err error) {
res, err := api.client.restClient.Delete(api.client.Endpoint+flavorUrl+"/"+flavorID, api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}
// Gets all tasks with the specified flavor ID, using options to filter the results.
// If options is nil, no filtering will occur.
func (api *FlavorsAPI) GetTasks(id string, options *TaskGetOptions) (result *TaskList, err error) {
uri := api.client.Endpoint + flavorUrl + "/" + id + "/tasks"
if options != nil {
uri += getQueryString(options)
}
res, err := api.client.restClient.GetList(api.client.Endpoint, uri, api.client.options.TokenOptions)
if err != nil {
return
}
result = &TaskList{}
err = json.Unmarshal(res, result)
return
}

View File

@ -1,219 +0,0 @@
// Copyright (c) 2016 VMware, Inc. All Rights Reserved.
//
// This product is licensed to you under the Apache License, Version 2.0 (the "License").
// You may not use this product except in compliance with the License.
//
// This product may include a number of subcomponents with separate copyright notices and
// license terms. Your use of these subcomponents is subject to the terms and conditions
// of the subcomponent's license, as noted in the LICENSE file.
package photon
import (
"bytes"
"encoding/json"
)
// Contains functionality for hosts API.
type HostsAPI struct {
client *Client
}
var hostUrl string = rootUrl + "/hosts"
// Creates a host.
func (api *HostsAPI) Create(hostSpec *HostCreateSpec, deploymentId string) (task *Task, err error) {
body, err := json.Marshal(hostSpec)
if err != nil {
return
}
res, err := api.client.restClient.Post(
api.client.Endpoint+deploymentUrl+"/"+deploymentId+"/hosts",
"application/json",
bytes.NewReader(body),
api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}
// Deletes a host with specified ID.
func (api *HostsAPI) Delete(id string) (task *Task, err error) {
res, err := api.client.restClient.Delete(api.client.Endpoint+hostUrl+"/"+id, api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}
// Returns all hosts
func (api *HostsAPI) GetAll() (result *Hosts, err error) {
res, err := api.client.restClient.Get(api.client.Endpoint+hostUrl, api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
res, err = getError(res)
if err != nil {
return
}
result = &Hosts{}
err = json.NewDecoder(res.Body).Decode(result)
return
}
// Gets a host with the specified ID.
func (api *HostsAPI) Get(id string) (host *Host, err error) {
res, err := api.client.restClient.Get(api.client.Endpoint+hostUrl+"/"+id, api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
res, err = getError(res)
if err != nil {
return
}
var result Host
err = json.NewDecoder(res.Body).Decode(&result)
return &result, nil
}
// Sets host's availability zone.
func (api *HostsAPI) SetAvailabilityZone(id string, availabilityZone *HostSetAvailabilityZoneOperation) (task *Task, err error) {
body, err := json.Marshal(availabilityZone)
if err != nil {
return
}
res, err := api.client.restClient.Post(
api.client.Endpoint+hostUrl+"/"+id+"/set_availability_zone",
"application/json",
bytes.NewReader(body),
api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}
// Gets all tasks with the specified host ID, using options to filter the results.
// If options is nil, no filtering will occur.
func (api *HostsAPI) GetTasks(id string, options *TaskGetOptions) (result *TaskList, err error) {
uri := api.client.Endpoint + hostUrl + "/" + id + "/tasks"
if options != nil {
uri += getQueryString(options)
}
res, err := api.client.restClient.GetList(api.client.Endpoint, uri, api.client.options.TokenOptions)
if err != nil {
return
}
result = &TaskList{}
err = json.Unmarshal(res, result)
return
}
// Gets all the vms with the specified host ID.
func (api *HostsAPI) GetVMs(id string) (result *VMs, err error) {
res, err := api.client.restClient.Get(api.client.Endpoint+hostUrl+"/"+id+"/vms", api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
res, err = getError(res)
if err != nil {
return
}
result = &VMs{}
err = json.NewDecoder(res.Body).Decode(result)
return
}
// provision the host with the specified id
func (api *HostsAPI) Provision(id string) (task *Task, err error) {
body := []byte{}
res, err := api.client.restClient.Post(
api.client.Endpoint+hostUrl+"/"+id+"/provision",
"application/json",
bytes.NewReader(body),
api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}
// Suspend the host with the specified id
func (api *HostsAPI) Suspend(id string) (task *Task, err error) {
body := []byte{}
res, err := api.client.restClient.Post(
api.client.Endpoint+hostUrl+"/"+id+"/suspend",
"application/json",
bytes.NewReader(body),
api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}
// Resume the host with the specified id
func (api *HostsAPI) Resume(id string) (task *Task, err error) {
body := []byte{}
res, err := api.client.restClient.Post(
api.client.Endpoint+hostUrl+"/"+id+"/resume",
"application/json",
bytes.NewReader(body),
api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}
// Host with the specified id enter maintenance mode
func (api *HostsAPI) EnterMaintenanceMode(id string) (task *Task, err error) {
body := []byte{}
res, err := api.client.restClient.Post(
api.client.Endpoint+hostUrl+"/"+id+"/enter_maintenance",
"application/json",
bytes.NewReader(body),
api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}
// Host with the specified id exit maintenance mode
func (api *HostsAPI) ExitMaintenanceMode(id string) (task *Task, err error) {
body := []byte{}
res, err := api.client.restClient.Post(
api.client.Endpoint+hostUrl+"/"+id+"/exit_maintenance",
"application/json",
bytes.NewReader(body),
api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}

View File

@ -1,182 +0,0 @@
// Copyright (c) 2016 VMware, Inc. All Rights Reserved.
//
// This product is licensed to you under the Apache License, Version 2.0 (the "License").
// You may not use this product except in compliance with the License.
//
// This product may include a number of subcomponents with separate copyright notices and
// license terms. Your use of these subcomponents is subject to the terms and conditions
// of the subcomponent's license, as noted in the LICENSE file.
package photon
import (
"bytes"
"encoding/json"
"io"
)
// Contains functionality for images API.
type ImagesAPI struct {
client *Client
}
// Options for GetImage API.
type ImageGetOptions struct {
Name string `urlParam:"name"`
}
var imageUrl string = rootUrl + "/images"
// Uploads a new image, reading from the specified image path.
// If options is nil, default options are used.
func (api *ImagesAPI) CreateFromFile(imagePath string, options *ImageCreateOptions) (task *Task, err error) {
params := imageCreateOptionsToMap(options)
res, err := api.client.restClient.MultipartUploadFile(api.client.Endpoint+imageUrl, imagePath, params, api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
result, err := getTask(getError(res))
return result, err
}
// Uploads a new image, reading from the specified io.Reader.
// Name is a descriptive name of the image, it is used in the filename field of the Content-Disposition header,
// and does not need to be unique.
// If options is nil, default options are used.
func (api *ImagesAPI) Create(reader io.ReadSeeker, name string, options *ImageCreateOptions) (task *Task, err error) {
params := imageCreateOptionsToMap(options)
res, err := api.client.restClient.MultipartUpload(api.client.Endpoint+imageUrl, reader, name, params, api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
result, err := getTask(getError(res))
return result, err
}
// Gets all images on this photon instance.
func (api *ImagesAPI) GetAll(options *ImageGetOptions) (images *Images, err error) {
uri := api.client.Endpoint + imageUrl
if options != nil {
uri += getQueryString(options)
}
res, err := api.client.restClient.GetList(api.client.Endpoint, uri, api.client.options.TokenOptions)
if err != nil {
return
}
images = &Images{}
err = json.Unmarshal(res, images)
return
}
// Gets details of image with the specified ID.
func (api *ImagesAPI) Get(imageID string) (image *Image, err error) {
res, err := api.client.restClient.Get(api.client.Endpoint+imageUrl+"/"+imageID, api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
res, err = getError(res)
if err != nil {
return
}
var result Image
err = json.NewDecoder(res.Body).Decode(&result)
return &result, nil
}
// Deletes image with the specified ID.
func (api *ImagesAPI) Delete(imageID string) (task *Task, err error) {
res, err := api.client.restClient.Delete(api.client.Endpoint+imageUrl+"/"+imageID, api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
result, err := getTask(getError(res))
return result, err
}
// Gets all tasks with the specified image ID, using options to filter the results.
// If options is nil, no filtering will occur.
func (api *ImagesAPI) GetTasks(id string, options *TaskGetOptions) (result *TaskList, err error) {
uri := api.client.Endpoint + imageUrl + "/" + id + "/tasks"
if options != nil {
uri += getQueryString(options)
}
res, err := api.client.restClient.GetList(api.client.Endpoint, uri, api.client.options.TokenOptions)
if err != nil {
return
}
result = &TaskList{}
err = json.Unmarshal(res, result)
return
}
// Gets IAM Policy of an image.
func (api *ImagesAPI) GetIam(imageID string) (policy *[]PolicyEntry, err error) {
res, err := api.client.restClient.Get(
api.client.Endpoint+imageUrl+"/"+imageID+"/iam",
api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
res, err = getError(res)
if err != nil {
return
}
var result []PolicyEntry
err = json.NewDecoder(res.Body).Decode(&result)
return &result, nil
}
// Sets IAM Policy on an image.
func (api *ImagesAPI) SetIam(imageID string, policy *[]PolicyEntry) (task *Task, err error) {
body, err := json.Marshal(policy)
if err != nil {
return
}
res, err := api.client.restClient.Post(
api.client.Endpoint+imageUrl+"/"+imageID+"/iam",
"application/json",
bytes.NewReader(body),
api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}
// Modifies IAM Policy on an image.
func (api *ImagesAPI) ModifyIam(imageID string, policyDelta *PolicyDelta) (task *Task, err error) {
body, err := json.Marshal(policyDelta)
if err != nil {
return
}
res, err := api.client.restClient.Put(
api.client.Endpoint+imageUrl+"/"+imageID+"/iam",
"application/json",
bytes.NewReader(body),
api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}
func imageCreateOptionsToMap(opts *ImageCreateOptions) map[string]string {
if opts == nil {
return nil
}
return map[string]string{
"ImageReplication": opts.ReplicationType,
}
}

View File

@ -1,39 +0,0 @@
// Copyright (c) 2016 VMware, Inc. All Rights Reserved.
//
// This product is licensed to you under the Apache License, Version 2.0 (the "License").
// You may not use this product except in compliance with the License.
//
// This product may include a number of subcomponents with separate copyright notices and
// license terms. Your use of these subcomponents is subject to the terms and conditions
// of the subcomponent's license, as noted in the LICENSE file.
package photon
import (
"encoding/json"
)
type InfoAPI struct {
client *Client
}
var infoUrl = rootUrl + "/info"
// Get info
func (api *InfoAPI) Get() (info *Info, err error) {
res, err := api.client.restClient.Get(api.client.Endpoint+infoUrl, api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
res, err = getError(res)
if err != nil {
return
}
info = new(Info)
err = json.NewDecoder(res.Body).Decode(info)
return
}

View File

@ -1,34 +0,0 @@
load("@io_bazel_rules_go//go:def.bzl", "go_library")
go_library(
name = "go_default_library",
srcs = [
"jwttoken.go",
"oidcclient.go",
"oidcclient_sspi.go",
"oidcclient_sspi_unsupported.go",
],
importmap = "k8s.io/kubernetes/vendor/github.com/vmware/photon-controller-go-sdk/photon/lightwave",
importpath = "github.com/vmware/photon-controller-go-sdk/photon/lightwave",
visibility = ["//visibility:public"],
deps = select({
"@io_bazel_rules_go//go/platform:windows": [
"//vendor/github.com/vmware/photon-controller-go-sdk/SSPI:go_default_library",
],
"//conditions:default": [],
}),
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)

View File

@ -1,59 +0,0 @@
package lightwave
import (
"encoding/base64"
"encoding/json"
"strings"
)
type JWTToken struct {
TokenId string `json:"jti"`
Algorithm string `json:"alg"`
Subject string `json:"sub"`
Audience []string `json:"aud"`
Groups []string `json:"groups"`
Issuer string `json:"iss"`
IssuedAt int64 `json:"iat"`
Expires int64 `json:"exp"`
Scope string `json:"scope"`
TokenType string `json:"token_type"`
TokenClass string `json:"token_class"`
Tenant string `json:"tenant"`
// It's possible to have more fields depending on how Lightwave defines the token.
// This covers all the fields we currently have.
}
// A JSON web token is a set of Base64 encoded strings separated by a period (.)
// When decoded, it will either be JSON text or a signature
// Here we decode the strings into a single token structure. We do not parse the signature.
func ParseTokenDetails(token string) (jwtToken *JWTToken) {
jwtToken = &JWTToken{}
chunks := strings.Split(token, ".")
for _, chunk := range chunks {
json_string, err := base64.RawURLEncoding.DecodeString(chunk)
if err == nil {
// Ignore errors. We expect that the signature is not JSON,
// so unmarshalling it will fail. That's fine. We'll extract
// all the data we can.
_ = json.Unmarshal(json_string, &jwtToken)
}
}
return jwtToken
}
// A JSON web token is a set of Base64 encoded strings separated by a period (.)
// When decoded, it will either be JSON text or a signature
// Here we parse the full JSON text. We do not parse the signature.
func ParseRawTokenDetails(token string) (jwtToken []string, err error) {
chunks := strings.Split(token, ".")
for _, chunk := range chunks {
jsonString, err := base64.RawURLEncoding.DecodeString(chunk)
if err == nil {
jwtToken = append(jwtToken, string(jsonString))
}
}
return jwtToken, err
}

View File

@ -1,238 +0,0 @@
// Copyright (c) 2016 VMware, Inc. All Rights Reserved.
//
// This product is licensed to you under the Apache License, Version 2.0 (the "License").
// You may not use this product except in compliance with the License.
//
// This product may include a number of subcomponents with separate copyright notices and
// license terms. Your use of these subcomponents is subject to the terms and conditions
// of the subcomponent's license, as noted in the LICENSE file.
package lightwave
import (
"crypto/tls"
"crypto/x509"
"encoding/json"
"encoding/pem"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"strings"
)
const tokenScope string = "openid offline_access"
type OIDCClient struct {
httpClient *http.Client
logger *log.Logger
Endpoint string
Options *OIDCClientOptions
}
type OIDCClientOptions struct {
// Whether or not to ignore any TLS errors when talking to photon,
// false by default.
IgnoreCertificate bool
// List of root CA's to use for server validation
// nil by default.
RootCAs *x509.CertPool
// The scope values to use when requesting tokens
TokenScope string
}
func NewOIDCClient(endpoint string, options *OIDCClientOptions, logger *log.Logger) (c *OIDCClient) {
if logger == nil {
logger = log.New(ioutil.Discard, "", log.LstdFlags)
}
options = buildOptions(options)
tr := &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: options.IgnoreCertificate,
RootCAs: options.RootCAs},
}
c = &OIDCClient{
httpClient: &http.Client{Transport: tr},
logger: logger,
Endpoint: strings.TrimRight(endpoint, "/"),
Options: options,
}
return
}
func buildOptions(options *OIDCClientOptions) (result *OIDCClientOptions) {
result = &OIDCClientOptions{
TokenScope: tokenScope,
}
if options == nil {
return
}
result.IgnoreCertificate = options.IgnoreCertificate
if options.RootCAs != nil {
result.RootCAs = options.RootCAs
}
if options.TokenScope != "" {
result.TokenScope = options.TokenScope
}
return
}
func (client *OIDCClient) buildUrl(path string) (url string) {
return fmt.Sprintf("%s%s", client.Endpoint, path)
}
// Cert download helper
const certDownloadPath string = "/afd/vecs/ssl"
type lightWaveCert struct {
Value string `json:"encoded"`
}
func (client *OIDCClient) GetRootCerts() (certList []*x509.Certificate, err error) {
// turn TLS verification off for
originalTr := client.httpClient.Transport
defer client.setTransport(originalTr)
tr := &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
}
client.setTransport(tr)
// get the certs
resp, err := client.httpClient.Get(client.buildUrl(certDownloadPath))
if err != nil {
return
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
err = fmt.Errorf("Unexpected error retrieving auth server certs: %v %s", resp.StatusCode, resp.Status)
return
}
// parse the certs
certsData := &[]lightWaveCert{}
err = json.NewDecoder(resp.Body).Decode(certsData)
if err != nil {
return
}
certList = make([]*x509.Certificate, len(*certsData))
for idx, cert := range *certsData {
block, _ := pem.Decode([]byte(cert.Value))
if block == nil {
err = fmt.Errorf("Unexpected response format: %v", certsData)
return nil, err
}
decodedCert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, err
}
certList[idx] = decodedCert
}
return
}
func (client *OIDCClient) setTransport(tr http.RoundTripper) {
client.httpClient.Transport = tr
}
// Toke request helpers
const tokenPath string = "/openidconnect/token"
const passwordGrantFormatString = "grant_type=password&username=%s&password=%s&scope=%s"
const refreshTokenGrantFormatString = "grant_type=refresh_token&refresh_token=%s"
type OIDCTokenResponse struct {
AccessToken string `json:"access_token"`
ExpiresIn int `json:"expires_in"`
RefreshToken string `json:"refresh_token,omitempty"`
IdToken string `json:"id_token"`
TokenType string `json:"token_type"`
}
func (client *OIDCClient) GetTokenByPasswordGrant(username string, password string) (tokens *OIDCTokenResponse, err error) {
username = url.QueryEscape(username)
password = url.QueryEscape(password)
body := fmt.Sprintf(passwordGrantFormatString, username, password, client.Options.TokenScope)
return client.getToken(body)
}
func (client *OIDCClient) GetTokenByRefreshTokenGrant(refreshToken string) (tokens *OIDCTokenResponse, err error) {
body := fmt.Sprintf(refreshTokenGrantFormatString, refreshToken)
return client.getToken(body)
}
func (client *OIDCClient) getToken(body string) (tokens *OIDCTokenResponse, err error) {
request, err := http.NewRequest("POST", client.buildUrl(tokenPath), strings.NewReader(body))
if err != nil {
return nil, err
}
request.Header.Add("Content-Type", "application/x-www-form-urlencoded")
resp, err := client.httpClient.Do(request)
if err != nil {
return nil, err
}
defer resp.Body.Close()
err = client.checkResponse(resp)
if err != nil {
return nil, err
}
tokens = &OIDCTokenResponse{}
err = json.NewDecoder(resp.Body).Decode(tokens)
if err != nil {
return nil, err
}
return
}
type OIDCError struct {
Code string `json:"error"`
Message string `json:"error_description"`
}
func (e OIDCError) Error() string {
return fmt.Sprintf("%v: %v", e.Code, e.Message)
}
func (client *OIDCClient) checkResponse(response *http.Response) (err error) {
if response.StatusCode/100 == 2 {
return
}
respBody, readErr := ioutil.ReadAll(response.Body)
if err != nil {
return fmt.Errorf(
"Status: %v, Body: %v [%v]", response.Status, string(respBody[:]), readErr)
}
var oidcErr OIDCError
err = json.Unmarshal(respBody, &oidcErr)
if err != nil {
return fmt.Errorf(
"Status: %v, Body: %v [%v]", response.Status, string(respBody[:]), readErr)
}
return oidcErr
}

View File

@ -1,131 +0,0 @@
// Copyright (c) 2017 VMware, Inc. All Rights Reserved.
//
// This product is licensed to you under the Apache License, Version 2.0 (the "License").
// You may not use this product except in compliance with the License.
//
// This product may include a number of subcomponents with separate copyright notices and
// license terms. Your use of these subcomponents is subject to the terms and conditions
// of the subcomponent's license, as noted in the LICENSE file.
// +build windows
package lightwave
import (
"encoding/base64"
"fmt"
"github.com/vmware/photon-controller-go-sdk/SSPI"
"math/rand"
"net"
"net/url"
"strings"
"time"
)
const gssTicketGrantFormatString = "grant_type=urn:vmware:grant_type:gss_ticket&gss_ticket=%s&context_id=%s&scope=%s"
// GetTokensFromWindowsLogInContext gets tokens based on Windows logged in context
// Here is how it works:
// 1. Get the SPN (Service Principal Name) in the format host/FQDN of lightwave. This is needed for SSPI/Kerberos protocol
// 2. Call Windows API AcquireCredentialsHandle() using SSPI library. This will give the current users credential handle
// 3. Using this handle call Windows API AcquireCredentialsHandle(). This will give you byte[]
// 4. Encode this byte[] and send it to OIDC server over HTTP (using POST)
// 5. OIDC server can send either of the following
// - Access tokens. In this case return access tokens to client
// - Error in the format: invalid_grant: gss_continue_needed:'context id':'token from server'
// 6. In case you get error, parse it and get the token from server
// 7. Feed this token to step 3 and repeat steps till you get the access tokens from server
func (client *OIDCClient) GetTokensFromWindowsLogInContext() (tokens *OIDCTokenResponse, err error) {
spn, err := client.buildSPN()
if err != nil {
return nil, err
}
auth, _ := SSPI.GetAuth("", "", spn, "")
userContext, err := auth.InitialBytes()
if err != nil {
return nil, err
}
// In case of multiple req/res between client and server (as explained in above comment),
// server needs to maintain the mapping of context id -> token
// So we need to generate random string as a context id
// If we use same context id for all the requests, results can be erroneous
contextId := client.generateRandomString()
body := fmt.Sprintf(gssTicketGrantFormatString, url.QueryEscape(base64.StdEncoding.EncodeToString(userContext)), contextId, client.Options.TokenScope)
tokens, err = client.getToken(body)
for {
if err == nil {
break
}
// In case of error the response will be in format: invalid_grant: gss_continue_needed:'context id':'token from server'
gssToken := client.validateAndExtractGSSResponse(err, contextId)
if gssToken == "" {
return nil, err
}
data, err := base64.StdEncoding.DecodeString(gssToken)
if err != nil {
return nil, err
}
userContext, err := auth.NextBytes(data)
body := fmt.Sprintf(gssTicketGrantFormatString, url.QueryEscape(base64.StdEncoding.EncodeToString(userContext)), contextId, client.Options.TokenScope)
tokens, err = client.getToken(body)
}
return tokens, err
}
// Gets the SPN (Service Principal Name) in the format host/FQDN of lightwave
func (client *OIDCClient) buildSPN() (spn string, err error) {
u, err := url.Parse(client.Endpoint)
if err != nil {
return "", err
}
host, _, err := net.SplitHostPort(u.Host)
if err != nil {
return "", err
}
addr, err := net.LookupAddr(host)
if err != nil {
return "", err
}
var s = strings.TrimSuffix(addr[0], ".")
return "host/" + s, nil
}
// validateAndExtractGSSResponse parse the error from server and returns token from server
// In case of error from the server, response will be in format: invalid_grant: gss_continue_needed:'context id':'token from server'
// So, we check for the above format in error and then return the token from server
// If error is not in above format, we return empty string
func (client *OIDCClient) validateAndExtractGSSResponse(err error, contextId string) string {
parts := strings.Split(err.Error(), ":")
if !(len(parts) == 4 && strings.TrimSpace(parts[1]) == "gss_continue_needed" && parts[2] == contextId) {
return ""
} else {
return parts[3]
}
}
func (client *OIDCClient) generateRandomString() string {
const length = 10
const asciiA = 65
const asciiZ = 90
rand.Seed(time.Now().UTC().UnixNano())
bytes := make([]byte, length)
for i := 0; i < length; i++ {
bytes[i] = byte(randInt(asciiA, asciiZ))
}
return string(bytes)
}
func randInt(min int, max int) int {
return min + rand.Intn(max-min)
}

View File

@ -1,18 +0,0 @@
// Copyright (c) 2017 VMware, Inc. All Rights Reserved.
//
// This product is licensed to you under the Apache License, Version 2.0 (the "License").
// You may not use this product except in compliance with the License.
//
// This product may include a number of subcomponents with separate copyright notices and
// license terms. Your use of these subcomponents is subject to the terms and conditions
// of the subcomponent's license, as noted in the LICENSE file.
// +build !windows
package lightwave
import "errors"
func (client *OIDCClient) GetTokensFromWindowsLogInContext() (tokens *OIDCTokenResponse, err error) {
return nil, errors.New("Not supported on this OS")
}

View File

@ -1,101 +0,0 @@
// Copyright (c) 2016 VMware, Inc. All Rights Reserved.
//
// This product is licensed to you under the Apache License, Version 2.0 (the "License").
// You may not use this product except in compliance with the License.
//
// This product may include a number of subcomponents with separate copyright notices and
// license terms. Your use of these subcomponents is subject to the terms and conditions
// of the subcomponent's license, as noted in the LICENSE file.
package photon
import (
"bytes"
"encoding/json"
)
// Contains functionality for networks API.
type NetworksAPI struct {
client *Client
}
// Options used for GetAll API
type NetworkGetOptions struct {
Name string `urlParam:"name"`
}
var networkUrl string = rootUrl + "/subnets"
// Creates a network.
func (api *NetworksAPI) Create(networkSpec *NetworkCreateSpec) (task *Task, err error) {
body, err := json.Marshal(networkSpec)
if err != nil {
return
}
res, err := api.client.restClient.Post(
api.client.Endpoint+networkUrl,
"application/json",
bytes.NewReader(body),
api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}
// Deletes a network with specified ID.
func (api *NetworksAPI) Delete(id string) (task *Task, err error) {
res, err := api.client.restClient.Delete(api.client.Endpoint+networkUrl+"/"+id, api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}
// Gets a network with the specified ID.
func (api *NetworksAPI) Get(id string) (network *Network, err error) {
res, err := api.client.restClient.Get(api.client.Endpoint+networkUrl+"/"+id, api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
res, err = getError(res)
if err != nil {
return
}
var result Network
err = json.NewDecoder(res.Body).Decode(&result)
return &result, nil
}
// Returns all networks
func (api *NetworksAPI) GetAll(options *NetworkGetOptions) (result *Networks, err error) {
uri := api.client.Endpoint + networkUrl
if options != nil {
uri += getQueryString(options)
}
res, err := api.client.restClient.GetList(api.client.Endpoint, uri, api.client.options.TokenOptions)
result = &Networks{}
err = json.Unmarshal(res, result)
return
}
// Sets default network.
func (api *NetworksAPI) SetDefault(id string) (task *Task, err error) {
res, err := api.client.restClient.Post(
api.client.Endpoint+networkUrl+"/"+id+"/set_default",
"application/json",
bytes.NewReader([]byte("")),
api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}

View File

@ -1,208 +0,0 @@
// Copyright (c) 2016 VMware, Inc. All Rights Reserved.
//
// This product is licensed to you under the Apache License, Version 2.0 (the "License").
// You may not use this product except in compliance with the License.
//
// This product may include a number of subcomponents with separate copyright notices and
// license terms. Your use of these subcomponents is subject to the terms and conditions
// of the subcomponent's license, as noted in the LICENSE file.
package photon
import (
"bytes"
"encoding/json"
)
// Contains functionality for projects API.
type ProjectsAPI struct {
client *Client
}
// Options for GetDisks API.
type DiskGetOptions struct {
Name string `urlParam:"name"`
}
// Options for GetDisks API.
type VmGetOptions struct {
Name string `urlParam:"name"`
}
var projectUrl string = rootUrl + "/projects/"
// Deletes the project with specified ID. Any VMs, disks, etc., owned by the project must be deleted first.
func (api *ProjectsAPI) Delete(projectID string) (task *Task, err error) {
res, err := api.client.restClient.Delete(api.client.Endpoint+projectUrl+projectID, api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}
// Creates a disk on the specified project.
func (api *ProjectsAPI) CreateDisk(projectID string, spec *DiskCreateSpec) (task *Task, err error) {
body, err := json.Marshal(spec)
if err != nil {
return
}
res, err := api.client.restClient.Post(
api.client.Endpoint+projectUrl+projectID+"/disks",
"application/json",
bytes.NewReader(body),
api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}
// Gets disks for project with the specified ID, using options to filter the results.
// If options is nil, no filtering will occur.
func (api *ProjectsAPI) GetDisks(projectID string, options *DiskGetOptions) (result *DiskList, err error) {
uri := api.client.Endpoint + projectUrl + projectID + "/disks"
if options != nil {
uri += getQueryString(options)
}
res, err := api.client.restClient.GetList(api.client.Endpoint, uri, api.client.options.TokenOptions)
if err != nil {
return
}
result = &DiskList{}
err = json.Unmarshal(res, result)
return
}
// Creates a VM on the specified project.
func (api *ProjectsAPI) CreateVM(projectID string, spec *VmCreateSpec) (task *Task, err error) {
body, err := json.Marshal(spec)
if err != nil {
return
}
res, err := api.client.restClient.Post(
api.client.Endpoint+projectUrl+projectID+"/vms",
"application/json",
bytes.NewReader(body),
api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}
// Gets all tasks with the specified project ID, using options to filter the results.
// If options is nil, no filtering will occur.
func (api *ProjectsAPI) GetTasks(id string, options *TaskGetOptions) (result *TaskList, err error) {
uri := api.client.Endpoint + projectUrl + id + "/tasks"
if options != nil {
uri += getQueryString(options)
}
res, err := api.client.restClient.GetList(api.client.Endpoint, uri, api.client.options.TokenOptions)
if err != nil {
return
}
result = &TaskList{}
err = json.Unmarshal(res, result)
return
}
// Gets vms for project with the specified ID, using options to filter the results.
// If options is nil, no filtering will occur.
func (api *ProjectsAPI) GetVMs(projectID string, options *VmGetOptions) (result *VMs, err error) {
uri := api.client.Endpoint + projectUrl + projectID + "/vms"
if options != nil {
uri += getQueryString(options)
}
res, err := api.client.restClient.GetList(api.client.Endpoint, uri, api.client.options.TokenOptions)
if err != nil {
return
}
result = &VMs{}
err = json.Unmarshal(res, result)
return
}
// Creates a service on the specified project.
func (api *ProjectsAPI) CreateService(projectID string, spec *ServiceCreateSpec) (task *Task, err error) {
body, err := json.Marshal(spec)
if err != nil {
return
}
res, err := api.client.restClient.Post(
api.client.Endpoint+projectUrl+projectID+"/services",
"application/json",
bytes.NewReader(body),
api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}
// Gets services for project with the specified ID
func (api *ProjectsAPI) GetServices(projectID string) (result *Services, err error) {
uri := api.client.Endpoint + projectUrl + projectID + "/services"
res, err := api.client.restClient.GetList(api.client.Endpoint, uri, api.client.options.TokenOptions)
if err != nil {
return
}
result = &Services{}
err = json.Unmarshal(res, result)
return
}
// Gets the project with a specified ID.
func (api *ProjectsAPI) Get(id string) (project *ProjectCompact, err error) {
res, err := api.client.restClient.Get(api.getEntityUrl(id), api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
res, err = getError(res)
if err != nil {
return
}
project = &ProjectCompact{}
err = json.NewDecoder(res.Body).Decode(project)
return
}
// Set security groups for this project, overwriting any existing ones.
func (api *ProjectsAPI) SetSecurityGroups(projectID string, securityGroups *SecurityGroupsSpec) (*Task, error) {
return setSecurityGroups(api.client, api.getEntityUrl(projectID), securityGroups)
}
func (api *ProjectsAPI) getEntityUrl(id string) string {
return api.client.Endpoint + projectUrl + id
}
// Creates a router on the specified project.
func (api *ProjectsAPI) CreateRouter(projectID string, spec *RouterCreateSpec) (task *Task, err error) {
body, err := json.Marshal(spec)
if err != nil {
return
}
res, err := api.client.restClient.Post(
api.client.Endpoint+projectUrl+projectID+"/routers",
"application/json",
bytes.NewReader(body),
api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}

View File

@ -1,55 +0,0 @@
// Copyright (c) 2016 VMware, Inc. All Rights Reserved.
//
// This product is licensed to you under the Apache License, Version 2.0 (the "License").
// You may not use this product except in compliance with the License.
//
// This product may include a number of subcomponents with separate copyright notices and
// license terms. Your use of these subcomponents is subject to the terms and conditions
// of the subcomponent's license, as noted in the LICENSE file.
package photon
import (
"encoding/json"
)
// Contains functionality for hosts API.
type ResourceTicketsAPI struct {
client *Client
}
var resourceTicketUrl string = rootUrl + "/resource-tickets/"
// Gets all tasks with the specified resource ticket ID, using options to filter the results.
// If options is nil, no filtering will occur.
func (api *ResourceTicketsAPI) GetTasks(id string, options *TaskGetOptions) (result *TaskList, err error) {
uri := api.client.Endpoint + resourceTicketUrl + id + "/tasks"
if options != nil {
uri += getQueryString(options)
}
res, err := api.client.restClient.GetList(api.client.Endpoint, uri, api.client.options.TokenOptions)
if err != nil {
return
}
result = &TaskList{}
err = json.Unmarshal(res, result)
return
}
// Gets the resource ticket with a specified ID.
func (api *ResourceTicketsAPI) Get(id string) (resourceTicket *ResourceTicket, err error) {
res, err := api.client.restClient.Get(api.client.Endpoint+resourceTicketUrl+"/"+id,
api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
res, err = getError(res)
if err != nil {
return
}
resourceTicket = &ResourceTicket{}
err = json.NewDecoder(res.Body).Decode(resourceTicket)
return
}

View File

@ -1,326 +0,0 @@
// Copyright (c) 2016 VMware, Inc. All Rights Reserved.
//
// This product is licensed to you under the Apache License, Version 2.0 (the "License").
// You may not use this product except in compliance with the License.
//
// This product may include a number of subcomponents with separate copyright notices and
// license terms. Your use of these subcomponents is subject to the terms and conditions
// of the subcomponent's license, as noted in the LICENSE file.
package photon
import (
"bytes"
"crypto/rand"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"path/filepath"
"strings"
)
type restClient struct {
httpClient *http.Client
logger *log.Logger
Auth *AuthAPI
UpdateAccessTokenCallback TokenCallback
}
type request struct {
Method string
URL string
ContentType string
Body io.Reader
Tokens *TokenOptions
}
type page struct {
Items []interface{} `json:"items"`
NextPageLink string `json:"nextPageLink"`
PreviousPageLink string `json:"previousPageLink"`
}
type documentList struct {
Items []interface{}
}
type bodyRewinder func() io.Reader
const appJson string = "application/json"
// Root URL specifies the API version.
const rootUrl string = "/v1"
// From https://golang.org/src/mime/multipart/writer.go
var quoteEscaper = strings.NewReplacer("\\", "\\\\", `"`, "\\\"")
func (client *restClient) AppendSlice(origSlice []interface{}, dataToAppend []interface{}) []interface{} {
origLen := len(origSlice)
newLen := origLen + len(dataToAppend)
if newLen > cap(origSlice) {
newSlice := make([]interface{}, (newLen+1)*2)
copy(newSlice, origSlice)
origSlice = newSlice
}
origSlice = origSlice[0:newLen]
copy(origSlice[origLen:newLen], dataToAppend)
return origSlice
}
func (client *restClient) Get(url string, tokens *TokenOptions) (res *http.Response, err error) {
req := request{"GET", url, "", nil, tokens}
res, err = client.SendRequest(&req, nil)
return
}
func (client *restClient) GetList(endpoint string, url string, tokens *TokenOptions) (result []byte, err error) {
req := request{"GET", url, "", nil, tokens}
res, err := client.SendRequest(&req, nil)
if err != nil {
return
}
res, err = getError(res)
if err != nil {
return
}
decoder := json.NewDecoder(res.Body)
decoder.UseNumber()
page := &page{}
err = decoder.Decode(page)
if err != nil {
return
}
documentList := &documentList{}
documentList.Items = client.AppendSlice(documentList.Items, page.Items)
for page.NextPageLink != "" {
req = request{"GET", endpoint + page.NextPageLink, "", nil, tokens}
res, err = client.SendRequest(&req, nil)
if err != nil {
return
}
res, err = getError(res)
if err != nil {
return
}
decoder = json.NewDecoder(res.Body)
decoder.UseNumber()
page.NextPageLink = ""
page.PreviousPageLink = ""
err = decoder.Decode(page)
if err != nil {
return
}
documentList.Items = client.AppendSlice(documentList.Items, page.Items)
}
result, err = json.Marshal(documentList)
return
}
func (client *restClient) Post(url string, contentType string, body io.ReadSeeker, tokens *TokenOptions) (res *http.Response, err error) {
if contentType == "" {
contentType = appJson
}
req := request{"POST", url, contentType, body, tokens}
rewinder := func() io.Reader {
body.Seek(0, 0)
return body
}
res, err = client.SendRequest(&req, rewinder)
return
}
func (client *restClient) Patch(url string, contentType string, body io.ReadSeeker, tokens *TokenOptions) (res *http.Response, err error) {
if contentType == "" {
contentType = appJson
}
req := request{"PATCH", url, contentType, body, tokens}
rewinder := func() io.Reader {
body.Seek(0, 0)
return body
}
res, err = client.SendRequest(&req, rewinder)
return
}
func (client *restClient) Put(url string, contentType string, body io.ReadSeeker, tokens *TokenOptions) (res *http.Response, err error) {
if contentType == "" {
contentType = appJson
}
req := request{"PUT", url, contentType, body, tokens}
rewinder := func() io.Reader {
body.Seek(0, 0)
return body
}
res, err = client.SendRequest(&req, rewinder)
return
}
func (client *restClient) Delete(url string, tokens *TokenOptions) (res *http.Response, err error) {
req := request{"DELETE", url, "", nil, tokens}
res, err = client.SendRequest(&req, nil)
return
}
func (client *restClient) SendRequest(req *request, bodyRewinder bodyRewinder) (res *http.Response, err error) {
res, err = client.sendRequestHelper(req)
// In most cases, we'll return immediately
// If the operation succeeded, but we got a 401 response and if we're using
// authentication, then we'll look into the body to see if the token expired
if err != nil {
return res, err
}
if res.StatusCode != 401 {
// It's not a 401, so the token didn't expire
return res, err
}
if req.Tokens == nil || req.Tokens.AccessToken == "" {
// We don't have a token, so we can't renew the token, no need to proceed
return res, err
}
// We're going to look in the body to see if it failed because the token expired
// This means we need to read the body, but the functions that call us also
// expect to read the body. So we read the body, then create a new reader
// so they can read the body as normal.
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return res, err
}
res.Body = ioutil.NopCloser(bytes.NewReader(body))
// Now see if we had an expired token or not
var apiError ApiError
err = json.Unmarshal(body, &apiError)
if err != nil {
return res, err
}
if apiError.Code != "ExpiredAuthToken" {
return res, nil
}
// We were told that the access token expired, so try to renew it.
// Note that this looks recursive because GetTokensByRefreshToken() will
// call the /auth API, and therefore SendRequest(). However, it calls
// without a token, so we avoid having a loop
newTokens, err := client.Auth.GetTokensByRefreshToken(req.Tokens.RefreshToken)
if err != nil {
return res, err
}
req.Tokens.AccessToken = newTokens.AccessToken
if client.UpdateAccessTokenCallback != nil {
client.UpdateAccessTokenCallback(newTokens.AccessToken)
}
if req.Body != nil && bodyRewinder != nil {
req.Body = bodyRewinder()
}
res, err = client.sendRequestHelper(req)
return res, nil
}
func (client *restClient) sendRequestHelper(req *request) (res *http.Response, err error) {
r, err := http.NewRequest(req.Method, req.URL, req.Body)
if err != nil {
client.logger.Printf("An error occured creating request %s on %s. Error: %s", req.Method, req.URL, err)
return
}
if req.ContentType != "" {
r.Header.Add("Content-Type", req.ContentType)
}
if req.Tokens != nil && req.Tokens.AccessToken != "" {
r.Header.Add("Authorization", "Bearer "+req.Tokens.AccessToken)
}
res, err = client.httpClient.Do(r)
if err != nil {
client.logger.Printf("An error occured when calling %s on %s. Error: %s", req.Method, req.URL, err)
return
}
client.logger.Printf("[%s] %s - %s %s", res.Header.Get("request-id"), res.Status, req.Method, req.URL)
return
}
func (client *restClient) MultipartUploadFile(url, filePath string, params map[string]string, tokens *TokenOptions) (res *http.Response, err error) {
file, err := os.Open(filePath)
if err != nil {
return
}
defer file.Close()
return client.MultipartUpload(url, file, filepath.Base(filePath), params, tokens)
}
func (client *restClient) MultipartUpload(url string, reader io.ReadSeeker, filename string, params map[string]string, tokens *TokenOptions) (res *http.Response, err error) {
boundary := client.randomBoundary()
multiReader, contentType := client.createMultiReader(reader, filename, params, boundary)
rewinder := func() io.Reader {
reader.Seek(0, 0)
multiReader, _ := client.createMultiReader(reader, filename, params, boundary)
return multiReader
}
res, err = client.SendRequest(&request{"POST", url, contentType, multiReader, tokens}, rewinder)
return
}
func (client *restClient) createMultiReader(reader io.ReadSeeker, filename string, params map[string]string, boundary string) (io.Reader, string) {
// The mime/multipart package does not support streaming multipart data from disk,
// at least not without complicated, problematic goroutines that simultaneously read/write into a buffer.
// A much easier approach is to just construct the multipart request by hand, using io.MultiPart to
// concatenate the parts of the request together into a single io.Reader.
parts := []io.Reader{}
// Create a part for each key, val pair in params
for k, v := range params {
parts = append(parts, client.createFieldPart(k, v, boundary))
}
start := fmt.Sprintf("\r\n--%s\r\n", boundary)
start += fmt.Sprintf("Content-Disposition: form-data; name=\"file\"; filename=\"%s\"\r\n", quoteEscaper.Replace(filename))
start += fmt.Sprintf("Content-Type: application/octet-stream\r\n\r\n")
end := fmt.Sprintf("\r\n--%s--", boundary)
// The request will consist of a reader to begin the request, a reader which points
// to the file data on disk, and a reader containing the closing boundary of the request.
parts = append(parts, strings.NewReader(start), reader, strings.NewReader(end))
contentType := fmt.Sprintf("multipart/form-data; boundary=%s", boundary)
return io.MultiReader(parts...), contentType
}
// From https://golang.org/src/mime/multipart/writer.go
func (client *restClient) randomBoundary() string {
var buf [30]byte
_, err := io.ReadFull(rand.Reader, buf[:])
if err != nil {
panic(err)
}
return fmt.Sprintf("%x", buf[:])
}
// Creates a reader that encapsulates a single multipart form part
func (client *restClient) createFieldPart(fieldname, value, boundary string) io.Reader {
str := fmt.Sprintf("\r\n--%s\r\n", boundary)
str += fmt.Sprintf("Content-Disposition: form-data; name=\"%s\"\r\n\r\n", quoteEscaper.Replace(fieldname))
str += value
return strings.NewReader(str)
}

View File

@ -1,90 +0,0 @@
// Copyright (c) 2017 VMware, Inc. All Rights Reserved.
//
// This product is licensed to you under the Apache License, Version 2.0 (the "License").
// You may not use this product except in compliance with the License.
//
// This product may include a number of subcomponents with separate copyright notices and
// license terms. Your use of these subcomponents is subject to the terms and conditions
// of the subcomponent's license, as noted in the LICENSE file.
package photon
import (
"bytes"
"encoding/json"
)
// Contains functionality for routers API.
type RoutersAPI struct {
client *Client
}
var routerUrl string = rootUrl + "/routers/"
// Gets a router with the specified ID.
func (api *RoutersAPI) Get(id string) (router *Router, err error) {
res, err := api.client.restClient.Get(api.client.Endpoint+routerUrl+id, api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
res, err = getError(res)
if err != nil {
return
}
var result Router
err = json.NewDecoder(res.Body).Decode(&result)
return &result, nil
}
// Updates router's attributes.
func (api *RoutersAPI) UpdateRouter(id string, routerSpec *RouterUpdateSpec) (task *Task, err error) {
body, err := json.Marshal(routerSpec)
if err != nil {
return
}
res, err := api.client.restClient.Put(
api.client.Endpoint+routerUrl+id,
"application/json",
bytes.NewReader(body),
api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}
// Deletes a router with specified ID.
func (api *RoutersAPI) Delete(routerID string) (task *Task, err error) {
res, err := api.client.restClient.Delete(api.client.Endpoint+routerUrl+routerID, api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}
// Creates a subnet on the specified router.
func (api *RoutersAPI) CreateSubnet(routerID string, spec *SubnetCreateSpec) (task *Task, err error) {
body, err := json.Marshal(spec)
if err != nil {
return
}
res, err := api.client.restClient.Post(
api.client.Endpoint+routerUrl+routerID+"/subnets",
"application/json",
bytes.NewReader(body),
api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}

View File

@ -1,139 +0,0 @@
// Copyright (c) 2016 VMware, Inc. All Rights Reserved.
//
// This product is licensed to you under the Apache License, Version 2.0 (the "License").
// You may not use this product except in compliance with the License.
//
// This product may include a number of subcomponents with separate copyright notices and
// license terms. Your use of these subcomponents is subject to the terms and conditions
// of the subcomponent's license, as noted in the LICENSE file.
package photon
import (
"bytes"
"encoding/json"
)
// Contains functionality for services API.
type ServicesAPI struct {
client *Client
}
var serviceUrl = rootUrl + "/services/"
// Extended Properties
const (
ExtendedPropertyDNS = "dns"
ExtendedPropertyGateway = "gateway"
ExtendedPropertyNetMask = "netmask"
ExtendedPropertyLoadBalancerIP = "load_balancer_ip"
ExtendedPropertyNumberOfMasters = "number_of_masters"
ExtendedPropertyMasterIPs = "master_ips"
ExtendedPropertyMasterIP = "master_ip"
ExtendedPropertyMasterIP2 = "master_ip2"
ExtendedPropertyContainerNetwork = "container_network"
ExtendedPropertyZookeeperIP1 = "zookeeper_ip1"
ExtendedPropertyZookeeperIP2 = "zookeeper_ip2"
ExtendedPropertyZookeeperIP3 = "zookeeper_ip3"
ExtendedPropertyNumberOfETCDs = "number_of_etcds"
ExtendedPropertyETCDIP1 = "etcd_ip1"
ExtendedPropertyETCDIP2 = "etcd_ip2"
ExtendedPropertyETCDIP3 = "etcd_ip3"
ExtendedPropertySSHKey = "ssh_key"
ExtendedPropertyRegistryCACert = "registry_ca_cert"
ExtendedPropertyAdminPassword = "admin_password"
)
// Deletes a service with specified ID.
func (api *ServicesAPI) Delete(id string) (task *Task, err error) {
res, err := api.client.restClient.Delete(api.client.Endpoint+serviceUrl+id, api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}
// Gets a service with the specified ID.
func (api *ServicesAPI) Get(id string) (service *Service, err error) {
res, err := api.client.restClient.Get(api.client.Endpoint+serviceUrl+id, api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
res, err = getError(res)
if err != nil {
return
}
var result Service
err = json.NewDecoder(res.Body).Decode(&result)
return &result, nil
}
// Gets vms for service with the specified ID.
func (api *ServicesAPI) GetVMs(id string) (result *VMs, err error) {
uri := api.client.Endpoint + serviceUrl + id + "/vms"
res, err := api.client.restClient.GetList(api.client.Endpoint, uri, api.client.options.TokenOptions)
if err != nil {
return
}
result = &VMs{}
err = json.Unmarshal(res, result)
return
}
// Resize a service to specified count.
func (api *ServicesAPI) Resize(id string, resize *ServiceResizeOperation) (task *Task, err error) {
body, err := json.Marshal(resize)
if err != nil {
return
}
res, err := api.client.restClient.Post(
api.client.Endpoint+serviceUrl+id+"/resize",
"application/json",
bytes.NewReader(body),
api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}
// Start a background process to recreate failed VMs in a service with the specified ID.
func (api *ServicesAPI) TriggerMaintenance(id string) (task *Task, err error) {
body := []byte{}
res, err := api.client.restClient.Post(
api.client.Endpoint+serviceUrl+id+"/trigger_maintenance",
"application/json",
bytes.NewReader(body),
api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}
// Change a service version to the specified image by destroying and recreating the VMs.
func (api *ServicesAPI) ChangeVersion(id string, changeVersion *ServiceChangeVersionOperation) (task *Task, err error) {
body, err := json.Marshal(changeVersion)
if err != nil {
return
}
res, err := api.client.restClient.Post(
api.client.Endpoint+serviceUrl+id+"/change_version",
"application/json",
bytes.NewReader(body),
api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}

View File

@ -1,37 +0,0 @@
// Copyright (c) 2016 VMware, Inc. All Rights Reserved.
//
// This product is licensed to you under the Apache License, Version 2.0 (the "License").
// You may not use this product except in compliance with the License.
//
// This product may include a number of subcomponents with separate copyright notices and
// license terms. Your use of these subcomponents is subject to the terms and conditions
// of the subcomponent's license, as noted in the LICENSE file.
package photon
import (
"encoding/json"
)
// Contains functionality for status API.
type StatusAPI struct {
client *Client
}
var statusUrl string = rootUrl + "/status"
// Returns the status of an photon endpoint.
func (api *StatusAPI) Get() (status *Status, err error) {
res, err := api.client.restClient.Get(api.client.Endpoint+statusUrl, api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
res, err = getError(res)
if err != nil {
return
}
status = &Status{}
err = json.NewDecoder(res.Body).Decode(status)
return
}

View File

@ -1,72 +0,0 @@
// Copyright (c) 2017 VMware, Inc. All Rights Reserved.
//
// This product is licensed to you under the Apache License, Version 2.0 (the "License").
// You may not use this product except in compliance with the License.
//
// This product may include a number of subcomponents with separate copyright notices and
// license terms. Your use of these subcomponents is subject to the terms and conditions
// of the subcomponent's license, as noted in the LICENSE file.
package photon
import (
"bytes"
"encoding/json"
)
// Contains functionality for subnets API.
type SubnetsAPI struct {
client *Client
}
var subnetUrl string = "/temp-subnets/"
// Deletes a subnet with the specified ID.
func (api *SubnetsAPI) Delete(id string) (task *Task, err error) {
res, err := api.client.restClient.Delete(api.client.Endpoint+subnetUrl+id, api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}
// Gets a subnet with the specified ID.
func (api *SubnetsAPI) Get(id string) (subnet *Subnet, err error) {
res, err := api.client.restClient.Get(api.client.Endpoint+subnetUrl+id, api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
res, err = getError(res)
if err != nil {
return
}
var result Subnet
err = json.NewDecoder(res.Body).Decode(&result)
return &result, nil
}
// Updates subnet's attributes.
func (api *SubnetsAPI) Update(id string, subnetSpec *SubnetUpdateSpec) (task *Task, err error) {
body, err := json.Marshal(subnetSpec)
if err != nil {
return
}
res, err := api.client.restClient.Put(
api.client.Endpoint+subnetUrl+id,
"application/json",
bytes.NewReader(body),
api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}

View File

@ -1,108 +0,0 @@
// Copyright (c) 2016 VMware, Inc. All Rights Reserved.
//
// This product is licensed to you under the Apache License, Version 2.0 (the "License").
// You may not use this product except in compliance with the License.
//
// This product may include a number of subcomponents with separate copyright notices and
// license terms. Your use of these subcomponents is subject to the terms and conditions
// of the subcomponent's license, as noted in the LICENSE file.
package photon
import (
"encoding/json"
"time"
)
// Contains functionality for tasks API.
type TasksAPI struct {
client *Client
}
var taskUrl string = rootUrl + "/tasks"
// Gets a task by ID.
func (api *TasksAPI) Get(id string) (task *Task, err error) {
res, err := api.client.restClient.Get(api.client.Endpoint+taskUrl+"/"+id, api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
result, err := getTask(getError(res))
return result, err
}
// Gets all tasks, using options to filter the results.
// If options is nil, no filtering will occur.
func (api *TasksAPI) GetAll(options *TaskGetOptions) (result *TaskList, err error) {
uri := api.client.Endpoint + taskUrl
if options != nil {
uri += getQueryString(options)
}
res, err := api.client.restClient.GetList(api.client.Endpoint, uri, api.client.options.TokenOptions)
if err != nil {
return
}
result = &TaskList{}
err = json.Unmarshal(res, result)
return
}
// Waits for a task to complete by polling the tasks API until a task returns with
// the state COMPLETED or ERROR. Will wait no longer than the duration specified by timeout.
func (api *TasksAPI) WaitTimeout(id string, timeout time.Duration) (task *Task, err error) {
start := time.Now()
numErrors := 0
maxErrors := api.client.options.TaskRetryCount
for time.Since(start) < timeout {
task, err = api.Get(id)
if err != nil {
switch err.(type) {
// If an ApiError comes back, something is wrong, return the error to the caller
case ApiError:
return
// For other errors, retry before giving up
default:
numErrors++
if numErrors > maxErrors {
return
}
}
} else {
// Reset the error count any time a successful call is made
numErrors = 0
if task.State == "COMPLETED" {
return
}
if task.State == "ERROR" {
err = TaskError{task.ID, getFailedStep(task)}
return
}
}
time.Sleep(api.client.options.TaskPollDelay)
}
err = TaskTimeoutError{id}
return
}
// Waits for a task to complete by polling the tasks API until a task returns with
// the state COMPLETED or ERROR.
func (api *TasksAPI) Wait(id string) (task *Task, err error) {
return api.WaitTimeout(id, api.client.options.TaskPollTimeout)
}
// Gets the failed step in the task to get error details for failed task.
func getFailedStep(task *Task) (step Step) {
var errorStep Step
for _, s := range task.Steps {
if s.State == "ERROR" {
errorStep = s
break
}
}
return errorStep
}

View File

@ -1,213 +0,0 @@
// Copyright (c) 2016 VMware, Inc. All Rights Reserved.
//
// This product is licensed to you under the Apache License, Version 2.0 (the "License").
// You may not use this product except in compliance with the License.
//
// This product may include a number of subcomponents with separate copyright notices and
// license terms. Your use of these subcomponents is subject to the terms and conditions
// of the subcomponent's license, as noted in the LICENSE file.
package photon
import (
"bytes"
"encoding/json"
"fmt"
)
// Contains functionality for tenants API.
type TenantsAPI struct {
client *Client
}
// Options for GetResourceTickets API.
type ResourceTicketGetOptions struct {
Name string `urlParam:"name"`
}
// Options for GetProjects API.
type ProjectGetOptions struct {
Name string `urlParam:"name"`
}
var tenantUrl string = rootUrl + "/tenants"
// Returns all tenants on an photon instance.
func (api *TenantsAPI) GetAll() (result *Tenants, err error) {
uri := api.client.Endpoint + tenantUrl
res, err := api.client.restClient.GetList(api.client.Endpoint, uri, api.client.options.TokenOptions)
if err != nil {
return
}
result = &Tenants{}
err = json.Unmarshal(res, result)
return
}
// Creates a tenant.
func (api *TenantsAPI) Create(tenantSpec *TenantCreateSpec) (task *Task, err error) {
body, err := json.Marshal(tenantSpec)
if err != nil {
return
}
res, err := api.client.restClient.Post(
api.client.Endpoint+tenantUrl,
"application/json",
bytes.NewReader(body),
api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}
// Deletes the tenant with specified ID. Any projects, VMs, disks, etc., owned by the tenant must be deleted first.
func (api *TenantsAPI) Delete(id string) (task *Task, err error) {
res, err := api.client.restClient.Delete(api.client.Endpoint+tenantUrl+"/"+id, api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}
// Creates a resource ticket on the specified tenant.
func (api *TenantsAPI) CreateResourceTicket(tenantId string, spec *ResourceTicketCreateSpec) (task *Task, err error) {
body, err := json.Marshal(spec)
if err != nil {
return
}
res, err := api.client.restClient.Post(
api.client.Endpoint+tenantUrl+"/"+tenantId+"/resource-tickets",
"application/json",
bytes.NewReader(body),
api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}
// Gets resource tickets for tenant with the specified ID, using options to filter the results.
// If options is nil, no filtering will occur.
func (api *TenantsAPI) GetResourceTickets(tenantId string, options *ResourceTicketGetOptions) (tickets *ResourceList, err error) {
uri := api.client.Endpoint + tenantUrl + "/" + tenantId + "/resource-tickets"
if options != nil {
uri += getQueryString(options)
}
res, err := api.client.restClient.GetList(api.client.Endpoint, uri, api.client.options.TokenOptions)
if err != nil {
return
}
tickets = &ResourceList{}
err = json.Unmarshal(res, tickets)
return
}
// Creates a project on the specified tenant.
func (api *TenantsAPI) CreateProject(tenantId string, spec *ProjectCreateSpec) (task *Task, err error) {
body, err := json.Marshal(spec)
if err != nil {
return
}
res, err := api.client.restClient.Post(
api.client.Endpoint+tenantUrl+"/"+tenantId+"/projects",
"application/json",
bytes.NewReader(body),
api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}
// Gets the projects for tenant with the specified ID, using options to filter the results.
// If options is nil, no filtering will occur.
func (api *TenantsAPI) GetProjects(tenantId string, options *ProjectGetOptions) (result *ProjectList, err error) {
uri := api.client.Endpoint + tenantUrl + "/" + tenantId + "/projects"
if options != nil {
uri += getQueryString(options)
}
res, err := api.client.restClient.GetList(api.client.Endpoint, uri, api.client.options.TokenOptions)
if err != nil {
return
}
result = &(ProjectList{})
err = json.Unmarshal(res, result)
return
}
// Gets all tasks with the specified tenant ID, using options to filter the results.
// If options is nil, no filtering will occur.
func (api *TenantsAPI) GetTasks(id string, options *TaskGetOptions) (result *TaskList, err error) {
uri := api.client.Endpoint + tenantUrl + "/" + id + "/tasks"
if options != nil {
uri += getQueryString(options)
}
res, err := api.client.restClient.GetList(api.client.Endpoint, uri, api.client.options.TokenOptions)
if err != nil {
return
}
result = &TaskList{}
err = json.Unmarshal(res, result)
return
}
// Gets a tenant with the specified ID or name
func (api *TenantsAPI) Get(identity string) (tenant *Tenant, err error) {
res, err := api.client.restClient.Get(api.getEntityUrl(identity), api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
res, err = getError(res)
tenant = &Tenant{}
if res != nil {
err = json.NewDecoder(res.Body).Decode(tenant)
// ID corresponds to the tenant ID found, return tenant
if err == nil {
return
}
}
// Find by Name
uri := api.client.Endpoint + tenantUrl + "?name=" + identity
res2, err := api.client.restClient.GetList(api.client.Endpoint, uri, api.client.options.TokenOptions)
if err != nil {
return
}
tenants := &Tenants{}
err = json.Unmarshal(res2, tenants)
if err != nil {
return
}
if len(tenants.Items) < 1 {
err = fmt.Errorf("Cannot find a tenant with id or name match %s", identity)
return
}
tenant = &(tenants.Items[0])
return
}
// Set security groups for this tenant, overwriting any existing ones.
func (api *TenantsAPI) SetSecurityGroups(id string, securityGroups *SecurityGroupsSpec) (*Task, error) {
return setSecurityGroups(api.client, api.getEntityUrl(id), securityGroups)
}
func (api *TenantsAPI) getEntityUrl(id string) (url string) {
return api.client.Endpoint + tenantUrl + "/" + id
}

View File

@ -1,110 +0,0 @@
// Copyright (c) 2016 VMware, Inc. All Rights Reserved.
//
// This product is licensed to you under the Apache License, Version 2.0 (the "License").
// You may not use this product except in compliance with the License.
//
// This product may include a number of subcomponents with separate copyright notices and
// license terms. Your use of these subcomponents is subject to the terms and conditions
// of the subcomponent's license, as noted in the LICENSE file.
package photon
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"reflect"
)
// Reads an error out of the HTTP response, or does nothing if
// no error occured.
func getError(res *http.Response) (*http.Response, error) {
// Do nothing if the response is a successful 2xx
if res.StatusCode/100 == 2 {
return res, nil
}
var apiError ApiError
// ReadAll is usually a bad practice, but here we need to read the response all
// at once because we may attempt to use the data twice. It's preferable to use
// methods that take io.Reader, e.g. json.NewDecoder
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
err = json.Unmarshal(body, &apiError)
if err != nil {
// If deserializing into ApiError fails, return a generic HttpError instead
return nil, HttpError{res.StatusCode, string(body[:])}
}
apiError.HttpStatusCode = res.StatusCode
return nil, apiError
}
// Reads a task object out of the HTTP response. Takes an error argument
// so that GetTask can easily wrap GetError. This function will do nothing
// if e is not nil.
// e.g. res, err := getTask(getError(someApi.Get()))
func getTask(res *http.Response, e error) (*Task, error) {
if e != nil {
return nil, e
}
var task Task
err := json.NewDecoder(res.Body).Decode(&task)
if err != nil {
return nil, err
}
if task.State == "ERROR" {
// Critical: return task as well, so that it can be examined
// for error details.
return &task, TaskError{task.ID, getFailedStep(&task)}
}
return &task, nil
}
// Converts an options struct into a query string.
// E.g. type Foo struct {A int; B int} might return "?a=5&b=10".
// Will return an empty string if no options are set.
func getQueryString(options interface{}) string {
buffer := bytes.Buffer{}
buffer.WriteString("?")
strct := reflect.ValueOf(options).Elem()
typ := strct.Type()
for i := 0; i < strct.NumField(); i++ {
field := strct.Field(i)
value := fmt.Sprint(field.Interface())
if value != "" {
buffer.WriteString(typ.Field(i).Tag.Get("urlParam") + "=" + url.QueryEscape(value))
if i < strct.NumField()-1 {
buffer.WriteString("&")
}
}
}
uri := buffer.String()
if uri == "?" {
return ""
}
return uri
}
// Sets security groups for a given entity (deployment/tenant/project)
func setSecurityGroups(client *Client, entityUrl string, securityGroups *SecurityGroupsSpec) (task *Task, err error) {
body, err := json.Marshal(securityGroups)
if err != nil {
return
}
url := entityUrl + "/set_security_groups"
res, err := client.restClient.Post(
url,
"application/json",
bytes.NewReader(body),
client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}

View File

@ -1,122 +0,0 @@
// Copyright (c) 2016 VMware, Inc. All Rights Reserved.
//
// This product is licensed to you under the Apache License, Version 2.0 (the "License").
// You may not use this product except in compliance with the License.
//
// This product may include a number of subcomponents with separate copyright notices and
// license terms. Your use of these subcomponents is subject to the terms and conditions
// of the subcomponent's license, as noted in the LICENSE file.
package photon
import (
"bytes"
"encoding/json"
)
// Contains pointer to api client.
type VirtualSubnetsAPI struct {
client *Client
}
// Options used for GetAll API
type VirtualSubnetGetOptions struct {
Name string `urlParam:"name"`
}
var subnetsUrl = rootUrl + "/subnets"
var projectsUrl = rootUrl + "/projects"
// Create a virtual network
func (api *VirtualSubnetsAPI) Create(projectId string,
virtualNetworkSpec *VirtualSubnetCreateSpec) (task *Task, err error) {
body, err := json.Marshal(virtualNetworkSpec)
if err != nil {
return
}
res, err := api.client.restClient.Post(
api.client.Endpoint+projectsUrl+"/"+projectId+"/subnets",
"application/json",
bytes.NewReader(body),
api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}
// Delete a virtual network with the specified ID.
func (api *VirtualSubnetsAPI) Delete(id string) (task *Task, err error) {
res, err := api.client.restClient.Delete(api.client.Endpoint+subnetsUrl+"/"+id,
api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}
// Get the virtual subnet with the specified id
func (api *VirtualSubnetsAPI) Get(id string) (subnet *VirtualSubnet, err error) {
res, err := api.client.restClient.Get(api.client.Endpoint+subnetsUrl+"/"+id,
api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
res, err = getError(res)
if err != nil {
return
}
subnet = new(VirtualSubnet)
err = json.NewDecoder(res.Body).Decode(subnet)
return
}
// Return all virtual networks
func (api *VirtualSubnetsAPI) GetAll(projectId string,
options *VirtualSubnetGetOptions) (subnets *VirtualSubnets, err error) {
uri := api.client.Endpoint + projectsUrl + "/" + projectId + "/subnets"
if options != nil {
uri += getQueryString(options)
}
res, err := api.client.restClient.GetList(api.client.Endpoint, uri, api.client.options.TokenOptions)
if err != nil {
return
}
subnets = &VirtualSubnets{}
err = json.Unmarshal(res, subnets)
return
}
func (api *VirtualSubnetsAPI) SetDefault(id string) (task *Task, err error) {
res, err := api.client.restClient.Post(
api.client.Endpoint+subnetsUrl+"/"+id+"/set_default",
"application/json",
bytes.NewReader([]byte("")),
api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}

View File

@ -1,327 +0,0 @@
// Copyright (c) 2016 VMware, Inc. All Rights Reserved.
//
// This product is licensed to you under the Apache License, Version 2.0 (the "License").
// You may not use this product except in compliance with the License.
//
// This product may include a number of subcomponents with separate copyright notices and
// license terms. Your use of these subcomponents is subject to the terms and conditions
// of the subcomponent's license, as noted in the LICENSE file.
package photon
import (
"bytes"
"encoding/json"
"io"
)
// Contains functionality for VMs API.
type VmAPI struct {
client *Client
}
var vmUrl string = rootUrl + "/vms/"
func (api *VmAPI) Get(id string) (vm *VM, err error) {
res, err := api.client.restClient.Get(api.client.Endpoint+vmUrl+id, api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
res, err = getError(res)
if err != nil {
return
}
vm = &VM{}
err = json.NewDecoder(res.Body).Decode(vm)
return
}
func (api *VmAPI) Delete(id string) (task *Task, err error) {
res, err := api.client.restClient.Delete(api.client.Endpoint+vmUrl+id, api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}
func (api *VmAPI) AttachDisk(id string, op *VmDiskOperation) (task *Task, err error) {
body, err := json.Marshal(op)
if err != nil {
return
}
res, err := api.client.restClient.Post(
api.client.Endpoint+vmUrl+id+"/attach_disk",
"application/json",
bytes.NewReader(body),
api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}
func (api *VmAPI) DetachDisk(id string, op *VmDiskOperation) (task *Task, err error) {
body, err := json.Marshal(op)
if err != nil {
return
}
res, err := api.client.restClient.Post(
api.client.Endpoint+vmUrl+id+"/detach_disk",
"application/json",
bytes.NewReader(body),
api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}
func (api *VmAPI) AttachISO(id string, reader io.ReadSeeker, name string) (task *Task, err error) {
res, err := api.client.restClient.MultipartUpload(
api.client.Endpoint+vmUrl+id+"/attach_iso", reader, name, nil, api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
result, err := getTask(getError(res))
return result, err
}
func (api *VmAPI) DetachISO(id string) (task *Task, err error) {
body := []byte{}
if err != nil {
return
}
res, err := api.client.restClient.Post(
api.client.Endpoint+vmUrl+id+"/detach_iso",
"application/json",
bytes.NewReader(body),
api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}
func (api *VmAPI) Start(id string) (task *Task, err error) {
body := []byte{}
if err != nil {
return
}
res, err := api.client.restClient.Post(
api.client.Endpoint+vmUrl+id+"/start",
"application/json",
bytes.NewReader(body),
api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}
func (api *VmAPI) Stop(id string) (task *Task, err error) {
body := []byte{}
if err != nil {
return
}
res, err := api.client.restClient.Post(
api.client.Endpoint+vmUrl+id+"/stop",
"application/json",
bytes.NewReader(body),
api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}
func (api *VmAPI) Restart(id string) (task *Task, err error) {
body := []byte{}
if err != nil {
return
}
res, err := api.client.restClient.Post(
api.client.Endpoint+vmUrl+id+"/restart",
"application/json",
bytes.NewReader(body),
api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}
func (api *VmAPI) Resume(id string) (task *Task, err error) {
body := []byte{}
if err != nil {
return
}
res, err := api.client.restClient.Post(
api.client.Endpoint+vmUrl+id+"/resume",
"application/json",
bytes.NewReader(body),
api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}
func (api *VmAPI) Suspend(id string) (task *Task, err error) {
body := []byte{}
if err != nil {
return
}
res, err := api.client.restClient.Post(
api.client.Endpoint+vmUrl+id+"/suspend",
"application/json",
bytes.NewReader(body),
api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}
func (api *VmAPI) SetMetadata(id string, metadata *VmMetadata) (task *Task, err error) {
body, err := json.Marshal(metadata)
if err != nil {
return
}
res, err := api.client.restClient.Post(
api.client.Endpoint+vmUrl+id+"/set_metadata",
"application/json",
bytes.NewReader(body),
api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}
// Gets all tasks with the specified vm ID, using options to filter the results.
// If options is nil, no filtering will occur.
func (api *VmAPI) GetTasks(id string, options *TaskGetOptions) (result *TaskList, err error) {
uri := api.client.Endpoint + vmUrl + id + "/tasks"
if options != nil {
uri += getQueryString(options)
}
res, err := api.client.restClient.GetList(api.client.Endpoint, uri, api.client.options.TokenOptions)
if err != nil {
return
}
result = &TaskList{}
err = json.Unmarshal(res, result)
return
}
func (api *VmAPI) GetNetworks(id string) (task *Task, err error) {
res, err := api.client.restClient.Get(api.client.Endpoint+vmUrl+id+"/subnets", api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}
func (api *VmAPI) AcquireFloatingIp(id string, spec *VmFloatingIpSpec) (task *Task, err error) {
body, err := json.Marshal(spec)
if err != nil {
return
}
res, err := api.client.restClient.Post(
api.client.Endpoint+vmUrl+id+"/acquire_floating_ip",
"application/json",
bytes.NewReader(body),
api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}
func (api *VmAPI) ReleaseFloatingIp(id string) (task *Task, err error) {
res, err := api.client.restClient.Delete(
api.client.Endpoint+vmUrl+id+"/release_floating_ip",
api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}
func (api *VmAPI) GetMKSTicket(id string) (task *Task, err error) {
res, err := api.client.restClient.Get(api.client.Endpoint+vmUrl+id+"/mks_ticket", api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}
func (api *VmAPI) SetTag(id string, tag *VmTag) (task *Task, err error) {
body, err := json.Marshal(tag)
if err != nil {
return
}
res, err := api.client.restClient.Post(
api.client.Endpoint+vmUrl+id+"/tags",
"application/json",
bytes.NewReader(body),
api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}
func (api *VmAPI) CreateImage(id string, options *ImageCreateSpec) (task *Task, err error) {
body, err := json.Marshal(options)
if err != nil {
return
}
res, err := api.client.restClient.Post(
api.client.Endpoint+vmUrl+id+"/create_image",
"application/json",
bytes.NewReader(body),
api.client.options.TokenOptions)
if err != nil {
return
}
defer res.Body.Close()
task, err = getTask(getError(res))
return
}

View File

@ -1,201 +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,96 +0,0 @@
//
// Copyright 2016, Sander van Harmelen
//
// 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 cloudstack
import (
"encoding/json"
"net/url"
)
type ListApisParams struct {
p map[string]interface{}
}
func (p *ListApisParams) toURLValues() url.Values {
u := url.Values{}
if p.p == nil {
return u
}
if v, found := p.p["name"]; found {
u.Set("name", v.(string))
}
return u
}
func (p *ListApisParams) SetName(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["name"] = v
return
}
// You should always use this function to get a new ListApisParams instance,
// as then you are sure you have configured all required params
func (s *APIDiscoveryService) NewListApisParams() *ListApisParams {
p := &ListApisParams{}
p.p = make(map[string]interface{})
return p
}
// lists all available apis on the server, provided by the Api Discovery plugin
func (s *APIDiscoveryService) ListApis(p *ListApisParams) (*ListApisResponse, error) {
resp, err := s.cs.newRequest("listApis", p.toURLValues())
if err != nil {
return nil, err
}
var r ListApisResponse
if err := json.Unmarshal(resp, &r); err != nil {
return nil, err
}
return &r, nil
}
type ListApisResponse struct {
Count int `json:"count"`
Apis []*Api `json:"api"`
}
type Api struct {
Description string `json:"description,omitempty"`
Isasync bool `json:"isasync,omitempty"`
Name string `json:"name,omitempty"`
Params []struct {
Description string `json:"description,omitempty"`
Length int `json:"length,omitempty"`
Name string `json:"name,omitempty"`
Related string `json:"related,omitempty"`
Required bool `json:"required,omitempty"`
Since string `json:"since,omitempty"`
Type string `json:"type,omitempty"`
} `json:"params,omitempty"`
Related string `json:"related,omitempty"`
Response []struct {
Description string `json:"description,omitempty"`
Name string `json:"name,omitempty"`
Response []string `json:"response,omitempty"`
Type string `json:"type,omitempty"`
} `json:"response,omitempty"`
Since string `json:"since,omitempty"`
Type string `json:"type,omitempty"`
}

File diff suppressed because it is too large Load Diff

View File

@ -1,811 +0,0 @@
//
// Copyright 2016, Sander van Harmelen
//
// 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 cloudstack
import (
"encoding/json"
"fmt"
"net/url"
"strconv"
"strings"
)
type AssociateIpAddressParams struct {
p map[string]interface{}
}
func (p *AssociateIpAddressParams) toURLValues() url.Values {
u := url.Values{}
if p.p == nil {
return u
}
if v, found := p.p["account"]; found {
u.Set("account", v.(string))
}
if v, found := p.p["domainid"]; found {
u.Set("domainid", v.(string))
}
if v, found := p.p["fordisplay"]; found {
vv := strconv.FormatBool(v.(bool))
u.Set("fordisplay", vv)
}
if v, found := p.p["isportable"]; found {
vv := strconv.FormatBool(v.(bool))
u.Set("isportable", vv)
}
if v, found := p.p["networkid"]; found {
u.Set("networkid", v.(string))
}
if v, found := p.p["projectid"]; found {
u.Set("projectid", v.(string))
}
if v, found := p.p["regionid"]; found {
vv := strconv.Itoa(v.(int))
u.Set("regionid", vv)
}
if v, found := p.p["vpcid"]; found {
u.Set("vpcid", v.(string))
}
if v, found := p.p["zoneid"]; found {
u.Set("zoneid", v.(string))
}
return u
}
func (p *AssociateIpAddressParams) SetAccount(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["account"] = v
return
}
func (p *AssociateIpAddressParams) SetDomainid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["domainid"] = v
return
}
func (p *AssociateIpAddressParams) SetFordisplay(v bool) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["fordisplay"] = v
return
}
func (p *AssociateIpAddressParams) SetIsportable(v bool) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["isportable"] = v
return
}
func (p *AssociateIpAddressParams) SetNetworkid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["networkid"] = v
return
}
func (p *AssociateIpAddressParams) SetProjectid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["projectid"] = v
return
}
func (p *AssociateIpAddressParams) SetRegionid(v int) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["regionid"] = v
return
}
func (p *AssociateIpAddressParams) SetVpcid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["vpcid"] = v
return
}
func (p *AssociateIpAddressParams) SetZoneid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["zoneid"] = v
return
}
// You should always use this function to get a new AssociateIpAddressParams instance,
// as then you are sure you have configured all required params
func (s *AddressService) NewAssociateIpAddressParams() *AssociateIpAddressParams {
p := &AssociateIpAddressParams{}
p.p = make(map[string]interface{})
return p
}
// Acquires and associates a public IP to an account.
func (s *AddressService) AssociateIpAddress(p *AssociateIpAddressParams) (*AssociateIpAddressResponse, error) {
resp, err := s.cs.newRequest("associateIpAddress", p.toURLValues())
if err != nil {
return nil, err
}
var r AssociateIpAddressResponse
if err := json.Unmarshal(resp, &r); err != nil {
return nil, err
}
// If we have a async client, we need to wait for the async result
if s.cs.async {
b, err := s.cs.GetAsyncJobResult(r.JobID, s.cs.timeout)
if err != nil {
if err == AsyncTimeoutErr {
return &r, err
}
return nil, err
}
b, err = getRawValue(b)
if err != nil {
return nil, err
}
if err := json.Unmarshal(b, &r); err != nil {
return nil, err
}
}
return &r, nil
}
type AssociateIpAddressResponse struct {
JobID string `json:"jobid,omitempty"`
Account string `json:"account,omitempty"`
Allocated string `json:"allocated,omitempty"`
Associatednetworkid string `json:"associatednetworkid,omitempty"`
Associatednetworkname string `json:"associatednetworkname,omitempty"`
Domain string `json:"domain,omitempty"`
Domainid string `json:"domainid,omitempty"`
Fordisplay bool `json:"fordisplay,omitempty"`
Forvirtualnetwork bool `json:"forvirtualnetwork,omitempty"`
Id string `json:"id,omitempty"`
Ipaddress string `json:"ipaddress,omitempty"`
Isportable bool `json:"isportable,omitempty"`
Issourcenat bool `json:"issourcenat,omitempty"`
Isstaticnat bool `json:"isstaticnat,omitempty"`
Issystem bool `json:"issystem,omitempty"`
Networkid string `json:"networkid,omitempty"`
Physicalnetworkid string `json:"physicalnetworkid,omitempty"`
Project string `json:"project,omitempty"`
Projectid string `json:"projectid,omitempty"`
Purpose string `json:"purpose,omitempty"`
State string `json:"state,omitempty"`
Tags []struct {
Account string `json:"account,omitempty"`
Customer string `json:"customer,omitempty"`
Domain string `json:"domain,omitempty"`
Domainid string `json:"domainid,omitempty"`
Key string `json:"key,omitempty"`
Project string `json:"project,omitempty"`
Projectid string `json:"projectid,omitempty"`
Resourceid string `json:"resourceid,omitempty"`
Resourcetype string `json:"resourcetype,omitempty"`
Value string `json:"value,omitempty"`
} `json:"tags,omitempty"`
Virtualmachinedisplayname string `json:"virtualmachinedisplayname,omitempty"`
Virtualmachineid string `json:"virtualmachineid,omitempty"`
Virtualmachinename string `json:"virtualmachinename,omitempty"`
Vlanid string `json:"vlanid,omitempty"`
Vlanname string `json:"vlanname,omitempty"`
Vmipaddress string `json:"vmipaddress,omitempty"`
Vpcid string `json:"vpcid,omitempty"`
Zoneid string `json:"zoneid,omitempty"`
Zonename string `json:"zonename,omitempty"`
}
type DisassociateIpAddressParams struct {
p map[string]interface{}
}
func (p *DisassociateIpAddressParams) toURLValues() url.Values {
u := url.Values{}
if p.p == nil {
return u
}
if v, found := p.p["id"]; found {
u.Set("id", v.(string))
}
return u
}
func (p *DisassociateIpAddressParams) SetId(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["id"] = v
return
}
// You should always use this function to get a new DisassociateIpAddressParams instance,
// as then you are sure you have configured all required params
func (s *AddressService) NewDisassociateIpAddressParams(id string) *DisassociateIpAddressParams {
p := &DisassociateIpAddressParams{}
p.p = make(map[string]interface{})
p.p["id"] = id
return p
}
// Disassociates an IP address from the account.
func (s *AddressService) DisassociateIpAddress(p *DisassociateIpAddressParams) (*DisassociateIpAddressResponse, error) {
resp, err := s.cs.newRequest("disassociateIpAddress", p.toURLValues())
if err != nil {
return nil, err
}
var r DisassociateIpAddressResponse
if err := json.Unmarshal(resp, &r); err != nil {
return nil, err
}
// If we have a async client, we need to wait for the async result
if s.cs.async {
b, err := s.cs.GetAsyncJobResult(r.JobID, s.cs.timeout)
if err != nil {
if err == AsyncTimeoutErr {
return &r, err
}
return nil, err
}
if err := json.Unmarshal(b, &r); err != nil {
return nil, err
}
}
return &r, nil
}
type DisassociateIpAddressResponse struct {
JobID string `json:"jobid,omitempty"`
Displaytext string `json:"displaytext,omitempty"`
Success bool `json:"success,omitempty"`
}
type ListPublicIpAddressesParams struct {
p map[string]interface{}
}
func (p *ListPublicIpAddressesParams) toURLValues() url.Values {
u := url.Values{}
if p.p == nil {
return u
}
if v, found := p.p["account"]; found {
u.Set("account", v.(string))
}
if v, found := p.p["allocatedonly"]; found {
vv := strconv.FormatBool(v.(bool))
u.Set("allocatedonly", vv)
}
if v, found := p.p["associatednetworkid"]; found {
u.Set("associatednetworkid", v.(string))
}
if v, found := p.p["domainid"]; found {
u.Set("domainid", v.(string))
}
if v, found := p.p["fordisplay"]; found {
vv := strconv.FormatBool(v.(bool))
u.Set("fordisplay", vv)
}
if v, found := p.p["forloadbalancing"]; found {
vv := strconv.FormatBool(v.(bool))
u.Set("forloadbalancing", vv)
}
if v, found := p.p["forvirtualnetwork"]; found {
vv := strconv.FormatBool(v.(bool))
u.Set("forvirtualnetwork", vv)
}
if v, found := p.p["id"]; found {
u.Set("id", v.(string))
}
if v, found := p.p["ipaddress"]; found {
u.Set("ipaddress", v.(string))
}
if v, found := p.p["isrecursive"]; found {
vv := strconv.FormatBool(v.(bool))
u.Set("isrecursive", vv)
}
if v, found := p.p["issourcenat"]; found {
vv := strconv.FormatBool(v.(bool))
u.Set("issourcenat", vv)
}
if v, found := p.p["isstaticnat"]; found {
vv := strconv.FormatBool(v.(bool))
u.Set("isstaticnat", vv)
}
if v, found := p.p["keyword"]; found {
u.Set("keyword", v.(string))
}
if v, found := p.p["listall"]; found {
vv := strconv.FormatBool(v.(bool))
u.Set("listall", vv)
}
if v, found := p.p["page"]; found {
vv := strconv.Itoa(v.(int))
u.Set("page", vv)
}
if v, found := p.p["pagesize"]; found {
vv := strconv.Itoa(v.(int))
u.Set("pagesize", vv)
}
if v, found := p.p["physicalnetworkid"]; found {
u.Set("physicalnetworkid", v.(string))
}
if v, found := p.p["projectid"]; found {
u.Set("projectid", v.(string))
}
if v, found := p.p["state"]; found {
u.Set("state", v.(string))
}
if v, found := p.p["tags"]; found {
i := 0
for k, vv := range v.(map[string]string) {
u.Set(fmt.Sprintf("tags[%d].key", i), k)
u.Set(fmt.Sprintf("tags[%d].value", i), vv)
i++
}
}
if v, found := p.p["vlanid"]; found {
u.Set("vlanid", v.(string))
}
if v, found := p.p["vpcid"]; found {
u.Set("vpcid", v.(string))
}
if v, found := p.p["zoneid"]; found {
u.Set("zoneid", v.(string))
}
return u
}
func (p *ListPublicIpAddressesParams) SetAccount(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["account"] = v
return
}
func (p *ListPublicIpAddressesParams) SetAllocatedonly(v bool) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["allocatedonly"] = v
return
}
func (p *ListPublicIpAddressesParams) SetAssociatednetworkid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["associatednetworkid"] = v
return
}
func (p *ListPublicIpAddressesParams) SetDomainid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["domainid"] = v
return
}
func (p *ListPublicIpAddressesParams) SetFordisplay(v bool) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["fordisplay"] = v
return
}
func (p *ListPublicIpAddressesParams) SetForloadbalancing(v bool) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["forloadbalancing"] = v
return
}
func (p *ListPublicIpAddressesParams) SetForvirtualnetwork(v bool) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["forvirtualnetwork"] = v
return
}
func (p *ListPublicIpAddressesParams) SetId(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["id"] = v
return
}
func (p *ListPublicIpAddressesParams) SetIpaddress(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["ipaddress"] = v
return
}
func (p *ListPublicIpAddressesParams) SetIsrecursive(v bool) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["isrecursive"] = v
return
}
func (p *ListPublicIpAddressesParams) SetIssourcenat(v bool) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["issourcenat"] = v
return
}
func (p *ListPublicIpAddressesParams) SetIsstaticnat(v bool) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["isstaticnat"] = v
return
}
func (p *ListPublicIpAddressesParams) SetKeyword(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["keyword"] = v
return
}
func (p *ListPublicIpAddressesParams) SetListall(v bool) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["listall"] = v
return
}
func (p *ListPublicIpAddressesParams) SetPage(v int) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["page"] = v
return
}
func (p *ListPublicIpAddressesParams) SetPagesize(v int) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["pagesize"] = v
return
}
func (p *ListPublicIpAddressesParams) SetPhysicalnetworkid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["physicalnetworkid"] = v
return
}
func (p *ListPublicIpAddressesParams) SetProjectid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["projectid"] = v
return
}
func (p *ListPublicIpAddressesParams) SetState(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["state"] = v
return
}
func (p *ListPublicIpAddressesParams) SetTags(v map[string]string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["tags"] = v
return
}
func (p *ListPublicIpAddressesParams) SetVlanid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["vlanid"] = v
return
}
func (p *ListPublicIpAddressesParams) SetVpcid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["vpcid"] = v
return
}
func (p *ListPublicIpAddressesParams) SetZoneid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["zoneid"] = v
return
}
// You should always use this function to get a new ListPublicIpAddressesParams instance,
// as then you are sure you have configured all required params
func (s *AddressService) NewListPublicIpAddressesParams() *ListPublicIpAddressesParams {
p := &ListPublicIpAddressesParams{}
p.p = make(map[string]interface{})
return p
}
// This is a courtesy helper function, which in some cases may not work as expected!
func (s *AddressService) GetPublicIpAddressByID(id string, opts ...OptionFunc) (*PublicIpAddress, int, error) {
p := &ListPublicIpAddressesParams{}
p.p = make(map[string]interface{})
p.p["id"] = id
for _, fn := range opts {
if err := fn(s.cs, p); err != nil {
return nil, -1, err
}
}
l, err := s.ListPublicIpAddresses(p)
if err != nil {
if strings.Contains(err.Error(), fmt.Sprintf(
"Invalid parameter id value=%s due to incorrect long value format, "+
"or entity does not exist", id)) {
return nil, 0, fmt.Errorf("No match found for %s: %+v", id, l)
}
return nil, -1, err
}
if l.Count == 0 {
return nil, l.Count, fmt.Errorf("No match found for %s: %+v", id, l)
}
if l.Count == 1 {
return l.PublicIpAddresses[0], l.Count, nil
}
return nil, l.Count, fmt.Errorf("There is more then one result for PublicIpAddress UUID: %s!", id)
}
// Lists all public ip addresses
func (s *AddressService) ListPublicIpAddresses(p *ListPublicIpAddressesParams) (*ListPublicIpAddressesResponse, error) {
resp, err := s.cs.newRequest("listPublicIpAddresses", p.toURLValues())
if err != nil {
return nil, err
}
var r ListPublicIpAddressesResponse
if err := json.Unmarshal(resp, &r); err != nil {
return nil, err
}
return &r, nil
}
type ListPublicIpAddressesResponse struct {
Count int `json:"count"`
PublicIpAddresses []*PublicIpAddress `json:"publicipaddress"`
}
type PublicIpAddress struct {
Account string `json:"account,omitempty"`
Allocated string `json:"allocated,omitempty"`
Associatednetworkid string `json:"associatednetworkid,omitempty"`
Associatednetworkname string `json:"associatednetworkname,omitempty"`
Domain string `json:"domain,omitempty"`
Domainid string `json:"domainid,omitempty"`
Fordisplay bool `json:"fordisplay,omitempty"`
Forvirtualnetwork bool `json:"forvirtualnetwork,omitempty"`
Id string `json:"id,omitempty"`
Ipaddress string `json:"ipaddress,omitempty"`
Isportable bool `json:"isportable,omitempty"`
Issourcenat bool `json:"issourcenat,omitempty"`
Isstaticnat bool `json:"isstaticnat,omitempty"`
Issystem bool `json:"issystem,omitempty"`
Networkid string `json:"networkid,omitempty"`
Physicalnetworkid string `json:"physicalnetworkid,omitempty"`
Project string `json:"project,omitempty"`
Projectid string `json:"projectid,omitempty"`
Purpose string `json:"purpose,omitempty"`
State string `json:"state,omitempty"`
Tags []struct {
Account string `json:"account,omitempty"`
Customer string `json:"customer,omitempty"`
Domain string `json:"domain,omitempty"`
Domainid string `json:"domainid,omitempty"`
Key string `json:"key,omitempty"`
Project string `json:"project,omitempty"`
Projectid string `json:"projectid,omitempty"`
Resourceid string `json:"resourceid,omitempty"`
Resourcetype string `json:"resourcetype,omitempty"`
Value string `json:"value,omitempty"`
} `json:"tags,omitempty"`
Virtualmachinedisplayname string `json:"virtualmachinedisplayname,omitempty"`
Virtualmachineid string `json:"virtualmachineid,omitempty"`
Virtualmachinename string `json:"virtualmachinename,omitempty"`
Vlanid string `json:"vlanid,omitempty"`
Vlanname string `json:"vlanname,omitempty"`
Vmipaddress string `json:"vmipaddress,omitempty"`
Vpcid string `json:"vpcid,omitempty"`
Zoneid string `json:"zoneid,omitempty"`
Zonename string `json:"zonename,omitempty"`
}
type UpdateIpAddressParams struct {
p map[string]interface{}
}
func (p *UpdateIpAddressParams) toURLValues() url.Values {
u := url.Values{}
if p.p == nil {
return u
}
if v, found := p.p["customid"]; found {
u.Set("customid", v.(string))
}
if v, found := p.p["fordisplay"]; found {
vv := strconv.FormatBool(v.(bool))
u.Set("fordisplay", vv)
}
if v, found := p.p["id"]; found {
u.Set("id", v.(string))
}
return u
}
func (p *UpdateIpAddressParams) SetCustomid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["customid"] = v
return
}
func (p *UpdateIpAddressParams) SetFordisplay(v bool) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["fordisplay"] = v
return
}
func (p *UpdateIpAddressParams) SetId(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["id"] = v
return
}
// You should always use this function to get a new UpdateIpAddressParams instance,
// as then you are sure you have configured all required params
func (s *AddressService) NewUpdateIpAddressParams(id string) *UpdateIpAddressParams {
p := &UpdateIpAddressParams{}
p.p = make(map[string]interface{})
p.p["id"] = id
return p
}
// Updates an IP address
func (s *AddressService) UpdateIpAddress(p *UpdateIpAddressParams) (*UpdateIpAddressResponse, error) {
resp, err := s.cs.newRequest("updateIpAddress", p.toURLValues())
if err != nil {
return nil, err
}
var r UpdateIpAddressResponse
if err := json.Unmarshal(resp, &r); err != nil {
return nil, err
}
// If we have a async client, we need to wait for the async result
if s.cs.async {
b, err := s.cs.GetAsyncJobResult(r.JobID, s.cs.timeout)
if err != nil {
if err == AsyncTimeoutErr {
return &r, err
}
return nil, err
}
b, err = getRawValue(b)
if err != nil {
return nil, err
}
if err := json.Unmarshal(b, &r); err != nil {
return nil, err
}
}
return &r, nil
}
type UpdateIpAddressResponse struct {
JobID string `json:"jobid,omitempty"`
Account string `json:"account,omitempty"`
Allocated string `json:"allocated,omitempty"`
Associatednetworkid string `json:"associatednetworkid,omitempty"`
Associatednetworkname string `json:"associatednetworkname,omitempty"`
Domain string `json:"domain,omitempty"`
Domainid string `json:"domainid,omitempty"`
Fordisplay bool `json:"fordisplay,omitempty"`
Forvirtualnetwork bool `json:"forvirtualnetwork,omitempty"`
Id string `json:"id,omitempty"`
Ipaddress string `json:"ipaddress,omitempty"`
Isportable bool `json:"isportable,omitempty"`
Issourcenat bool `json:"issourcenat,omitempty"`
Isstaticnat bool `json:"isstaticnat,omitempty"`
Issystem bool `json:"issystem,omitempty"`
Networkid string `json:"networkid,omitempty"`
Physicalnetworkid string `json:"physicalnetworkid,omitempty"`
Project string `json:"project,omitempty"`
Projectid string `json:"projectid,omitempty"`
Purpose string `json:"purpose,omitempty"`
State string `json:"state,omitempty"`
Tags []struct {
Account string `json:"account,omitempty"`
Customer string `json:"customer,omitempty"`
Domain string `json:"domain,omitempty"`
Domainid string `json:"domainid,omitempty"`
Key string `json:"key,omitempty"`
Project string `json:"project,omitempty"`
Projectid string `json:"projectid,omitempty"`
Resourceid string `json:"resourceid,omitempty"`
Resourcetype string `json:"resourcetype,omitempty"`
Value string `json:"value,omitempty"`
} `json:"tags,omitempty"`
Virtualmachinedisplayname string `json:"virtualmachinedisplayname,omitempty"`
Virtualmachineid string `json:"virtualmachineid,omitempty"`
Virtualmachinename string `json:"virtualmachinename,omitempty"`
Vlanid string `json:"vlanid,omitempty"`
Vlanname string `json:"vlanname,omitempty"`
Vmipaddress string `json:"vmipaddress,omitempty"`
Vpcid string `json:"vpcid,omitempty"`
Zoneid string `json:"zoneid,omitempty"`
Zonename string `json:"zonename,omitempty"`
}

View File

@ -1,887 +0,0 @@
//
// Copyright 2016, Sander van Harmelen
//
// 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 cloudstack
import (
"encoding/json"
"fmt"
"net/url"
"strconv"
"strings"
)
type CreateAffinityGroupParams struct {
p map[string]interface{}
}
func (p *CreateAffinityGroupParams) toURLValues() url.Values {
u := url.Values{}
if p.p == nil {
return u
}
if v, found := p.p["account"]; found {
u.Set("account", v.(string))
}
if v, found := p.p["description"]; found {
u.Set("description", v.(string))
}
if v, found := p.p["domainid"]; found {
u.Set("domainid", v.(string))
}
if v, found := p.p["name"]; found {
u.Set("name", v.(string))
}
if v, found := p.p["projectid"]; found {
u.Set("projectid", v.(string))
}
if v, found := p.p["type"]; found {
u.Set("type", v.(string))
}
return u
}
func (p *CreateAffinityGroupParams) SetAccount(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["account"] = v
return
}
func (p *CreateAffinityGroupParams) SetDescription(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["description"] = v
return
}
func (p *CreateAffinityGroupParams) SetDomainid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["domainid"] = v
return
}
func (p *CreateAffinityGroupParams) SetName(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["name"] = v
return
}
func (p *CreateAffinityGroupParams) SetProjectid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["projectid"] = v
return
}
func (p *CreateAffinityGroupParams) SetType(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["affinityGroupType"] = v
return
}
// You should always use this function to get a new CreateAffinityGroupParams instance,
// as then you are sure you have configured all required params
func (s *AffinityGroupService) NewCreateAffinityGroupParams(name string, affinityGroupType string) *CreateAffinityGroupParams {
p := &CreateAffinityGroupParams{}
p.p = make(map[string]interface{})
p.p["name"] = name
p.p["affinityGroupType"] = affinityGroupType
return p
}
// Creates an affinity/anti-affinity group
func (s *AffinityGroupService) CreateAffinityGroup(p *CreateAffinityGroupParams) (*CreateAffinityGroupResponse, error) {
resp, err := s.cs.newRequest("createAffinityGroup", p.toURLValues())
if err != nil {
return nil, err
}
var r CreateAffinityGroupResponse
if err := json.Unmarshal(resp, &r); err != nil {
return nil, err
}
// If we have a async client, we need to wait for the async result
if s.cs.async {
b, err := s.cs.GetAsyncJobResult(r.JobID, s.cs.timeout)
if err != nil {
if err == AsyncTimeoutErr {
return &r, err
}
return nil, err
}
b, err = getRawValue(b)
if err != nil {
return nil, err
}
if err := json.Unmarshal(b, &r); err != nil {
return nil, err
}
}
return &r, nil
}
type CreateAffinityGroupResponse struct {
JobID string `json:"jobid,omitempty"`
Account string `json:"account,omitempty"`
Description string `json:"description,omitempty"`
Domain string `json:"domain,omitempty"`
Domainid string `json:"domainid,omitempty"`
Id string `json:"id,omitempty"`
Name string `json:"name,omitempty"`
Project string `json:"project,omitempty"`
Projectid string `json:"projectid,omitempty"`
Type string `json:"type,omitempty"`
VirtualmachineIds []string `json:"virtualmachineIds,omitempty"`
}
type DeleteAffinityGroupParams struct {
p map[string]interface{}
}
func (p *DeleteAffinityGroupParams) toURLValues() url.Values {
u := url.Values{}
if p.p == nil {
return u
}
if v, found := p.p["account"]; found {
u.Set("account", v.(string))
}
if v, found := p.p["domainid"]; found {
u.Set("domainid", v.(string))
}
if v, found := p.p["id"]; found {
u.Set("id", v.(string))
}
if v, found := p.p["name"]; found {
u.Set("name", v.(string))
}
if v, found := p.p["projectid"]; found {
u.Set("projectid", v.(string))
}
return u
}
func (p *DeleteAffinityGroupParams) SetAccount(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["account"] = v
return
}
func (p *DeleteAffinityGroupParams) SetDomainid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["domainid"] = v
return
}
func (p *DeleteAffinityGroupParams) SetId(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["id"] = v
return
}
func (p *DeleteAffinityGroupParams) SetName(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["name"] = v
return
}
func (p *DeleteAffinityGroupParams) SetProjectid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["projectid"] = v
return
}
// You should always use this function to get a new DeleteAffinityGroupParams instance,
// as then you are sure you have configured all required params
func (s *AffinityGroupService) NewDeleteAffinityGroupParams() *DeleteAffinityGroupParams {
p := &DeleteAffinityGroupParams{}
p.p = make(map[string]interface{})
return p
}
// Deletes affinity group
func (s *AffinityGroupService) DeleteAffinityGroup(p *DeleteAffinityGroupParams) (*DeleteAffinityGroupResponse, error) {
resp, err := s.cs.newRequest("deleteAffinityGroup", p.toURLValues())
if err != nil {
return nil, err
}
var r DeleteAffinityGroupResponse
if err := json.Unmarshal(resp, &r); err != nil {
return nil, err
}
// If we have a async client, we need to wait for the async result
if s.cs.async {
b, err := s.cs.GetAsyncJobResult(r.JobID, s.cs.timeout)
if err != nil {
if err == AsyncTimeoutErr {
return &r, err
}
return nil, err
}
if err := json.Unmarshal(b, &r); err != nil {
return nil, err
}
}
return &r, nil
}
type DeleteAffinityGroupResponse struct {
JobID string `json:"jobid,omitempty"`
Displaytext string `json:"displaytext,omitempty"`
Success bool `json:"success,omitempty"`
}
type ListAffinityGroupsParams struct {
p map[string]interface{}
}
func (p *ListAffinityGroupsParams) toURLValues() url.Values {
u := url.Values{}
if p.p == nil {
return u
}
if v, found := p.p["account"]; found {
u.Set("account", v.(string))
}
if v, found := p.p["domainid"]; found {
u.Set("domainid", v.(string))
}
if v, found := p.p["id"]; found {
u.Set("id", v.(string))
}
if v, found := p.p["isrecursive"]; found {
vv := strconv.FormatBool(v.(bool))
u.Set("isrecursive", vv)
}
if v, found := p.p["keyword"]; found {
u.Set("keyword", v.(string))
}
if v, found := p.p["listall"]; found {
vv := strconv.FormatBool(v.(bool))
u.Set("listall", vv)
}
if v, found := p.p["name"]; found {
u.Set("name", v.(string))
}
if v, found := p.p["page"]; found {
vv := strconv.Itoa(v.(int))
u.Set("page", vv)
}
if v, found := p.p["pagesize"]; found {
vv := strconv.Itoa(v.(int))
u.Set("pagesize", vv)
}
if v, found := p.p["projectid"]; found {
u.Set("projectid", v.(string))
}
if v, found := p.p["type"]; found {
u.Set("type", v.(string))
}
if v, found := p.p["virtualmachineid"]; found {
u.Set("virtualmachineid", v.(string))
}
return u
}
func (p *ListAffinityGroupsParams) SetAccount(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["account"] = v
return
}
func (p *ListAffinityGroupsParams) SetDomainid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["domainid"] = v
return
}
func (p *ListAffinityGroupsParams) SetId(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["id"] = v
return
}
func (p *ListAffinityGroupsParams) SetIsrecursive(v bool) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["isrecursive"] = v
return
}
func (p *ListAffinityGroupsParams) SetKeyword(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["keyword"] = v
return
}
func (p *ListAffinityGroupsParams) SetListall(v bool) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["listall"] = v
return
}
func (p *ListAffinityGroupsParams) SetName(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["name"] = v
return
}
func (p *ListAffinityGroupsParams) SetPage(v int) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["page"] = v
return
}
func (p *ListAffinityGroupsParams) SetPagesize(v int) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["pagesize"] = v
return
}
func (p *ListAffinityGroupsParams) SetProjectid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["projectid"] = v
return
}
func (p *ListAffinityGroupsParams) SetType(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["affinityGroupType"] = v
return
}
func (p *ListAffinityGroupsParams) SetVirtualmachineid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["virtualmachineid"] = v
return
}
// You should always use this function to get a new ListAffinityGroupsParams instance,
// as then you are sure you have configured all required params
func (s *AffinityGroupService) NewListAffinityGroupsParams() *ListAffinityGroupsParams {
p := &ListAffinityGroupsParams{}
p.p = make(map[string]interface{})
return p
}
// This is a courtesy helper function, which in some cases may not work as expected!
func (s *AffinityGroupService) GetAffinityGroupID(name string, opts ...OptionFunc) (string, int, error) {
p := &ListAffinityGroupsParams{}
p.p = make(map[string]interface{})
p.p["name"] = name
for _, fn := range opts {
if err := fn(s.cs, p); err != nil {
return "", -1, err
}
}
l, err := s.ListAffinityGroups(p)
if err != nil {
return "", -1, err
}
if l.Count == 0 {
return "", l.Count, fmt.Errorf("No match found for %s: %+v", name, l)
}
if l.Count == 1 {
return l.AffinityGroups[0].Id, l.Count, nil
}
if l.Count > 1 {
for _, v := range l.AffinityGroups {
if v.Name == name {
return v.Id, l.Count, nil
}
}
}
return "", l.Count, fmt.Errorf("Could not find an exact match for %s: %+v", name, l)
}
// This is a courtesy helper function, which in some cases may not work as expected!
func (s *AffinityGroupService) GetAffinityGroupByName(name string, opts ...OptionFunc) (*AffinityGroup, int, error) {
id, count, err := s.GetAffinityGroupID(name, opts...)
if err != nil {
return nil, count, err
}
r, count, err := s.GetAffinityGroupByID(id, opts...)
if err != nil {
return nil, count, err
}
return r, count, nil
}
// This is a courtesy helper function, which in some cases may not work as expected!
func (s *AffinityGroupService) GetAffinityGroupByID(id string, opts ...OptionFunc) (*AffinityGroup, int, error) {
p := &ListAffinityGroupsParams{}
p.p = make(map[string]interface{})
p.p["id"] = id
for _, fn := range opts {
if err := fn(s.cs, p); err != nil {
return nil, -1, err
}
}
l, err := s.ListAffinityGroups(p)
if err != nil {
if strings.Contains(err.Error(), fmt.Sprintf(
"Invalid parameter id value=%s due to incorrect long value format, "+
"or entity does not exist", id)) {
return nil, 0, fmt.Errorf("No match found for %s: %+v", id, l)
}
return nil, -1, err
}
if l.Count == 0 {
return nil, l.Count, fmt.Errorf("No match found for %s: %+v", id, l)
}
if l.Count == 1 {
return l.AffinityGroups[0], l.Count, nil
}
return nil, l.Count, fmt.Errorf("There is more then one result for AffinityGroup UUID: %s!", id)
}
// Lists affinity groups
func (s *AffinityGroupService) ListAffinityGroups(p *ListAffinityGroupsParams) (*ListAffinityGroupsResponse, error) {
resp, err := s.cs.newRequest("listAffinityGroups", p.toURLValues())
if err != nil {
return nil, err
}
var r ListAffinityGroupsResponse
if err := json.Unmarshal(resp, &r); err != nil {
return nil, err
}
return &r, nil
}
type ListAffinityGroupsResponse struct {
Count int `json:"count"`
AffinityGroups []*AffinityGroup `json:"affinitygroup"`
}
type AffinityGroup struct {
Account string `json:"account,omitempty"`
Description string `json:"description,omitempty"`
Domain string `json:"domain,omitempty"`
Domainid string `json:"domainid,omitempty"`
Id string `json:"id,omitempty"`
Name string `json:"name,omitempty"`
Project string `json:"project,omitempty"`
Projectid string `json:"projectid,omitempty"`
Type string `json:"type,omitempty"`
VirtualmachineIds []string `json:"virtualmachineIds,omitempty"`
}
type UpdateVMAffinityGroupParams struct {
p map[string]interface{}
}
func (p *UpdateVMAffinityGroupParams) toURLValues() url.Values {
u := url.Values{}
if p.p == nil {
return u
}
if v, found := p.p["affinitygroupids"]; found {
vv := strings.Join(v.([]string), ",")
u.Set("affinitygroupids", vv)
}
if v, found := p.p["affinitygroupnames"]; found {
vv := strings.Join(v.([]string), ",")
u.Set("affinitygroupnames", vv)
}
if v, found := p.p["id"]; found {
u.Set("id", v.(string))
}
return u
}
func (p *UpdateVMAffinityGroupParams) SetAffinitygroupids(v []string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["affinitygroupids"] = v
return
}
func (p *UpdateVMAffinityGroupParams) SetAffinitygroupnames(v []string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["affinitygroupnames"] = v
return
}
func (p *UpdateVMAffinityGroupParams) SetId(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["id"] = v
return
}
// You should always use this function to get a new UpdateVMAffinityGroupParams instance,
// as then you are sure you have configured all required params
func (s *AffinityGroupService) NewUpdateVMAffinityGroupParams(id string) *UpdateVMAffinityGroupParams {
p := &UpdateVMAffinityGroupParams{}
p.p = make(map[string]interface{})
p.p["id"] = id
return p
}
// Updates the affinity/anti-affinity group associations of a virtual machine. The VM has to be stopped and restarted for the new properties to take effect.
func (s *AffinityGroupService) UpdateVMAffinityGroup(p *UpdateVMAffinityGroupParams) (*UpdateVMAffinityGroupResponse, error) {
resp, err := s.cs.newRequest("updateVMAffinityGroup", p.toURLValues())
if err != nil {
return nil, err
}
var r UpdateVMAffinityGroupResponse
if err := json.Unmarshal(resp, &r); err != nil {
return nil, err
}
// If we have a async client, we need to wait for the async result
if s.cs.async {
b, err := s.cs.GetAsyncJobResult(r.JobID, s.cs.timeout)
if err != nil {
if err == AsyncTimeoutErr {
return &r, err
}
return nil, err
}
b, err = getRawValue(b)
if err != nil {
return nil, err
}
if err := json.Unmarshal(b, &r); err != nil {
return nil, err
}
}
return &r, nil
}
type UpdateVMAffinityGroupResponse struct {
JobID string `json:"jobid,omitempty"`
Account string `json:"account,omitempty"`
Affinitygroup []struct {
Account string `json:"account,omitempty"`
Description string `json:"description,omitempty"`
Domain string `json:"domain,omitempty"`
Domainid string `json:"domainid,omitempty"`
Id string `json:"id,omitempty"`
Name string `json:"name,omitempty"`
Project string `json:"project,omitempty"`
Projectid string `json:"projectid,omitempty"`
Type string `json:"type,omitempty"`
VirtualmachineIds []string `json:"virtualmachineIds,omitempty"`
} `json:"affinitygroup,omitempty"`
Cpunumber int `json:"cpunumber,omitempty"`
Cpuspeed int `json:"cpuspeed,omitempty"`
Cpuused string `json:"cpuused,omitempty"`
Created string `json:"created,omitempty"`
Details map[string]string `json:"details,omitempty"`
Diskioread int64 `json:"diskioread,omitempty"`
Diskiowrite int64 `json:"diskiowrite,omitempty"`
Diskkbsread int64 `json:"diskkbsread,omitempty"`
Diskkbswrite int64 `json:"diskkbswrite,omitempty"`
Diskofferingid string `json:"diskofferingid,omitempty"`
Diskofferingname string `json:"diskofferingname,omitempty"`
Displayname string `json:"displayname,omitempty"`
Displayvm bool `json:"displayvm,omitempty"`
Domain string `json:"domain,omitempty"`
Domainid string `json:"domainid,omitempty"`
Forvirtualnetwork bool `json:"forvirtualnetwork,omitempty"`
Group string `json:"group,omitempty"`
Groupid string `json:"groupid,omitempty"`
Guestosid string `json:"guestosid,omitempty"`
Haenable bool `json:"haenable,omitempty"`
Hostid string `json:"hostid,omitempty"`
Hostname string `json:"hostname,omitempty"`
Hypervisor string `json:"hypervisor,omitempty"`
Id string `json:"id,omitempty"`
Instancename string `json:"instancename,omitempty"`
Isdynamicallyscalable bool `json:"isdynamicallyscalable,omitempty"`
Isodisplaytext string `json:"isodisplaytext,omitempty"`
Isoid string `json:"isoid,omitempty"`
Isoname string `json:"isoname,omitempty"`
Keypair string `json:"keypair,omitempty"`
Memory int `json:"memory,omitempty"`
Name string `json:"name,omitempty"`
Networkkbsread int64 `json:"networkkbsread,omitempty"`
Networkkbswrite int64 `json:"networkkbswrite,omitempty"`
Nic []struct {
Broadcasturi string `json:"broadcasturi,omitempty"`
Deviceid string `json:"deviceid,omitempty"`
Gateway string `json:"gateway,omitempty"`
Id string `json:"id,omitempty"`
Ip6address string `json:"ip6address,omitempty"`
Ip6cidr string `json:"ip6cidr,omitempty"`
Ip6gateway string `json:"ip6gateway,omitempty"`
Ipaddress string `json:"ipaddress,omitempty"`
Isdefault bool `json:"isdefault,omitempty"`
Isolationuri string `json:"isolationuri,omitempty"`
Macaddress string `json:"macaddress,omitempty"`
Netmask string `json:"netmask,omitempty"`
Networkid string `json:"networkid,omitempty"`
Networkname string `json:"networkname,omitempty"`
Secondaryip []struct {
Id string `json:"id,omitempty"`
Ipaddress string `json:"ipaddress,omitempty"`
} `json:"secondaryip,omitempty"`
Traffictype string `json:"traffictype,omitempty"`
Type string `json:"type,omitempty"`
Virtualmachineid string `json:"virtualmachineid,omitempty"`
} `json:"nic,omitempty"`
Ostypeid int64 `json:"ostypeid,omitempty"`
Password string `json:"password,omitempty"`
Passwordenabled bool `json:"passwordenabled,omitempty"`
Project string `json:"project,omitempty"`
Projectid string `json:"projectid,omitempty"`
Publicip string `json:"publicip,omitempty"`
Publicipid string `json:"publicipid,omitempty"`
Rootdeviceid int64 `json:"rootdeviceid,omitempty"`
Rootdevicetype string `json:"rootdevicetype,omitempty"`
Securitygroup []struct {
Account string `json:"account,omitempty"`
Description string `json:"description,omitempty"`
Domain string `json:"domain,omitempty"`
Domainid string `json:"domainid,omitempty"`
Egressrule []struct {
Account string `json:"account,omitempty"`
Cidr string `json:"cidr,omitempty"`
Endport int `json:"endport,omitempty"`
Icmpcode int `json:"icmpcode,omitempty"`
Icmptype int `json:"icmptype,omitempty"`
Protocol string `json:"protocol,omitempty"`
Ruleid string `json:"ruleid,omitempty"`
Securitygroupname string `json:"securitygroupname,omitempty"`
Startport int `json:"startport,omitempty"`
Tags []struct {
Account string `json:"account,omitempty"`
Customer string `json:"customer,omitempty"`
Domain string `json:"domain,omitempty"`
Domainid string `json:"domainid,omitempty"`
Key string `json:"key,omitempty"`
Project string `json:"project,omitempty"`
Projectid string `json:"projectid,omitempty"`
Resourceid string `json:"resourceid,omitempty"`
Resourcetype string `json:"resourcetype,omitempty"`
Value string `json:"value,omitempty"`
} `json:"tags,omitempty"`
} `json:"egressrule,omitempty"`
Id string `json:"id,omitempty"`
Ingressrule []struct {
Account string `json:"account,omitempty"`
Cidr string `json:"cidr,omitempty"`
Endport int `json:"endport,omitempty"`
Icmpcode int `json:"icmpcode,omitempty"`
Icmptype int `json:"icmptype,omitempty"`
Protocol string `json:"protocol,omitempty"`
Ruleid string `json:"ruleid,omitempty"`
Securitygroupname string `json:"securitygroupname,omitempty"`
Startport int `json:"startport,omitempty"`
Tags []struct {
Account string `json:"account,omitempty"`
Customer string `json:"customer,omitempty"`
Domain string `json:"domain,omitempty"`
Domainid string `json:"domainid,omitempty"`
Key string `json:"key,omitempty"`
Project string `json:"project,omitempty"`
Projectid string `json:"projectid,omitempty"`
Resourceid string `json:"resourceid,omitempty"`
Resourcetype string `json:"resourcetype,omitempty"`
Value string `json:"value,omitempty"`
} `json:"tags,omitempty"`
} `json:"ingressrule,omitempty"`
Name string `json:"name,omitempty"`
Project string `json:"project,omitempty"`
Projectid string `json:"projectid,omitempty"`
Tags []struct {
Account string `json:"account,omitempty"`
Customer string `json:"customer,omitempty"`
Domain string `json:"domain,omitempty"`
Domainid string `json:"domainid,omitempty"`
Key string `json:"key,omitempty"`
Project string `json:"project,omitempty"`
Projectid string `json:"projectid,omitempty"`
Resourceid string `json:"resourceid,omitempty"`
Resourcetype string `json:"resourcetype,omitempty"`
Value string `json:"value,omitempty"`
} `json:"tags,omitempty"`
Virtualmachinecount int `json:"virtualmachinecount,omitempty"`
Virtualmachineids []string `json:"virtualmachineids,omitempty"`
} `json:"securitygroup,omitempty"`
Serviceofferingid string `json:"serviceofferingid,omitempty"`
Serviceofferingname string `json:"serviceofferingname,omitempty"`
Servicestate string `json:"servicestate,omitempty"`
State string `json:"state,omitempty"`
Tags []struct {
Account string `json:"account,omitempty"`
Customer string `json:"customer,omitempty"`
Domain string `json:"domain,omitempty"`
Domainid string `json:"domainid,omitempty"`
Key string `json:"key,omitempty"`
Project string `json:"project,omitempty"`
Projectid string `json:"projectid,omitempty"`
Resourceid string `json:"resourceid,omitempty"`
Resourcetype string `json:"resourcetype,omitempty"`
Value string `json:"value,omitempty"`
} `json:"tags,omitempty"`
Templatedisplaytext string `json:"templatedisplaytext,omitempty"`
Templateid string `json:"templateid,omitempty"`
Templatename string `json:"templatename,omitempty"`
Userid string `json:"userid,omitempty"`
Username string `json:"username,omitempty"`
Vgpu string `json:"vgpu,omitempty"`
Zoneid string `json:"zoneid,omitempty"`
Zonename string `json:"zonename,omitempty"`
}
type ListAffinityGroupTypesParams struct {
p map[string]interface{}
}
func (p *ListAffinityGroupTypesParams) toURLValues() url.Values {
u := url.Values{}
if p.p == nil {
return u
}
if v, found := p.p["keyword"]; found {
u.Set("keyword", v.(string))
}
if v, found := p.p["page"]; found {
vv := strconv.Itoa(v.(int))
u.Set("page", vv)
}
if v, found := p.p["pagesize"]; found {
vv := strconv.Itoa(v.(int))
u.Set("pagesize", vv)
}
return u
}
func (p *ListAffinityGroupTypesParams) SetKeyword(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["keyword"] = v
return
}
func (p *ListAffinityGroupTypesParams) SetPage(v int) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["page"] = v
return
}
func (p *ListAffinityGroupTypesParams) SetPagesize(v int) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["pagesize"] = v
return
}
// You should always use this function to get a new ListAffinityGroupTypesParams instance,
// as then you are sure you have configured all required params
func (s *AffinityGroupService) NewListAffinityGroupTypesParams() *ListAffinityGroupTypesParams {
p := &ListAffinityGroupTypesParams{}
p.p = make(map[string]interface{})
return p
}
// Lists affinity group types available
func (s *AffinityGroupService) ListAffinityGroupTypes(p *ListAffinityGroupTypesParams) (*ListAffinityGroupTypesResponse, error) {
resp, err := s.cs.newRequest("listAffinityGroupTypes", p.toURLValues())
if err != nil {
return nil, err
}
var r ListAffinityGroupTypesResponse
if err := json.Unmarshal(resp, &r); err != nil {
return nil, err
}
return &r, nil
}
type ListAffinityGroupTypesResponse struct {
Count int `json:"count"`
AffinityGroupTypes []*AffinityGroupType `json:"affinitygrouptype"`
}
type AffinityGroupType struct {
Type string `json:"type,omitempty"`
}

View File

@ -1,505 +0,0 @@
//
// Copyright 2016, Sander van Harmelen
//
// 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 cloudstack
import (
"encoding/json"
"fmt"
"net/url"
"strconv"
"strings"
)
type ListAlertsParams struct {
p map[string]interface{}
}
func (p *ListAlertsParams) toURLValues() url.Values {
u := url.Values{}
if p.p == nil {
return u
}
if v, found := p.p["id"]; found {
u.Set("id", v.(string))
}
if v, found := p.p["keyword"]; found {
u.Set("keyword", v.(string))
}
if v, found := p.p["name"]; found {
u.Set("name", v.(string))
}
if v, found := p.p["page"]; found {
vv := strconv.Itoa(v.(int))
u.Set("page", vv)
}
if v, found := p.p["pagesize"]; found {
vv := strconv.Itoa(v.(int))
u.Set("pagesize", vv)
}
if v, found := p.p["type"]; found {
u.Set("type", v.(string))
}
return u
}
func (p *ListAlertsParams) SetId(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["id"] = v
return
}
func (p *ListAlertsParams) SetKeyword(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["keyword"] = v
return
}
func (p *ListAlertsParams) SetName(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["name"] = v
return
}
func (p *ListAlertsParams) SetPage(v int) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["page"] = v
return
}
func (p *ListAlertsParams) SetPagesize(v int) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["pagesize"] = v
return
}
func (p *ListAlertsParams) SetType(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["alertType"] = v
return
}
// You should always use this function to get a new ListAlertsParams instance,
// as then you are sure you have configured all required params
func (s *AlertService) NewListAlertsParams() *ListAlertsParams {
p := &ListAlertsParams{}
p.p = make(map[string]interface{})
return p
}
// This is a courtesy helper function, which in some cases may not work as expected!
func (s *AlertService) GetAlertID(name string, opts ...OptionFunc) (string, int, error) {
p := &ListAlertsParams{}
p.p = make(map[string]interface{})
p.p["name"] = name
for _, fn := range opts {
if err := fn(s.cs, p); err != nil {
return "", -1, err
}
}
l, err := s.ListAlerts(p)
if err != nil {
return "", -1, err
}
if l.Count == 0 {
return "", l.Count, fmt.Errorf("No match found for %s: %+v", name, l)
}
if l.Count == 1 {
return l.Alerts[0].Id, l.Count, nil
}
if l.Count > 1 {
for _, v := range l.Alerts {
if v.Name == name {
return v.Id, l.Count, nil
}
}
}
return "", l.Count, fmt.Errorf("Could not find an exact match for %s: %+v", name, l)
}
// This is a courtesy helper function, which in some cases may not work as expected!
func (s *AlertService) GetAlertByName(name string, opts ...OptionFunc) (*Alert, int, error) {
id, count, err := s.GetAlertID(name, opts...)
if err != nil {
return nil, count, err
}
r, count, err := s.GetAlertByID(id, opts...)
if err != nil {
return nil, count, err
}
return r, count, nil
}
// This is a courtesy helper function, which in some cases may not work as expected!
func (s *AlertService) GetAlertByID(id string, opts ...OptionFunc) (*Alert, int, error) {
p := &ListAlertsParams{}
p.p = make(map[string]interface{})
p.p["id"] = id
for _, fn := range opts {
if err := fn(s.cs, p); err != nil {
return nil, -1, err
}
}
l, err := s.ListAlerts(p)
if err != nil {
if strings.Contains(err.Error(), fmt.Sprintf(
"Invalid parameter id value=%s due to incorrect long value format, "+
"or entity does not exist", id)) {
return nil, 0, fmt.Errorf("No match found for %s: %+v", id, l)
}
return nil, -1, err
}
if l.Count == 0 {
return nil, l.Count, fmt.Errorf("No match found for %s: %+v", id, l)
}
if l.Count == 1 {
return l.Alerts[0], l.Count, nil
}
return nil, l.Count, fmt.Errorf("There is more then one result for Alert UUID: %s!", id)
}
// Lists all alerts.
func (s *AlertService) ListAlerts(p *ListAlertsParams) (*ListAlertsResponse, error) {
resp, err := s.cs.newRequest("listAlerts", p.toURLValues())
if err != nil {
return nil, err
}
var r ListAlertsResponse
if err := json.Unmarshal(resp, &r); err != nil {
return nil, err
}
return &r, nil
}
type ListAlertsResponse struct {
Count int `json:"count"`
Alerts []*Alert `json:"alert"`
}
type Alert struct {
Description string `json:"description,omitempty"`
Id string `json:"id,omitempty"`
Name string `json:"name,omitempty"`
Sent string `json:"sent,omitempty"`
Type int `json:"type,omitempty"`
}
type ArchiveAlertsParams struct {
p map[string]interface{}
}
func (p *ArchiveAlertsParams) toURLValues() url.Values {
u := url.Values{}
if p.p == nil {
return u
}
if v, found := p.p["enddate"]; found {
u.Set("enddate", v.(string))
}
if v, found := p.p["ids"]; found {
vv := strings.Join(v.([]string), ",")
u.Set("ids", vv)
}
if v, found := p.p["startdate"]; found {
u.Set("startdate", v.(string))
}
if v, found := p.p["type"]; found {
u.Set("type", v.(string))
}
return u
}
func (p *ArchiveAlertsParams) SetEnddate(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["enddate"] = v
return
}
func (p *ArchiveAlertsParams) SetIds(v []string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["ids"] = v
return
}
func (p *ArchiveAlertsParams) SetStartdate(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["startdate"] = v
return
}
func (p *ArchiveAlertsParams) SetType(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["alertType"] = v
return
}
// You should always use this function to get a new ArchiveAlertsParams instance,
// as then you are sure you have configured all required params
func (s *AlertService) NewArchiveAlertsParams() *ArchiveAlertsParams {
p := &ArchiveAlertsParams{}
p.p = make(map[string]interface{})
return p
}
// Archive one or more alerts.
func (s *AlertService) ArchiveAlerts(p *ArchiveAlertsParams) (*ArchiveAlertsResponse, error) {
resp, err := s.cs.newRequest("archiveAlerts", p.toURLValues())
if err != nil {
return nil, err
}
var r ArchiveAlertsResponse
if err := json.Unmarshal(resp, &r); err != nil {
return nil, err
}
return &r, nil
}
type ArchiveAlertsResponse struct {
Displaytext string `json:"displaytext,omitempty"`
Success string `json:"success,omitempty"`
}
type DeleteAlertsParams struct {
p map[string]interface{}
}
func (p *DeleteAlertsParams) toURLValues() url.Values {
u := url.Values{}
if p.p == nil {
return u
}
if v, found := p.p["enddate"]; found {
u.Set("enddate", v.(string))
}
if v, found := p.p["ids"]; found {
vv := strings.Join(v.([]string), ",")
u.Set("ids", vv)
}
if v, found := p.p["startdate"]; found {
u.Set("startdate", v.(string))
}
if v, found := p.p["type"]; found {
u.Set("type", v.(string))
}
return u
}
func (p *DeleteAlertsParams) SetEnddate(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["enddate"] = v
return
}
func (p *DeleteAlertsParams) SetIds(v []string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["ids"] = v
return
}
func (p *DeleteAlertsParams) SetStartdate(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["startdate"] = v
return
}
func (p *DeleteAlertsParams) SetType(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["alertType"] = v
return
}
// You should always use this function to get a new DeleteAlertsParams instance,
// as then you are sure you have configured all required params
func (s *AlertService) NewDeleteAlertsParams() *DeleteAlertsParams {
p := &DeleteAlertsParams{}
p.p = make(map[string]interface{})
return p
}
// Delete one or more alerts.
func (s *AlertService) DeleteAlerts(p *DeleteAlertsParams) (*DeleteAlertsResponse, error) {
resp, err := s.cs.newRequest("deleteAlerts", p.toURLValues())
if err != nil {
return nil, err
}
var r DeleteAlertsResponse
if err := json.Unmarshal(resp, &r); err != nil {
return nil, err
}
return &r, nil
}
type DeleteAlertsResponse struct {
Displaytext string `json:"displaytext,omitempty"`
Success string `json:"success,omitempty"`
}
type GenerateAlertParams struct {
p map[string]interface{}
}
func (p *GenerateAlertParams) toURLValues() url.Values {
u := url.Values{}
if p.p == nil {
return u
}
if v, found := p.p["description"]; found {
u.Set("description", v.(string))
}
if v, found := p.p["name"]; found {
u.Set("name", v.(string))
}
if v, found := p.p["podid"]; found {
u.Set("podid", v.(string))
}
if v, found := p.p["type"]; found {
vv := strconv.Itoa(v.(int))
u.Set("type", vv)
}
if v, found := p.p["zoneid"]; found {
u.Set("zoneid", v.(string))
}
return u
}
func (p *GenerateAlertParams) SetDescription(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["description"] = v
return
}
func (p *GenerateAlertParams) SetName(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["name"] = v
return
}
func (p *GenerateAlertParams) SetPodid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["podid"] = v
return
}
func (p *GenerateAlertParams) SetType(v int) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["alertType"] = v
return
}
func (p *GenerateAlertParams) SetZoneid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["zoneid"] = v
return
}
// You should always use this function to get a new GenerateAlertParams instance,
// as then you are sure you have configured all required params
func (s *AlertService) NewGenerateAlertParams(description string, name string, alertType int) *GenerateAlertParams {
p := &GenerateAlertParams{}
p.p = make(map[string]interface{})
p.p["description"] = description
p.p["name"] = name
p.p["alertType"] = alertType
return p
}
// Generates an alert
func (s *AlertService) GenerateAlert(p *GenerateAlertParams) (*GenerateAlertResponse, error) {
resp, err := s.cs.newRequest("generateAlert", p.toURLValues())
if err != nil {
return nil, err
}
var r GenerateAlertResponse
if err := json.Unmarshal(resp, &r); err != nil {
return nil, err
}
// If we have a async client, we need to wait for the async result
if s.cs.async {
b, err := s.cs.GetAsyncJobResult(r.JobID, s.cs.timeout)
if err != nil {
if err == AsyncTimeoutErr {
return &r, err
}
return nil, err
}
if err := json.Unmarshal(b, &r); err != nil {
return nil, err
}
}
return &r, nil
}
type GenerateAlertResponse struct {
JobID string `json:"jobid,omitempty"`
Displaytext string `json:"displaytext,omitempty"`
Success bool `json:"success,omitempty"`
}

View File

@ -1,239 +0,0 @@
//
// Copyright 2016, Sander van Harmelen
//
// 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 cloudstack
import (
"encoding/json"
"net/url"
"strconv"
"time"
)
type QueryAsyncJobResultParams struct {
p map[string]interface{}
}
func (p *QueryAsyncJobResultParams) toURLValues() url.Values {
u := url.Values{}
if p.p == nil {
return u
}
if v, found := p.p["jobid"]; found {
u.Set("jobid", v.(string))
}
return u
}
func (p *QueryAsyncJobResultParams) SetJobid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["jobid"] = v
return
}
// You should always use this function to get a new QueryAsyncJobResultParams instance,
// as then you are sure you have configured all required params
func (s *AsyncjobService) NewQueryAsyncJobResultParams(jobid string) *QueryAsyncJobResultParams {
p := &QueryAsyncJobResultParams{}
p.p = make(map[string]interface{})
p.p["jobid"] = jobid
return p
}
// Retrieves the current status of asynchronous job.
func (s *AsyncjobService) QueryAsyncJobResult(p *QueryAsyncJobResultParams) (*QueryAsyncJobResultResponse, error) {
var resp json.RawMessage
var err error
// We should be able to retry on failure as this call is idempotent
for i := 0; i < 3; i++ {
resp, err = s.cs.newRequest("queryAsyncJobResult", p.toURLValues())
if err == nil {
break
}
time.Sleep(500 * time.Millisecond)
}
if err != nil {
return nil, err
}
var r QueryAsyncJobResultResponse
if err := json.Unmarshal(resp, &r); err != nil {
return nil, err
}
return &r, nil
}
type QueryAsyncJobResultResponse struct {
Accountid string `json:"accountid,omitempty"`
Cmd string `json:"cmd,omitempty"`
Created string `json:"created,omitempty"`
Jobinstanceid string `json:"jobinstanceid,omitempty"`
Jobinstancetype string `json:"jobinstancetype,omitempty"`
Jobprocstatus int `json:"jobprocstatus,omitempty"`
Jobresult json.RawMessage `json:"jobresult,omitempty"`
Jobresultcode int `json:"jobresultcode,omitempty"`
Jobresulttype string `json:"jobresulttype,omitempty"`
Jobstatus int `json:"jobstatus,omitempty"`
Userid string `json:"userid,omitempty"`
}
type ListAsyncJobsParams struct {
p map[string]interface{}
}
func (p *ListAsyncJobsParams) toURLValues() url.Values {
u := url.Values{}
if p.p == nil {
return u
}
if v, found := p.p["account"]; found {
u.Set("account", v.(string))
}
if v, found := p.p["domainid"]; found {
u.Set("domainid", v.(string))
}
if v, found := p.p["isrecursive"]; found {
vv := strconv.FormatBool(v.(bool))
u.Set("isrecursive", vv)
}
if v, found := p.p["keyword"]; found {
u.Set("keyword", v.(string))
}
if v, found := p.p["listall"]; found {
vv := strconv.FormatBool(v.(bool))
u.Set("listall", vv)
}
if v, found := p.p["page"]; found {
vv := strconv.Itoa(v.(int))
u.Set("page", vv)
}
if v, found := p.p["pagesize"]; found {
vv := strconv.Itoa(v.(int))
u.Set("pagesize", vv)
}
if v, found := p.p["startdate"]; found {
u.Set("startdate", v.(string))
}
return u
}
func (p *ListAsyncJobsParams) SetAccount(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["account"] = v
return
}
func (p *ListAsyncJobsParams) SetDomainid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["domainid"] = v
return
}
func (p *ListAsyncJobsParams) SetIsrecursive(v bool) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["isrecursive"] = v
return
}
func (p *ListAsyncJobsParams) SetKeyword(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["keyword"] = v
return
}
func (p *ListAsyncJobsParams) SetListall(v bool) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["listall"] = v
return
}
func (p *ListAsyncJobsParams) SetPage(v int) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["page"] = v
return
}
func (p *ListAsyncJobsParams) SetPagesize(v int) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["pagesize"] = v
return
}
func (p *ListAsyncJobsParams) SetStartdate(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["startdate"] = v
return
}
// You should always use this function to get a new ListAsyncJobsParams instance,
// as then you are sure you have configured all required params
func (s *AsyncjobService) NewListAsyncJobsParams() *ListAsyncJobsParams {
p := &ListAsyncJobsParams{}
p.p = make(map[string]interface{})
return p
}
// Lists all pending asynchronous jobs for the account.
func (s *AsyncjobService) ListAsyncJobs(p *ListAsyncJobsParams) (*ListAsyncJobsResponse, error) {
resp, err := s.cs.newRequest("listAsyncJobs", p.toURLValues())
if err != nil {
return nil, err
}
var r ListAsyncJobsResponse
if err := json.Unmarshal(resp, &r); err != nil {
return nil, err
}
return &r, nil
}
type ListAsyncJobsResponse struct {
Count int `json:"count"`
AsyncJobs []*AsyncJob `json:"asyncjobs"`
}
type AsyncJob struct {
Accountid string `json:"accountid,omitempty"`
Cmd string `json:"cmd,omitempty"`
Created string `json:"created,omitempty"`
Jobinstanceid string `json:"jobinstanceid,omitempty"`
Jobinstancetype string `json:"jobinstancetype,omitempty"`
Jobprocstatus int `json:"jobprocstatus,omitempty"`
Jobresult json.RawMessage `json:"jobresult,omitempty"`
Jobresultcode int `json:"jobresultcode,omitempty"`
Jobresulttype string `json:"jobresulttype,omitempty"`
Jobstatus int `json:"jobstatus,omitempty"`
Userid string `json:"userid,omitempty"`
}

View File

@ -1,156 +0,0 @@
//
// Copyright 2016, Sander van Harmelen
//
// 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 cloudstack
import (
"encoding/json"
"net/url"
"strconv"
)
type LoginParams struct {
p map[string]interface{}
}
func (p *LoginParams) toURLValues() url.Values {
u := url.Values{}
if p.p == nil {
return u
}
if v, found := p.p["domain"]; found {
u.Set("domain", v.(string))
}
if v, found := p.p["domainId"]; found {
vv := strconv.FormatInt(v.(int64), 10)
u.Set("domainId", vv)
}
if v, found := p.p["password"]; found {
u.Set("password", v.(string))
}
if v, found := p.p["username"]; found {
u.Set("username", v.(string))
}
return u
}
func (p *LoginParams) SetDomain(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["domain"] = v
return
}
func (p *LoginParams) SetDomainId(v int64) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["domainId"] = v
return
}
func (p *LoginParams) SetPassword(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["password"] = v
return
}
func (p *LoginParams) SetUsername(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["username"] = v
return
}
// You should always use this function to get a new LoginParams instance,
// as then you are sure you have configured all required params
func (s *AuthenticationService) NewLoginParams(password string, username string) *LoginParams {
p := &LoginParams{}
p.p = make(map[string]interface{})
p.p["password"] = password
p.p["username"] = username
return p
}
// Logs a user into the CloudStack. A successful login attempt will generate a JSESSIONID cookie value that can be passed in subsequent Query command calls until the "logout" command has been issued or the session has expired.
func (s *AuthenticationService) Login(p *LoginParams) (*LoginResponse, error) {
resp, err := s.cs.newRequest("login", p.toURLValues())
if err != nil {
return nil, err
}
var r LoginResponse
if err := json.Unmarshal(resp, &r); err != nil {
return nil, err
}
return &r, nil
}
type LoginResponse struct {
Account string `json:"account,omitempty"`
Domainid string `json:"domainid,omitempty"`
Firstname string `json:"firstname,omitempty"`
Lastname string `json:"lastname,omitempty"`
Registered string `json:"registered,omitempty"`
Sessionkey string `json:"sessionkey,omitempty"`
Timeout int `json:"timeout,omitempty"`
Timezone string `json:"timezone,omitempty"`
Type string `json:"type,omitempty"`
Userid string `json:"userid,omitempty"`
Username string `json:"username,omitempty"`
}
type LogoutParams struct {
p map[string]interface{}
}
func (p *LogoutParams) toURLValues() url.Values {
u := url.Values{}
if p.p == nil {
return u
}
return u
}
// You should always use this function to get a new LogoutParams instance,
// as then you are sure you have configured all required params
func (s *AuthenticationService) NewLogoutParams() *LogoutParams {
p := &LogoutParams{}
p.p = make(map[string]interface{})
return p
}
// Logs out the user
func (s *AuthenticationService) Logout(p *LogoutParams) (*LogoutResponse, error) {
resp, err := s.cs.newRequest("logout", p.toURLValues())
if err != nil {
return nil, err
}
var r LogoutResponse
if err := json.Unmarshal(resp, &r); err != nil {
return nil, err
}
return &r, nil
}
type LogoutResponse struct {
Description string `json:"description,omitempty"`
}

File diff suppressed because it is too large Load Diff

View File

@ -1,88 +0,0 @@
load("@io_bazel_rules_go//go:def.bzl", "go_library")
go_library(
name = "go_default_library",
srcs = [
"APIDiscoveryService.go",
"AccountService.go",
"AddressService.go",
"AffinityGroupService.go",
"AlertService.go",
"AsyncjobService.go",
"AuthenticationService.go",
"AutoScaleService.go",
"BaremetalService.go",
"CertificateService.go",
"CloudIdentifierService.go",
"ClusterService.go",
"ConfigurationService.go",
"DiskOfferingService.go",
"DomainService.go",
"EventService.go",
"FirewallService.go",
"GuestOSService.go",
"HostService.go",
"HypervisorService.go",
"ISOService.go",
"ImageStoreService.go",
"InternalLBService.go",
"LDAPService.go",
"LimitService.go",
"LoadBalancerService.go",
"NATService.go",
"NetworkACLService.go",
"NetworkDeviceService.go",
"NetworkOfferingService.go",
"NetworkService.go",
"NicService.go",
"NiciraNVPService.go",
"OvsElementService.go",
"PodService.go",
"PoolService.go",
"PortableIPService.go",
"ProjectService.go",
"QuotaService.go",
"RegionService.go",
"ResourcemetadataService.go",
"ResourcetagsService.go",
"RouterService.go",
"SSHService.go",
"SecurityGroupService.go",
"ServiceOfferingService.go",
"SnapshotService.go",
"StoragePoolService.go",
"StratosphereSSPService.go",
"SwiftService.go",
"SystemCapacityService.go",
"SystemVMService.go",
"TemplateService.go",
"UCSService.go",
"UsageService.go",
"UserService.go",
"VLANService.go",
"VMGroupService.go",
"VPCService.go",
"VPNService.go",
"VirtualMachineService.go",
"VolumeService.go",
"ZoneService.go",
"cloudstack.go",
],
importmap = "k8s.io/kubernetes/vendor/github.com/xanzy/go-cloudstack/cloudstack",
importpath = "github.com/xanzy/go-cloudstack/cloudstack",
visibility = ["//visibility:public"],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)

View File

@ -1,918 +0,0 @@
//
// Copyright 2016, Sander van Harmelen
//
// 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 cloudstack
import (
"encoding/json"
"net/url"
"strconv"
)
type AddBaremetalPxeKickStartServerParams struct {
p map[string]interface{}
}
func (p *AddBaremetalPxeKickStartServerParams) toURLValues() url.Values {
u := url.Values{}
if p.p == nil {
return u
}
if v, found := p.p["password"]; found {
u.Set("password", v.(string))
}
if v, found := p.p["physicalnetworkid"]; found {
u.Set("physicalnetworkid", v.(string))
}
if v, found := p.p["podid"]; found {
u.Set("podid", v.(string))
}
if v, found := p.p["pxeservertype"]; found {
u.Set("pxeservertype", v.(string))
}
if v, found := p.p["tftpdir"]; found {
u.Set("tftpdir", v.(string))
}
if v, found := p.p["url"]; found {
u.Set("url", v.(string))
}
if v, found := p.p["username"]; found {
u.Set("username", v.(string))
}
return u
}
func (p *AddBaremetalPxeKickStartServerParams) SetPassword(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["password"] = v
return
}
func (p *AddBaremetalPxeKickStartServerParams) SetPhysicalnetworkid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["physicalnetworkid"] = v
return
}
func (p *AddBaremetalPxeKickStartServerParams) SetPodid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["podid"] = v
return
}
func (p *AddBaremetalPxeKickStartServerParams) SetPxeservertype(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["pxeservertype"] = v
return
}
func (p *AddBaremetalPxeKickStartServerParams) SetTftpdir(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["tftpdir"] = v
return
}
func (p *AddBaremetalPxeKickStartServerParams) SetUrl(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["url"] = v
return
}
func (p *AddBaremetalPxeKickStartServerParams) SetUsername(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["username"] = v
return
}
// You should always use this function to get a new AddBaremetalPxeKickStartServerParams instance,
// as then you are sure you have configured all required params
func (s *BaremetalService) NewAddBaremetalPxeKickStartServerParams(password string, physicalnetworkid string, pxeservertype string, tftpdir string, url string, username string) *AddBaremetalPxeKickStartServerParams {
p := &AddBaremetalPxeKickStartServerParams{}
p.p = make(map[string]interface{})
p.p["password"] = password
p.p["physicalnetworkid"] = physicalnetworkid
p.p["pxeservertype"] = pxeservertype
p.p["tftpdir"] = tftpdir
p.p["url"] = url
p.p["username"] = username
return p
}
// add a baremetal pxe server
func (s *BaremetalService) AddBaremetalPxeKickStartServer(p *AddBaremetalPxeKickStartServerParams) (*AddBaremetalPxeKickStartServerResponse, error) {
resp, err := s.cs.newRequest("addBaremetalPxeKickStartServer", p.toURLValues())
if err != nil {
return nil, err
}
var r AddBaremetalPxeKickStartServerResponse
if err := json.Unmarshal(resp, &r); err != nil {
return nil, err
}
// If we have a async client, we need to wait for the async result
if s.cs.async {
b, err := s.cs.GetAsyncJobResult(r.JobID, s.cs.timeout)
if err != nil {
if err == AsyncTimeoutErr {
return &r, err
}
return nil, err
}
b, err = getRawValue(b)
if err != nil {
return nil, err
}
if err := json.Unmarshal(b, &r); err != nil {
return nil, err
}
}
return &r, nil
}
type AddBaremetalPxeKickStartServerResponse struct {
JobID string `json:"jobid,omitempty"`
Tftpdir string `json:"tftpdir,omitempty"`
}
type AddBaremetalPxePingServerParams struct {
p map[string]interface{}
}
func (p *AddBaremetalPxePingServerParams) toURLValues() url.Values {
u := url.Values{}
if p.p == nil {
return u
}
if v, found := p.p["password"]; found {
u.Set("password", v.(string))
}
if v, found := p.p["physicalnetworkid"]; found {
u.Set("physicalnetworkid", v.(string))
}
if v, found := p.p["pingcifspassword"]; found {
u.Set("pingcifspassword", v.(string))
}
if v, found := p.p["pingcifsusername"]; found {
u.Set("pingcifsusername", v.(string))
}
if v, found := p.p["pingdir"]; found {
u.Set("pingdir", v.(string))
}
if v, found := p.p["pingstorageserverip"]; found {
u.Set("pingstorageserverip", v.(string))
}
if v, found := p.p["podid"]; found {
u.Set("podid", v.(string))
}
if v, found := p.p["pxeservertype"]; found {
u.Set("pxeservertype", v.(string))
}
if v, found := p.p["tftpdir"]; found {
u.Set("tftpdir", v.(string))
}
if v, found := p.p["url"]; found {
u.Set("url", v.(string))
}
if v, found := p.p["username"]; found {
u.Set("username", v.(string))
}
return u
}
func (p *AddBaremetalPxePingServerParams) SetPassword(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["password"] = v
return
}
func (p *AddBaremetalPxePingServerParams) SetPhysicalnetworkid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["physicalnetworkid"] = v
return
}
func (p *AddBaremetalPxePingServerParams) SetPingcifspassword(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["pingcifspassword"] = v
return
}
func (p *AddBaremetalPxePingServerParams) SetPingcifsusername(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["pingcifsusername"] = v
return
}
func (p *AddBaremetalPxePingServerParams) SetPingdir(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["pingdir"] = v
return
}
func (p *AddBaremetalPxePingServerParams) SetPingstorageserverip(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["pingstorageserverip"] = v
return
}
func (p *AddBaremetalPxePingServerParams) SetPodid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["podid"] = v
return
}
func (p *AddBaremetalPxePingServerParams) SetPxeservertype(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["pxeservertype"] = v
return
}
func (p *AddBaremetalPxePingServerParams) SetTftpdir(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["tftpdir"] = v
return
}
func (p *AddBaremetalPxePingServerParams) SetUrl(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["url"] = v
return
}
func (p *AddBaremetalPxePingServerParams) SetUsername(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["username"] = v
return
}
// You should always use this function to get a new AddBaremetalPxePingServerParams instance,
// as then you are sure you have configured all required params
func (s *BaremetalService) NewAddBaremetalPxePingServerParams(password string, physicalnetworkid string, pingdir string, pingstorageserverip string, pxeservertype string, tftpdir string, url string, username string) *AddBaremetalPxePingServerParams {
p := &AddBaremetalPxePingServerParams{}
p.p = make(map[string]interface{})
p.p["password"] = password
p.p["physicalnetworkid"] = physicalnetworkid
p.p["pingdir"] = pingdir
p.p["pingstorageserverip"] = pingstorageserverip
p.p["pxeservertype"] = pxeservertype
p.p["tftpdir"] = tftpdir
p.p["url"] = url
p.p["username"] = username
return p
}
// add a baremetal ping pxe server
func (s *BaremetalService) AddBaremetalPxePingServer(p *AddBaremetalPxePingServerParams) (*AddBaremetalPxePingServerResponse, error) {
resp, err := s.cs.newRequest("addBaremetalPxePingServer", p.toURLValues())
if err != nil {
return nil, err
}
var r AddBaremetalPxePingServerResponse
if err := json.Unmarshal(resp, &r); err != nil {
return nil, err
}
// If we have a async client, we need to wait for the async result
if s.cs.async {
b, err := s.cs.GetAsyncJobResult(r.JobID, s.cs.timeout)
if err != nil {
if err == AsyncTimeoutErr {
return &r, err
}
return nil, err
}
b, err = getRawValue(b)
if err != nil {
return nil, err
}
if err := json.Unmarshal(b, &r); err != nil {
return nil, err
}
}
return &r, nil
}
type AddBaremetalPxePingServerResponse struct {
JobID string `json:"jobid,omitempty"`
Pingdir string `json:"pingdir,omitempty"`
Pingstorageserverip string `json:"pingstorageserverip,omitempty"`
Tftpdir string `json:"tftpdir,omitempty"`
}
type AddBaremetalDhcpParams struct {
p map[string]interface{}
}
func (p *AddBaremetalDhcpParams) toURLValues() url.Values {
u := url.Values{}
if p.p == nil {
return u
}
if v, found := p.p["dhcpservertype"]; found {
u.Set("dhcpservertype", v.(string))
}
if v, found := p.p["password"]; found {
u.Set("password", v.(string))
}
if v, found := p.p["physicalnetworkid"]; found {
u.Set("physicalnetworkid", v.(string))
}
if v, found := p.p["url"]; found {
u.Set("url", v.(string))
}
if v, found := p.p["username"]; found {
u.Set("username", v.(string))
}
return u
}
func (p *AddBaremetalDhcpParams) SetDhcpservertype(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["dhcpservertype"] = v
return
}
func (p *AddBaremetalDhcpParams) SetPassword(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["password"] = v
return
}
func (p *AddBaremetalDhcpParams) SetPhysicalnetworkid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["physicalnetworkid"] = v
return
}
func (p *AddBaremetalDhcpParams) SetUrl(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["url"] = v
return
}
func (p *AddBaremetalDhcpParams) SetUsername(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["username"] = v
return
}
// You should always use this function to get a new AddBaremetalDhcpParams instance,
// as then you are sure you have configured all required params
func (s *BaremetalService) NewAddBaremetalDhcpParams(dhcpservertype string, password string, physicalnetworkid string, url string, username string) *AddBaremetalDhcpParams {
p := &AddBaremetalDhcpParams{}
p.p = make(map[string]interface{})
p.p["dhcpservertype"] = dhcpservertype
p.p["password"] = password
p.p["physicalnetworkid"] = physicalnetworkid
p.p["url"] = url
p.p["username"] = username
return p
}
// adds a baremetal dhcp server
func (s *BaremetalService) AddBaremetalDhcp(p *AddBaremetalDhcpParams) (*AddBaremetalDhcpResponse, error) {
resp, err := s.cs.newRequest("addBaremetalDhcp", p.toURLValues())
if err != nil {
return nil, err
}
var r AddBaremetalDhcpResponse
if err := json.Unmarshal(resp, &r); err != nil {
return nil, err
}
// If we have a async client, we need to wait for the async result
if s.cs.async {
b, err := s.cs.GetAsyncJobResult(r.JobID, s.cs.timeout)
if err != nil {
if err == AsyncTimeoutErr {
return &r, err
}
return nil, err
}
b, err = getRawValue(b)
if err != nil {
return nil, err
}
if err := json.Unmarshal(b, &r); err != nil {
return nil, err
}
}
return &r, nil
}
type AddBaremetalDhcpResponse struct {
JobID string `json:"jobid,omitempty"`
Dhcpservertype string `json:"dhcpservertype,omitempty"`
Id string `json:"id,omitempty"`
Physicalnetworkid string `json:"physicalnetworkid,omitempty"`
Provider string `json:"provider,omitempty"`
Url string `json:"url,omitempty"`
}
type ListBaremetalDhcpParams struct {
p map[string]interface{}
}
func (p *ListBaremetalDhcpParams) toURLValues() url.Values {
u := url.Values{}
if p.p == nil {
return u
}
if v, found := p.p["dhcpservertype"]; found {
u.Set("dhcpservertype", v.(string))
}
if v, found := p.p["id"]; found {
vv := strconv.FormatInt(v.(int64), 10)
u.Set("id", vv)
}
if v, found := p.p["keyword"]; found {
u.Set("keyword", v.(string))
}
if v, found := p.p["page"]; found {
vv := strconv.Itoa(v.(int))
u.Set("page", vv)
}
if v, found := p.p["pagesize"]; found {
vv := strconv.Itoa(v.(int))
u.Set("pagesize", vv)
}
if v, found := p.p["physicalnetworkid"]; found {
u.Set("physicalnetworkid", v.(string))
}
return u
}
func (p *ListBaremetalDhcpParams) SetDhcpservertype(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["dhcpservertype"] = v
return
}
func (p *ListBaremetalDhcpParams) SetId(v int64) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["id"] = v
return
}
func (p *ListBaremetalDhcpParams) SetKeyword(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["keyword"] = v
return
}
func (p *ListBaremetalDhcpParams) SetPage(v int) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["page"] = v
return
}
func (p *ListBaremetalDhcpParams) SetPagesize(v int) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["pagesize"] = v
return
}
func (p *ListBaremetalDhcpParams) SetPhysicalnetworkid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["physicalnetworkid"] = v
return
}
// You should always use this function to get a new ListBaremetalDhcpParams instance,
// as then you are sure you have configured all required params
func (s *BaremetalService) NewListBaremetalDhcpParams(physicalnetworkid string) *ListBaremetalDhcpParams {
p := &ListBaremetalDhcpParams{}
p.p = make(map[string]interface{})
p.p["physicalnetworkid"] = physicalnetworkid
return p
}
// list baremetal dhcp servers
func (s *BaremetalService) ListBaremetalDhcp(p *ListBaremetalDhcpParams) (*ListBaremetalDhcpResponse, error) {
resp, err := s.cs.newRequest("listBaremetalDhcp", p.toURLValues())
if err != nil {
return nil, err
}
var r ListBaremetalDhcpResponse
if err := json.Unmarshal(resp, &r); err != nil {
return nil, err
}
return &r, nil
}
type ListBaremetalDhcpResponse struct {
Count int `json:"count"`
BaremetalDhcp []*BaremetalDhcp `json:"baremetaldhcp"`
}
type BaremetalDhcp struct {
Dhcpservertype string `json:"dhcpservertype,omitempty"`
Id string `json:"id,omitempty"`
Physicalnetworkid string `json:"physicalnetworkid,omitempty"`
Provider string `json:"provider,omitempty"`
Url string `json:"url,omitempty"`
}
type ListBaremetalPxeServersParams struct {
p map[string]interface{}
}
func (p *ListBaremetalPxeServersParams) toURLValues() url.Values {
u := url.Values{}
if p.p == nil {
return u
}
if v, found := p.p["id"]; found {
vv := strconv.FormatInt(v.(int64), 10)
u.Set("id", vv)
}
if v, found := p.p["keyword"]; found {
u.Set("keyword", v.(string))
}
if v, found := p.p["page"]; found {
vv := strconv.Itoa(v.(int))
u.Set("page", vv)
}
if v, found := p.p["pagesize"]; found {
vv := strconv.Itoa(v.(int))
u.Set("pagesize", vv)
}
if v, found := p.p["physicalnetworkid"]; found {
u.Set("physicalnetworkid", v.(string))
}
return u
}
func (p *ListBaremetalPxeServersParams) SetId(v int64) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["id"] = v
return
}
func (p *ListBaremetalPxeServersParams) SetKeyword(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["keyword"] = v
return
}
func (p *ListBaremetalPxeServersParams) SetPage(v int) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["page"] = v
return
}
func (p *ListBaremetalPxeServersParams) SetPagesize(v int) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["pagesize"] = v
return
}
func (p *ListBaremetalPxeServersParams) SetPhysicalnetworkid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["physicalnetworkid"] = v
return
}
// You should always use this function to get a new ListBaremetalPxeServersParams instance,
// as then you are sure you have configured all required params
func (s *BaremetalService) NewListBaremetalPxeServersParams(physicalnetworkid string) *ListBaremetalPxeServersParams {
p := &ListBaremetalPxeServersParams{}
p.p = make(map[string]interface{})
p.p["physicalnetworkid"] = physicalnetworkid
return p
}
// list baremetal pxe server
func (s *BaremetalService) ListBaremetalPxeServers(p *ListBaremetalPxeServersParams) (*ListBaremetalPxeServersResponse, error) {
resp, err := s.cs.newRequest("listBaremetalPxeServers", p.toURLValues())
if err != nil {
return nil, err
}
var r ListBaremetalPxeServersResponse
if err := json.Unmarshal(resp, &r); err != nil {
return nil, err
}
return &r, nil
}
type ListBaremetalPxeServersResponse struct {
Count int `json:"count"`
BaremetalPxeServers []*BaremetalPxeServer `json:"baremetalpxeserver"`
}
type BaremetalPxeServer struct {
Id string `json:"id,omitempty"`
Physicalnetworkid string `json:"physicalnetworkid,omitempty"`
Provider string `json:"provider,omitempty"`
Url string `json:"url,omitempty"`
}
type AddBaremetalRctParams struct {
p map[string]interface{}
}
func (p *AddBaremetalRctParams) toURLValues() url.Values {
u := url.Values{}
if p.p == nil {
return u
}
if v, found := p.p["baremetalrcturl"]; found {
u.Set("baremetalrcturl", v.(string))
}
return u
}
func (p *AddBaremetalRctParams) SetBaremetalrcturl(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["baremetalrcturl"] = v
return
}
// You should always use this function to get a new AddBaremetalRctParams instance,
// as then you are sure you have configured all required params
func (s *BaremetalService) NewAddBaremetalRctParams(baremetalrcturl string) *AddBaremetalRctParams {
p := &AddBaremetalRctParams{}
p.p = make(map[string]interface{})
p.p["baremetalrcturl"] = baremetalrcturl
return p
}
// adds baremetal rack configuration text
func (s *BaremetalService) AddBaremetalRct(p *AddBaremetalRctParams) (*AddBaremetalRctResponse, error) {
resp, err := s.cs.newRequest("addBaremetalRct", p.toURLValues())
if err != nil {
return nil, err
}
var r AddBaremetalRctResponse
if err := json.Unmarshal(resp, &r); err != nil {
return nil, err
}
// If we have a async client, we need to wait for the async result
if s.cs.async {
b, err := s.cs.GetAsyncJobResult(r.JobID, s.cs.timeout)
if err != nil {
if err == AsyncTimeoutErr {
return &r, err
}
return nil, err
}
b, err = getRawValue(b)
if err != nil {
return nil, err
}
if err := json.Unmarshal(b, &r); err != nil {
return nil, err
}
}
return &r, nil
}
type AddBaremetalRctResponse struct {
JobID string `json:"jobid,omitempty"`
Id string `json:"id,omitempty"`
Url string `json:"url,omitempty"`
}
type DeleteBaremetalRctParams struct {
p map[string]interface{}
}
func (p *DeleteBaremetalRctParams) toURLValues() url.Values {
u := url.Values{}
if p.p == nil {
return u
}
if v, found := p.p["id"]; found {
u.Set("id", v.(string))
}
return u
}
func (p *DeleteBaremetalRctParams) SetId(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["id"] = v
return
}
// You should always use this function to get a new DeleteBaremetalRctParams instance,
// as then you are sure you have configured all required params
func (s *BaremetalService) NewDeleteBaremetalRctParams(id string) *DeleteBaremetalRctParams {
p := &DeleteBaremetalRctParams{}
p.p = make(map[string]interface{})
p.p["id"] = id
return p
}
// deletes baremetal rack configuration text
func (s *BaremetalService) DeleteBaremetalRct(p *DeleteBaremetalRctParams) (*DeleteBaremetalRctResponse, error) {
resp, err := s.cs.newRequest("deleteBaremetalRct", p.toURLValues())
if err != nil {
return nil, err
}
var r DeleteBaremetalRctResponse
if err := json.Unmarshal(resp, &r); err != nil {
return nil, err
}
// If we have a async client, we need to wait for the async result
if s.cs.async {
b, err := s.cs.GetAsyncJobResult(r.JobID, s.cs.timeout)
if err != nil {
if err == AsyncTimeoutErr {
return &r, err
}
return nil, err
}
if err := json.Unmarshal(b, &r); err != nil {
return nil, err
}
}
return &r, nil
}
type DeleteBaremetalRctResponse struct {
JobID string `json:"jobid,omitempty"`
Displaytext string `json:"displaytext,omitempty"`
Success bool `json:"success,omitempty"`
}
type ListBaremetalRctParams struct {
p map[string]interface{}
}
func (p *ListBaremetalRctParams) toURLValues() url.Values {
u := url.Values{}
if p.p == nil {
return u
}
if v, found := p.p["keyword"]; found {
u.Set("keyword", v.(string))
}
if v, found := p.p["page"]; found {
vv := strconv.Itoa(v.(int))
u.Set("page", vv)
}
if v, found := p.p["pagesize"]; found {
vv := strconv.Itoa(v.(int))
u.Set("pagesize", vv)
}
return u
}
func (p *ListBaremetalRctParams) SetKeyword(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["keyword"] = v
return
}
func (p *ListBaremetalRctParams) SetPage(v int) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["page"] = v
return
}
func (p *ListBaremetalRctParams) SetPagesize(v int) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["pagesize"] = v
return
}
// You should always use this function to get a new ListBaremetalRctParams instance,
// as then you are sure you have configured all required params
func (s *BaremetalService) NewListBaremetalRctParams() *ListBaremetalRctParams {
p := &ListBaremetalRctParams{}
p.p = make(map[string]interface{})
return p
}
// list baremetal rack configuration
func (s *BaremetalService) ListBaremetalRct(p *ListBaremetalRctParams) (*ListBaremetalRctResponse, error) {
resp, err := s.cs.newRequest("listBaremetalRct", p.toURLValues())
if err != nil {
return nil, err
}
var r ListBaremetalRctResponse
if err := json.Unmarshal(resp, &r); err != nil {
return nil, err
}
return &r, nil
}
type ListBaremetalRctResponse struct {
Count int `json:"count"`
BaremetalRct []*BaremetalRct `json:"baremetalrct"`
}
type BaremetalRct struct {
Id string `json:"id,omitempty"`
Url string `json:"url,omitempty"`
}

View File

@ -1,140 +0,0 @@
//
// Copyright 2016, Sander van Harmelen
//
// 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 cloudstack
import (
"encoding/json"
"net/url"
"strconv"
)
type UploadCustomCertificateParams struct {
p map[string]interface{}
}
func (p *UploadCustomCertificateParams) toURLValues() url.Values {
u := url.Values{}
if p.p == nil {
return u
}
if v, found := p.p["certificate"]; found {
u.Set("certificate", v.(string))
}
if v, found := p.p["domainsuffix"]; found {
u.Set("domainsuffix", v.(string))
}
if v, found := p.p["id"]; found {
vv := strconv.Itoa(v.(int))
u.Set("id", vv)
}
if v, found := p.p["name"]; found {
u.Set("name", v.(string))
}
if v, found := p.p["privatekey"]; found {
u.Set("privatekey", v.(string))
}
return u
}
func (p *UploadCustomCertificateParams) SetCertificate(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["certificate"] = v
return
}
func (p *UploadCustomCertificateParams) SetDomainsuffix(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["domainsuffix"] = v
return
}
func (p *UploadCustomCertificateParams) SetId(v int) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["id"] = v
return
}
func (p *UploadCustomCertificateParams) SetName(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["name"] = v
return
}
func (p *UploadCustomCertificateParams) SetPrivatekey(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["privatekey"] = v
return
}
// You should always use this function to get a new UploadCustomCertificateParams instance,
// as then you are sure you have configured all required params
func (s *CertificateService) NewUploadCustomCertificateParams(certificate string, domainsuffix string) *UploadCustomCertificateParams {
p := &UploadCustomCertificateParams{}
p.p = make(map[string]interface{})
p.p["certificate"] = certificate
p.p["domainsuffix"] = domainsuffix
return p
}
// Uploads a custom certificate for the console proxy VMs to use for SSL. Can be used to upload a single certificate signed by a known CA. Can also be used, through multiple calls, to upload a chain of certificates from CA to the custom certificate itself.
func (s *CertificateService) UploadCustomCertificate(p *UploadCustomCertificateParams) (*UploadCustomCertificateResponse, error) {
resp, err := s.cs.newRequest("uploadCustomCertificate", p.toURLValues())
if err != nil {
return nil, err
}
var r UploadCustomCertificateResponse
if err := json.Unmarshal(resp, &r); err != nil {
return nil, err
}
// If we have a async client, we need to wait for the async result
if s.cs.async {
b, err := s.cs.GetAsyncJobResult(r.JobID, s.cs.timeout)
if err != nil {
if err == AsyncTimeoutErr {
return &r, err
}
return nil, err
}
b, err = getRawValue(b)
if err != nil {
return nil, err
}
if err := json.Unmarshal(b, &r); err != nil {
return nil, err
}
}
return &r, nil
}
type UploadCustomCertificateResponse struct {
JobID string `json:"jobid,omitempty"`
Message string `json:"message,omitempty"`
}

View File

@ -1,74 +0,0 @@
//
// Copyright 2016, Sander van Harmelen
//
// 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 cloudstack
import (
"encoding/json"
"net/url"
)
type GetCloudIdentifierParams struct {
p map[string]interface{}
}
func (p *GetCloudIdentifierParams) toURLValues() url.Values {
u := url.Values{}
if p.p == nil {
return u
}
if v, found := p.p["userid"]; found {
u.Set("userid", v.(string))
}
return u
}
func (p *GetCloudIdentifierParams) SetUserid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["userid"] = v
return
}
// You should always use this function to get a new GetCloudIdentifierParams instance,
// as then you are sure you have configured all required params
func (s *CloudIdentifierService) NewGetCloudIdentifierParams(userid string) *GetCloudIdentifierParams {
p := &GetCloudIdentifierParams{}
p.p = make(map[string]interface{})
p.p["userid"] = userid
return p
}
// Retrieves a cloud identifier.
func (s *CloudIdentifierService) GetCloudIdentifier(p *GetCloudIdentifierParams) (*GetCloudIdentifierResponse, error) {
resp, err := s.cs.newRequest("getCloudIdentifier", p.toURLValues())
if err != nil {
return nil, err
}
var r GetCloudIdentifierResponse
if err := json.Unmarshal(resp, &r); err != nil {
return nil, err
}
return &r, nil
}
type GetCloudIdentifierResponse struct {
Cloudidentifier string `json:"cloudidentifier,omitempty"`
Signature string `json:"signature,omitempty"`
Userid string `json:"userid,omitempty"`
}

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