OCI: vendor dependencies

Signed-off-by: Roy Golan <rgolan@redhat.com>
This commit is contained in:
Roy Golan 2021-11-17 10:34:06 +02:00 committed by Sanne Raymaekers
parent c5feb93279
commit 932e0269f5
1358 changed files with 151693 additions and 0 deletions

2
go.mod
View file

@ -37,11 +37,13 @@ require (
github.com/labstack/echo/v4 v4.6.1
github.com/labstack/gommon v0.3.0
github.com/openshift-online/ocm-sdk-go v0.1.214
github.com/oracle/oci-go-sdk/v54 v54.0.0
github.com/prometheus/client_golang v1.11.0
github.com/prometheus/common v0.30.0 // indirect
github.com/prometheus/procfs v0.7.3 // indirect
github.com/segmentio/ksuid v1.0.4
github.com/sirupsen/logrus v1.8.1
github.com/spf13/cobra v0.0.3
github.com/stretchr/testify v1.7.0
github.com/ubccr/kerby v0.0.0-20170626144437-201a958fc453
github.com/vmware/govmomi v0.26.1

8
go.sum
View file

@ -348,6 +348,7 @@ github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpO
github.com/hudl/fargo v1.3.0/go.mod h1:y3CKSmjA+wD2gak7sUSXTAoopbhU08POFhmITJgmKTg=
github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM=
github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
github.com/influxdata/influxdb1-client v0.0.0-20191209144304-8bf82d3c094d/go.mod h1:qj24IKcXYK6Iy9ceXlo3Tc+vtHo9lIhSX5JddghvEPo=
github.com/jackc/chunkreader v1.0.0 h1:4s39bBR8ByfqH+DKm8rQA3E1LHZWB9XWcrz8fqaZbe0=
@ -544,6 +545,8 @@ github.com/openzipkin-contrib/zipkin-go-opentracing v0.4.5/go.mod h1:/wsWhb9smxS
github.com/openzipkin/zipkin-go v0.1.6/go.mod h1:QgAqvLzwWbR/WpD4A3cGpPtJrZXNIiJc5AZX7/PBEpw=
github.com/openzipkin/zipkin-go v0.2.1/go.mod h1:NaW6tEwdmWMaCDZzg8sh+IBNOxHMPnhQw8ySjnjRyN4=
github.com/openzipkin/zipkin-go v0.2.2/go.mod h1:NaW6tEwdmWMaCDZzg8sh+IBNOxHMPnhQw8ySjnjRyN4=
github.com/oracle/oci-go-sdk/v54 v54.0.0 h1:CDLjeSejv2aDpElAJrhKpi6zvT/zhZCZuXchUUZ+LS4=
github.com/oracle/oci-go-sdk/v54 v54.0.0/go.mod h1:+t+yvcFGVp+3ZnztnyxqXfQDsMlq8U25faBLa+mqCMc=
github.com/pact-foundation/pact-go v1.0.4/go.mod h1:uExwJY4kCzNPcHRj+hCR/HBbOOIwwtUjcrb0b5/5kLM=
github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc=
github.com/pborman/uuid v1.2.0/go.mod h1:X/NO0urCmaxf9VXbdlT7C2Yzkj2IKimNn4k+gtPdI/k=
@ -621,14 +624,19 @@ github.com/smartystreets/goconvey v1.6.4 h1:fv0U8FUIMPNf1L9lnHLvLhgicrIVChEkdzIK
github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA=
github.com/soheilhy/cmux v0.1.4/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4kGIyLM=
github.com/sony/gobreaker v0.4.1/go.mod h1:ZKptC7FHNvhBz7dN2LGjPVBz2sZJmc0/PkyDJOjmxWY=
github.com/sony/gobreaker v0.4.2-0.20210216022020-dd874f9dd33b h1:br+bPNZsJWKicw/5rALEo67QHs5weyD5tf8WST+4sJ0=
github.com/sony/gobreaker v0.4.2-0.20210216022020-dd874f9dd33b/go.mod h1:ZKptC7FHNvhBz7dN2LGjPVBz2sZJmc0/PkyDJOjmxWY=
github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA=
github.com/spf13/cobra v0.0.3 h1:ZlrZ4XsMRm04Fr5pSFxBgfND2EBVa1nLpiy1stUsX/8=
github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ=
github.com/spf13/pflag v1.0.1 h1:aCvUg6QPl3ibpQUxyLkrEkCHtPqYJL4x9AuhqVqFis4=
github.com/spf13/pflag v1.0.1/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=
github.com/streadway/amqp v0.0.0-20190404075320-75d898a42a94/go.mod h1:AZpEONHx3DKn8O/DFsRAY58/XVQiIPMTMB1SddzLXVw=
github.com/streadway/amqp v0.0.0-20190827072141-edfb9018d271/go.mod h1:AZpEONHx3DKn8O/DFsRAY58/XVQiIPMTMB1SddzLXVw=
github.com/streadway/handy v0.0.0-20190108123426-d5acb3125c2a/go.mod h1:qNTQ5P5JnDBl6z3cMAg/SywNDC5ABu5ApDIw6lUbRmI=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.2.0 h1:Hbg2NidpLE8veEBkEZTL3CvlkUIVzuU9jDplZO54c48=
github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=

13
vendor/github.com/inconshreveable/mousetrap/LICENSE generated vendored Normal file
View file

@ -0,0 +1,13 @@
Copyright 2014 Alan Shreve
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.

23
vendor/github.com/inconshreveable/mousetrap/README.md generated vendored Normal file
View file

@ -0,0 +1,23 @@
# mousetrap
mousetrap is a tiny library that answers a single question.
On a Windows machine, was the process invoked by someone double clicking on
the executable file while browsing in explorer?
### Motivation
Windows developers unfamiliar with command line tools will often "double-click"
the executable for a tool. Because most CLI tools print the help and then exit
when invoked without arguments, this is often very frustrating for those users.
mousetrap provides a way to detect these invocations so that you can provide
more helpful behavior and instructions on how to run the CLI tool. To see what
this looks like, both from an organizational and a technical perspective, see
https://inconshreveable.com/09-09-2014/sweat-the-small-stuff/
### The interface
The library exposes a single interface:
func StartedByExplorer() (bool)

View file

@ -0,0 +1,15 @@
// +build !windows
package mousetrap
// StartedByExplorer returns true if the program was invoked by the user
// double-clicking on the executable from explorer.exe
//
// It is conservative and returns false if any of the internal calls fail.
// It does not guarantee that the program was run from a terminal. It only can tell you
// whether it was launched from explorer.exe
//
// On non-Windows platforms, it always returns false.
func StartedByExplorer() bool {
return false
}

View file

@ -0,0 +1,98 @@
// +build windows
// +build !go1.4
package mousetrap
import (
"fmt"
"os"
"syscall"
"unsafe"
)
const (
// defined by the Win32 API
th32cs_snapprocess uintptr = 0x2
)
var (
kernel = syscall.MustLoadDLL("kernel32.dll")
CreateToolhelp32Snapshot = kernel.MustFindProc("CreateToolhelp32Snapshot")
Process32First = kernel.MustFindProc("Process32FirstW")
Process32Next = kernel.MustFindProc("Process32NextW")
)
// ProcessEntry32 structure defined by the Win32 API
type processEntry32 struct {
dwSize uint32
cntUsage uint32
th32ProcessID uint32
th32DefaultHeapID int
th32ModuleID uint32
cntThreads uint32
th32ParentProcessID uint32
pcPriClassBase int32
dwFlags uint32
szExeFile [syscall.MAX_PATH]uint16
}
func getProcessEntry(pid int) (pe *processEntry32, err error) {
snapshot, _, e1 := CreateToolhelp32Snapshot.Call(th32cs_snapprocess, uintptr(0))
if snapshot == uintptr(syscall.InvalidHandle) {
err = fmt.Errorf("CreateToolhelp32Snapshot: %v", e1)
return
}
defer syscall.CloseHandle(syscall.Handle(snapshot))
var processEntry processEntry32
processEntry.dwSize = uint32(unsafe.Sizeof(processEntry))
ok, _, e1 := Process32First.Call(snapshot, uintptr(unsafe.Pointer(&processEntry)))
if ok == 0 {
err = fmt.Errorf("Process32First: %v", e1)
return
}
for {
if processEntry.th32ProcessID == uint32(pid) {
pe = &processEntry
return
}
ok, _, e1 = Process32Next.Call(snapshot, uintptr(unsafe.Pointer(&processEntry)))
if ok == 0 {
err = fmt.Errorf("Process32Next: %v", e1)
return
}
}
}
func getppid() (pid int, err error) {
pe, err := getProcessEntry(os.Getpid())
if err != nil {
return
}
pid = int(pe.th32ParentProcessID)
return
}
// StartedByExplorer returns true if the program was invoked by the user double-clicking
// on the executable from explorer.exe
//
// It is conservative and returns false if any of the internal calls fail.
// It does not guarantee that the program was run from a terminal. It only can tell you
// whether it was launched from explorer.exe
func StartedByExplorer() bool {
ppid, err := getppid()
if err != nil {
return false
}
pe, err := getProcessEntry(ppid)
if err != nil {
return false
}
name := syscall.UTF16ToString(pe.szExeFile[:])
return name == "explorer.exe"
}

View file

@ -0,0 +1,46 @@
// +build windows
// +build go1.4
package mousetrap
import (
"os"
"syscall"
"unsafe"
)
func getProcessEntry(pid int) (*syscall.ProcessEntry32, error) {
snapshot, err := syscall.CreateToolhelp32Snapshot(syscall.TH32CS_SNAPPROCESS, 0)
if err != nil {
return nil, err
}
defer syscall.CloseHandle(snapshot)
var procEntry syscall.ProcessEntry32
procEntry.Size = uint32(unsafe.Sizeof(procEntry))
if err = syscall.Process32First(snapshot, &procEntry); err != nil {
return nil, err
}
for {
if procEntry.ProcessID == uint32(pid) {
return &procEntry, nil
}
err = syscall.Process32Next(snapshot, &procEntry)
if err != nil {
return nil, err
}
}
}
// StartedByExplorer returns true if the program was invoked by the user double-clicking
// on the executable from explorer.exe
//
// It is conservative and returns false if any of the internal calls fail.
// It does not guarantee that the program was run from a terminal. It only can tell you
// whether it was launched from explorer.exe
func StartedByExplorer() bool {
pe, err := getProcessEntry(os.Getppid())
if err != nil {
return false
}
return "explorer.exe" == syscall.UTF16ToString(pe.ExeFile[:])
}

82
vendor/github.com/oracle/oci-go-sdk/v54/LICENSE.txt generated vendored Normal file
View file

@ -0,0 +1,82 @@
Copyright (c) 2016, 2018, 2020, Oracle and/or its affiliates. All rights reserved.
This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl
or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
 ____________________________
The Universal Permissive License (UPL), Version 1.0
Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
Subject to the condition set forth below, permission is hereby granted to any person obtaining a copy of this software, associated documentation and/or data (collectively the "Software"), free of charge and under any and all copyright rights in the Software, and any and all patent rights owned or freely licensable by each licensor hereunder covering either (i) the unmodified Software as contributed to or provided by such licensor, or (ii) the Larger Works (as defined below), to deal in both
(a) the Software, and
(b) any piece of software and/or hardware listed in the lrgrwrks.txt file if one is included with the Software (each a "Larger Work" to which the Software is contributed by such licensors),
without restriction, including without limitation the rights to copy, create derivative works of, display, perform, and distribute the Software and make, use, sell, offer for sale, import, export, have made, and have sold the Software and the Larger Work(s), and to sublicense the foregoing rights on either these or other terms.
This license is subject to the following condition:
The above copyright notice and either this complete permission notice or at a minimum a reference to the UPL must be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
The Apache Software License, Version 2.0
Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); You may not use this product except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0. A copy of the license is also reproduced below. 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.
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:
You must give any other recipients of the Work or Derivative Works a copy of this License; and
You must cause any modified files to carry prominent notices stating that You changed the files; and
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
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.

1
vendor/github.com/oracle/oci-go-sdk/v54/NOTICE.txt generated vendored Normal file
View file

@ -0,0 +1 @@
Copyright (c) 2016, 2018, 2020, Oracle and/or its affiliates.

View file

@ -0,0 +1,261 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
package auth
import (
"bytes"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"fmt"
"github.com/oracle/oci-go-sdk/v54/common"
"sync"
)
// x509CertificateRetriever provides an X509 certificate with the RSA private key
type x509CertificateRetriever interface {
Refresh() error
CertificatePemRaw() []byte
Certificate() *x509.Certificate
PrivateKeyPemRaw() []byte
PrivateKey() *rsa.PrivateKey
}
// urlBasedX509CertificateRetriever retrieves PEM-encoded X509 certificates from the given URLs.
type urlBasedX509CertificateRetriever struct {
certURL string
privateKeyURL string
passphrase string
certificatePemRaw []byte
certificate *x509.Certificate
privateKeyPemRaw []byte
privateKey *rsa.PrivateKey
mux sync.Mutex
dispatcher common.HTTPRequestDispatcher
}
func newURLBasedX509CertificateRetriever(dispatcher common.HTTPRequestDispatcher, certURL, privateKeyURL, passphrase string) x509CertificateRetriever {
return &urlBasedX509CertificateRetriever{
certURL: certURL,
privateKeyURL: privateKeyURL,
passphrase: passphrase,
mux: sync.Mutex{},
dispatcher: dispatcher,
}
}
// Refresh() is failure atomic, i.e., CertificatePemRaw(), Certificate(), PrivateKeyPemRaw(), and PrivateKey() would
// return their previous values if Refresh() fails.
func (r *urlBasedX509CertificateRetriever) Refresh() error {
common.Debugln("Refreshing certificate")
r.mux.Lock()
defer r.mux.Unlock()
var err error
var certificatePemRaw []byte
var certificate *x509.Certificate
if certificatePemRaw, certificate, err = r.renewCertificate(r.certURL); err != nil {
return fmt.Errorf("failed to renew certificate: %s", err.Error())
}
var privateKeyPemRaw []byte
var privateKey *rsa.PrivateKey
if r.privateKeyURL != "" {
if privateKeyPemRaw, privateKey, err = r.renewPrivateKey(r.privateKeyURL, r.passphrase); err != nil {
return fmt.Errorf("failed to renew private key: %s", err.Error())
}
}
r.certificatePemRaw = certificatePemRaw
r.certificate = certificate
r.privateKeyPemRaw = privateKeyPemRaw
r.privateKey = privateKey
return nil
}
func (r *urlBasedX509CertificateRetriever) renewCertificate(url string) (certificatePemRaw []byte, certificate *x509.Certificate, err error) {
var body bytes.Buffer
if body, _, err = httpGet(r.dispatcher, url); err != nil {
return nil, nil, fmt.Errorf("failed to get certificate from %s: %s", url, err.Error())
}
certificatePemRaw = body.Bytes()
var block *pem.Block
block, _ = pem.Decode(certificatePemRaw)
if block == nil {
return nil, nil, fmt.Errorf("failed to parse the new certificate, not valid pem data")
}
if certificate, err = x509.ParseCertificate(block.Bytes); err != nil {
return nil, nil, fmt.Errorf("failed to parse the new certificate: %s", err.Error())
}
return certificatePemRaw, certificate, nil
}
func (r *urlBasedX509CertificateRetriever) renewPrivateKey(url, passphrase string) (privateKeyPemRaw []byte, privateKey *rsa.PrivateKey, err error) {
var body bytes.Buffer
if body, _, err = httpGet(r.dispatcher, url); err != nil {
return nil, nil, fmt.Errorf("failed to get private key from %s: %s", url, err.Error())
}
privateKeyPemRaw = body.Bytes()
if privateKey, err = common.PrivateKeyFromBytes(privateKeyPemRaw, &passphrase); err != nil {
return nil, nil, fmt.Errorf("failed to parse the new private key: %s", err.Error())
}
return privateKeyPemRaw, privateKey, nil
}
func (r *urlBasedX509CertificateRetriever) CertificatePemRaw() []byte {
r.mux.Lock()
defer r.mux.Unlock()
if r.certificatePemRaw == nil {
return nil
}
c := make([]byte, len(r.certificatePemRaw))
copy(c, r.certificatePemRaw)
return c
}
func (r *urlBasedX509CertificateRetriever) Certificate() *x509.Certificate {
r.mux.Lock()
defer r.mux.Unlock()
if r.certificate == nil {
return nil
}
c := *r.certificate
return &c
}
func (r *urlBasedX509CertificateRetriever) PrivateKeyPemRaw() []byte {
r.mux.Lock()
defer r.mux.Unlock()
if r.privateKeyPemRaw == nil {
return nil
}
c := make([]byte, len(r.privateKeyPemRaw))
copy(c, r.privateKeyPemRaw)
return c
}
func (r *urlBasedX509CertificateRetriever) PrivateKey() *rsa.PrivateKey {
r.mux.Lock()
defer r.mux.Unlock()
//Nil Private keys are supported as part of a certificate
if r.privateKey == nil {
return nil
}
c := *r.privateKey
return &c
}
//staticCertificateRetriever serves certificates from static data
type staticCertificateRetriever struct {
Passphrase []byte
CertificatePem []byte
PrivateKeyPem []byte
certificate *x509.Certificate
privateKey *rsa.PrivateKey
mux sync.Mutex
}
//Refresh proccess the inputs into appropiate keys and certificates
func (r *staticCertificateRetriever) Refresh() error {
r.mux.Lock()
defer r.mux.Unlock()
certifcate, err := r.readCertificate()
if err != nil {
r.certificate = nil
return err
}
r.certificate = certifcate
key, err := r.readPrivateKey()
if err != nil {
r.privateKey = nil
return err
}
r.privateKey = key
return nil
}
func (r *staticCertificateRetriever) Certificate() *x509.Certificate {
r.mux.Lock()
defer r.mux.Unlock()
return r.certificate
}
func (r *staticCertificateRetriever) PrivateKey() *rsa.PrivateKey {
r.mux.Lock()
defer r.mux.Unlock()
return r.privateKey
}
func (r *staticCertificateRetriever) CertificatePemRaw() []byte {
r.mux.Lock()
defer r.mux.Unlock()
if r.CertificatePem == nil {
return nil
}
c := make([]byte, len(r.CertificatePem))
copy(c, r.CertificatePem)
return c
}
func (r *staticCertificateRetriever) PrivateKeyPemRaw() []byte {
r.mux.Lock()
defer r.mux.Unlock()
if r.PrivateKeyPem == nil {
return nil
}
c := make([]byte, len(r.PrivateKeyPem))
copy(c, r.PrivateKeyPem)
return c
}
func (r *staticCertificateRetriever) readCertificate() (certificate *x509.Certificate, err error) {
block, _ := pem.Decode(r.CertificatePem)
if block == nil {
return nil, fmt.Errorf("failed to parse the new certificate, not valid pem data")
}
if certificate, err = x509.ParseCertificate(block.Bytes); err != nil {
return nil, fmt.Errorf("failed to parse the new certificate: %s", err.Error())
}
return certificate, nil
}
func (r *staticCertificateRetriever) readPrivateKey() (*rsa.PrivateKey, error) {
if r.PrivateKeyPem == nil {
return nil, nil
}
var pass *string
if r.Passphrase == nil {
pass = nil
} else {
ss := string(r.Passphrase)
pass = &ss
}
return common.PrivateKeyFromBytes(r.PrivateKeyPem, pass)
}

View file

@ -0,0 +1,110 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
package auth
import (
"crypto/rsa"
"fmt"
"github.com/oracle/oci-go-sdk/v54/common"
)
type instancePrincipalConfigurationProvider struct {
keyProvider instancePrincipalKeyProvider
region *common.Region
}
//InstancePrincipalConfigurationProvider returns a configuration for instance principals
func InstancePrincipalConfigurationProvider() (common.ConfigurationProvider, error) {
return newInstancePrincipalConfigurationProvider("", nil)
}
//InstancePrincipalConfigurationProviderForRegion returns a configuration for instance principals with a given region
func InstancePrincipalConfigurationProviderForRegion(region common.Region) (common.ConfigurationProvider, error) {
return newInstancePrincipalConfigurationProvider(region, nil)
}
//InstancePrincipalConfigurationProviderWithCustomClient returns a configuration for instance principals using a modifier function to modify the HTTPRequestDispatcher
func InstancePrincipalConfigurationProviderWithCustomClient(modifier func(common.HTTPRequestDispatcher) (common.HTTPRequestDispatcher, error)) (common.ConfigurationProvider, error) {
return newInstancePrincipalConfigurationProvider("", modifier)
}
//InstancePrincipalConfigurationForRegionWithCustomClient returns a configuration for instance principals with a given region using a modifier function to modify the HTTPRequestDispatcher
func InstancePrincipalConfigurationForRegionWithCustomClient(region common.Region, modifier func(common.HTTPRequestDispatcher) (common.HTTPRequestDispatcher, error)) (common.ConfigurationProvider, error) {
return newInstancePrincipalConfigurationProvider(region, modifier)
}
func newInstancePrincipalConfigurationProvider(region common.Region, modifier func(common.HTTPRequestDispatcher) (common.HTTPRequestDispatcher, error)) (common.ConfigurationProvider, error) {
var err error
var keyProvider *instancePrincipalKeyProvider
if keyProvider, err = newInstancePrincipalKeyProvider(modifier); err != nil {
return nil, fmt.Errorf("failed to create a new key provider for instance principal: %s", err.Error())
}
if len(region) > 0 {
return instancePrincipalConfigurationProvider{keyProvider: *keyProvider, region: &region}, nil
}
return instancePrincipalConfigurationProvider{keyProvider: *keyProvider, region: nil}, nil
}
//InstancePrincipalConfigurationWithCerts returns a configuration for instance principals with a given region and hardcoded certificates in lieu of metadata service certs
func InstancePrincipalConfigurationWithCerts(region common.Region, leafCertificate, leafPassphrase, leafPrivateKey []byte, intermediateCertificates [][]byte) (common.ConfigurationProvider, error) {
leafCertificateRetriever := staticCertificateRetriever{Passphrase: leafPassphrase, CertificatePem: leafCertificate, PrivateKeyPem: leafPrivateKey}
//The .Refresh() call actually reads the certificates from the inputs
err := leafCertificateRetriever.Refresh()
if err != nil {
return nil, err
}
certificate := leafCertificateRetriever.Certificate()
tenancyID := extractTenancyIDFromCertificate(certificate)
fedClient, err := newX509FederationClientWithCerts(region, tenancyID, leafCertificate, leafPassphrase, leafPrivateKey, intermediateCertificates, *newDispatcherModifier(nil))
if err != nil {
return nil, err
}
provider := instancePrincipalConfigurationProvider{
keyProvider: instancePrincipalKeyProvider{
Region: region,
FederationClient: fedClient,
TenancyID: tenancyID,
},
region: &region,
}
return provider, nil
}
func (p instancePrincipalConfigurationProvider) PrivateRSAKey() (*rsa.PrivateKey, error) {
return p.keyProvider.PrivateRSAKey()
}
func (p instancePrincipalConfigurationProvider) KeyID() (string, error) {
return p.keyProvider.KeyID()
}
func (p instancePrincipalConfigurationProvider) TenancyOCID() (string, error) {
return p.keyProvider.TenancyOCID()
}
func (p instancePrincipalConfigurationProvider) UserOCID() (string, error) {
return "", nil
}
func (p instancePrincipalConfigurationProvider) KeyFingerprint() (string, error) {
return "", nil
}
func (p instancePrincipalConfigurationProvider) Region() (string, error) {
if p.region == nil {
region := p.keyProvider.RegionForFederationClient()
common.Debugf("Region in instance principal configuration provider is nil. Returning federation clients region: %s", region)
return string(region), nil
}
return string(*p.region), nil
}
func (p instancePrincipalConfigurationProvider) AuthType() (common.AuthConfig, error) {
return common.AuthConfig{common.InstancePrincipal, false, nil}, fmt.Errorf("unsupported, keep the interface")
}

View file

@ -0,0 +1,41 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
package auth
import "github.com/oracle/oci-go-sdk/v54/common"
//dispatcherModifier gives ability to modify a HTTPRequestDispatcher before use.
type dispatcherModifier struct {
modifiers []func(common.HTTPRequestDispatcher) (common.HTTPRequestDispatcher, error)
}
//newDispatcherModifier creates a new dispatcherModifier with optional initial modifier (may be nil).
func newDispatcherModifier(modifier func(common.HTTPRequestDispatcher) (common.HTTPRequestDispatcher, error)) *dispatcherModifier {
dispatcherModifier := &dispatcherModifier{
modifiers: make([]func(common.HTTPRequestDispatcher) (common.HTTPRequestDispatcher, error), 0),
}
if modifier != nil {
dispatcherModifier.QueueModifier(modifier)
}
return dispatcherModifier
}
//QueueModifier queues up a new modifier
func (c *dispatcherModifier) QueueModifier(modifier func(common.HTTPRequestDispatcher) (common.HTTPRequestDispatcher, error)) {
c.modifiers = append(c.modifiers, modifier)
}
//Modify the provided HTTPRequestDispatcher with this modifier, and return the result, or error if something goes wrong
func (c *dispatcherModifier) Modify(dispatcher common.HTTPRequestDispatcher) (common.HTTPRequestDispatcher, error) {
if len(c.modifiers) > 0 {
for _, modifier := range c.modifiers {
var err error
if dispatcher, err = modifier(dispatcher); err != nil {
common.Debugf("An error occurred when attempting to modify the dispatcher. Error was: %s", err.Error())
return nil, err
}
}
}
return dispatcher, nil
}

View file

@ -0,0 +1,569 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Package auth provides supporting functions and structs for authentication
package auth
import (
"context"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"github.com/oracle/oci-go-sdk/v54/common"
"io/ioutil"
"net/http"
"os"
"strings"
"sync"
"time"
)
// federationClient is a client to retrieve the security token for an instance principal necessary to sign a request.
// It also provides the private key whose corresponding public key is used to retrieve the security token.
type federationClient interface {
ClaimHolder
PrivateKey() (*rsa.PrivateKey, error)
SecurityToken() (string, error)
}
// ClaimHolder is implemented by any token interface that provides access to the security claims embedded in the token.
type ClaimHolder interface {
GetClaim(key string) (interface{}, error)
}
type genericFederationClient struct {
SessionKeySupplier sessionKeySupplier
RefreshSecurityToken func() (securityToken, error)
securityToken securityToken
mux sync.Mutex
}
var _ federationClient = &genericFederationClient{}
func (c *genericFederationClient) PrivateKey() (*rsa.PrivateKey, error) {
c.mux.Lock()
defer c.mux.Unlock()
if err := c.renewKeyAndSecurityTokenIfNotValid(); err != nil {
return nil, err
}
return c.SessionKeySupplier.PrivateKey(), nil
}
func (c *genericFederationClient) SecurityToken() (token string, err error) {
c.mux.Lock()
defer c.mux.Unlock()
if err = c.renewKeyAndSecurityTokenIfNotValid(); err != nil {
return "", err
}
return c.securityToken.String(), nil
}
func (c *genericFederationClient) renewKeyAndSecurityTokenIfNotValid() (err error) {
if c.securityToken == nil || !c.securityToken.Valid() {
if err = c.renewKeyAndSecurityToken(); err != nil {
return fmt.Errorf("failed to renew security token: %s", err.Error())
}
}
return nil
}
func (c *genericFederationClient) renewKeyAndSecurityToken() (err error) {
common.Logf("Renewing keys for file based security token at: %v\n", time.Now().Format("15:04:05.000"))
if err = c.SessionKeySupplier.Refresh(); err != nil {
return fmt.Errorf("failed to refresh session key: %s", err.Error())
}
common.Logf("Renewing security token at: %v\n", time.Now().Format("15:04:05.000"))
if c.securityToken, err = c.RefreshSecurityToken(); err != nil {
return fmt.Errorf("failed to refresh security token key: %s", err.Error())
}
common.Logf("Security token renewed at: %v\n", time.Now().Format("15:04:05.000"))
return nil
}
func (c *genericFederationClient) GetClaim(key string) (interface{}, error) {
c.mux.Lock()
defer c.mux.Unlock()
if err := c.renewKeyAndSecurityTokenIfNotValid(); err != nil {
return nil, err
}
return c.securityToken.GetClaim(key)
}
func newFileBasedFederationClient(securityTokenPath string, supplier sessionKeySupplier) (*genericFederationClient, error) {
return &genericFederationClient{
SessionKeySupplier: supplier,
RefreshSecurityToken: func() (token securityToken, err error) {
var content []byte
if content, err = ioutil.ReadFile(securityTokenPath); err != nil {
return nil, fmt.Errorf("failed to read security token from :%s. Due to: %s", securityTokenPath, err.Error())
}
var newToken securityToken
if newToken, err = newPrincipalToken(string(content)); err != nil {
return nil, fmt.Errorf("failed to read security token from :%s. Due to: %s", securityTokenPath, err.Error())
}
return newToken, nil
},
}, nil
}
func newStaticFederationClient(sessionToken string, supplier sessionKeySupplier) (*genericFederationClient, error) {
var newToken securityToken
var err error
if newToken, err = newPrincipalToken(string(sessionToken)); err != nil {
return nil, fmt.Errorf("failed to read security token. Due to: %s", err.Error())
}
return &genericFederationClient{
SessionKeySupplier: supplier,
RefreshSecurityToken: func() (token securityToken, err error) {
return newToken, nil
},
}, nil
}
// x509FederationClient retrieves a security token from Auth service.
type x509FederationClient struct {
tenancyID string
sessionKeySupplier sessionKeySupplier
leafCertificateRetriever x509CertificateRetriever
intermediateCertificateRetrievers []x509CertificateRetriever
securityToken securityToken
authClient *common.BaseClient
mux sync.Mutex
}
func newX509FederationClient(region common.Region, tenancyID string, leafCertificateRetriever x509CertificateRetriever, intermediateCertificateRetrievers []x509CertificateRetriever, modifier dispatcherModifier) (federationClient, error) {
client := &x509FederationClient{
tenancyID: tenancyID,
leafCertificateRetriever: leafCertificateRetriever,
intermediateCertificateRetrievers: intermediateCertificateRetrievers,
}
client.sessionKeySupplier = newSessionKeySupplier()
authClient := newAuthClient(region, client)
var err error
if authClient.HTTPClient, err = modifier.Modify(authClient.HTTPClient); err != nil {
err = fmt.Errorf("failed to modify client: %s", err.Error())
return nil, err
}
client.authClient = authClient
return client, nil
}
func newX509FederationClientWithCerts(region common.Region, tenancyID string, leafCertificate, leafPassphrase, leafPrivateKey []byte, intermediateCertificates [][]byte, modifier dispatcherModifier) (federationClient, error) {
intermediateRetrievers := make([]x509CertificateRetriever, len(intermediateCertificates))
for i, c := range intermediateCertificates {
intermediateRetrievers[i] = &staticCertificateRetriever{Passphrase: []byte(""), CertificatePem: c, PrivateKeyPem: nil}
}
client := &x509FederationClient{
tenancyID: tenancyID,
leafCertificateRetriever: &staticCertificateRetriever{Passphrase: leafPassphrase, CertificatePem: leafCertificate, PrivateKeyPem: leafPrivateKey},
intermediateCertificateRetrievers: intermediateRetrievers,
}
client.sessionKeySupplier = newSessionKeySupplier()
authClient := newAuthClient(region, client)
var err error
if authClient.HTTPClient, err = modifier.Modify(authClient.HTTPClient); err != nil {
err = fmt.Errorf("failed to modify client: %s", err.Error())
return nil, err
}
client.authClient = authClient
return client, nil
}
var (
genericHeaders = []string{"date", "(request-target)"} // "host" is not needed for the federation endpoint. Don't ask me why.
bodyHeaders = []string{"content-length", "content-type", "x-content-sha256"}
)
func newAuthClient(region common.Region, provider common.KeyProvider) *common.BaseClient {
signer := common.RequestSigner(provider, genericHeaders, bodyHeaders)
client := common.DefaultBaseClientWithSigner(signer)
if regionURL, ok := os.LookupEnv("OCI_SDK_AUTH_CLIENT_REGION_URL"); ok {
client.Host = regionURL
} else {
client.Host = region.Endpoint("auth")
}
client.BasePath = "v1/x509"
return &client
}
// For authClient to sign requests to X509 Federation Endpoint
func (c *x509FederationClient) KeyID() (string, error) {
tenancy := c.tenancyID
fingerprint := fingerprint(c.leafCertificateRetriever.Certificate())
return fmt.Sprintf("%s/fed-x509/%s", tenancy, fingerprint), nil
}
// For authClient to sign requests to X509 Federation Endpoint
func (c *x509FederationClient) PrivateRSAKey() (*rsa.PrivateKey, error) {
key := c.leafCertificateRetriever.PrivateKey()
if key == nil {
return nil, fmt.Errorf("can not read private key from leaf certificate. Likely an error in the metadata service")
}
return key, nil
}
func (c *x509FederationClient) PrivateKey() (*rsa.PrivateKey, error) {
c.mux.Lock()
defer c.mux.Unlock()
if err := c.renewSecurityTokenIfNotValid(); err != nil {
return nil, err
}
return c.sessionKeySupplier.PrivateKey(), nil
}
func (c *x509FederationClient) SecurityToken() (token string, err error) {
c.mux.Lock()
defer c.mux.Unlock()
if err = c.renewSecurityTokenIfNotValid(); err != nil {
return "", err
}
return c.securityToken.String(), nil
}
func (c *x509FederationClient) renewSecurityTokenIfNotValid() (err error) {
if c.securityToken == nil || !c.securityToken.Valid() {
if err = c.renewSecurityToken(); err != nil {
return fmt.Errorf("failed to renew security token: %s", err.Error())
}
}
return nil
}
func (c *x509FederationClient) renewSecurityToken() (err error) {
if err = c.sessionKeySupplier.Refresh(); err != nil {
return fmt.Errorf("failed to refresh session key: %s", err.Error())
}
if err = c.leafCertificateRetriever.Refresh(); err != nil {
return fmt.Errorf("failed to refresh leaf certificate: %s", err.Error())
}
updatedTenancyID := extractTenancyIDFromCertificate(c.leafCertificateRetriever.Certificate())
if c.tenancyID != updatedTenancyID {
err = fmt.Errorf("unexpected update of tenancy OCID in the leaf certificate. Previous tenancy: %s, Updated: %s", c.tenancyID, updatedTenancyID)
return
}
for _, retriever := range c.intermediateCertificateRetrievers {
if err = retriever.Refresh(); err != nil {
return fmt.Errorf("failed to refresh intermediate certificate: %s", err.Error())
}
}
common.Logf("Renewing security token at: %v\n", time.Now().Format("15:04:05.000"))
if c.securityToken, err = c.getSecurityToken(); err != nil {
return fmt.Errorf("failed to get security token: %s", err.Error())
}
common.Logf("Security token renewed at: %v\n", time.Now().Format("15:04:05.000"))
return nil
}
func (c *x509FederationClient) getSecurityToken() (securityToken, error) {
request := c.makeX509FederationRequest()
var err error
var httpRequest http.Request
if httpRequest, err = common.MakeDefaultHTTPRequestWithTaggedStruct(http.MethodPost, "", request); err != nil {
return nil, fmt.Errorf("failed to make http request: %s", err.Error())
}
var httpResponse *http.Response
defer common.CloseBodyIfValid(httpResponse)
for retry := 0; retry < 5; retry++ {
if httpResponse, err = c.authClient.Call(context.Background(), &httpRequest); err == nil {
break
}
time.Sleep(250 * time.Microsecond)
}
if err != nil {
return nil, fmt.Errorf("failed to call: %s", err.Error())
}
response := x509FederationResponse{}
if err = common.UnmarshalResponse(httpResponse, &response); err != nil {
return nil, fmt.Errorf("failed to unmarshal the response: %s", err.Error())
}
return newPrincipalToken(response.Token.Token)
}
func (c *x509FederationClient) GetClaim(key string) (interface{}, error) {
c.mux.Lock()
defer c.mux.Unlock()
if err := c.renewSecurityTokenIfNotValid(); err != nil {
return nil, err
}
return c.securityToken.GetClaim(key)
}
type x509FederationRequest struct {
X509FederationDetails `contributesTo:"body"`
}
// X509FederationDetails x509 federation details
type X509FederationDetails struct {
Certificate string `mandatory:"true" json:"certificate,omitempty"`
PublicKey string `mandatory:"true" json:"publicKey,omitempty"`
IntermediateCertificates []string `mandatory:"false" json:"intermediateCertificates,omitempty"`
}
type x509FederationResponse struct {
Token `presentIn:"body"`
}
// Token token
type Token struct {
Token string `mandatory:"true" json:"token,omitempty"`
}
func (c *x509FederationClient) makeX509FederationRequest() *x509FederationRequest {
certificate := c.sanitizeCertificateString(string(c.leafCertificateRetriever.CertificatePemRaw()))
publicKey := c.sanitizeCertificateString(string(c.sessionKeySupplier.PublicKeyPemRaw()))
var intermediateCertificates []string
for _, retriever := range c.intermediateCertificateRetrievers {
intermediateCertificates = append(intermediateCertificates, c.sanitizeCertificateString(string(retriever.CertificatePemRaw())))
}
details := X509FederationDetails{
Certificate: certificate,
PublicKey: publicKey,
IntermediateCertificates: intermediateCertificates,
}
return &x509FederationRequest{details}
}
func (c *x509FederationClient) sanitizeCertificateString(certString string) string {
certString = strings.Replace(certString, "-----BEGIN CERTIFICATE-----", "", -1)
certString = strings.Replace(certString, "-----END CERTIFICATE-----", "", -1)
certString = strings.Replace(certString, "-----BEGIN PUBLIC KEY-----", "", -1)
certString = strings.Replace(certString, "-----END PUBLIC KEY-----", "", -1)
certString = strings.Replace(certString, "\n", "", -1)
return certString
}
// sessionKeySupplier provides an RSA keypair which can be re-generated by calling Refresh().
type sessionKeySupplier interface {
Refresh() error
PrivateKey() *rsa.PrivateKey
PublicKeyPemRaw() []byte
}
//genericKeySupplier implements sessionKeySupplier and provides an arbitrary refresh mechanism
type genericKeySupplier struct {
RefreshFn func() (*rsa.PrivateKey, []byte, error)
privateKey *rsa.PrivateKey
publicKeyPemRaw []byte
}
func (s genericKeySupplier) PrivateKey() *rsa.PrivateKey {
if s.privateKey == nil {
return nil
}
c := *s.privateKey
return &c
}
func (s genericKeySupplier) PublicKeyPemRaw() []byte {
if s.publicKeyPemRaw == nil {
return nil
}
c := make([]byte, len(s.publicKeyPemRaw))
copy(c, s.publicKeyPemRaw)
return c
}
func (s *genericKeySupplier) Refresh() (err error) {
privateKey, publicPem, err := s.RefreshFn()
if err != nil {
return err
}
s.privateKey = privateKey
s.publicKeyPemRaw = publicPem
return nil
}
// create a sessionKeySupplier that reads keys from file every time it refreshes
func newFileBasedKeySessionSupplier(privateKeyPemPath string, passphrasePath *string) (*genericKeySupplier, error) {
return &genericKeySupplier{
RefreshFn: func() (*rsa.PrivateKey, []byte, error) {
var err error
var passContent []byte
if passphrasePath != nil {
if passContent, err = ioutil.ReadFile(*passphrasePath); err != nil {
return nil, nil, fmt.Errorf("can not read passphrase from file: %s, due to %s", *passphrasePath, err.Error())
}
}
var keyPemContent []byte
if keyPemContent, err = ioutil.ReadFile(privateKeyPemPath); err != nil {
return nil, nil, fmt.Errorf("can not read private privateKey pem from file: %s, due to %s", privateKeyPemPath, err.Error())
}
var privateKey *rsa.PrivateKey
if privateKey, err = common.PrivateKeyFromBytesWithPassword(keyPemContent, passContent); err != nil {
return nil, nil, fmt.Errorf("can not create private privateKey from contents of: %s, due to: %s", privateKeyPemPath, err.Error())
}
var publicKeyAsnBytes []byte
if publicKeyAsnBytes, err = x509.MarshalPKIXPublicKey(privateKey.Public()); err != nil {
return nil, nil, fmt.Errorf("failed to marshal the public part of the new keypair: %s", err.Error())
}
publicKeyPemRaw := pem.EncodeToMemory(&pem.Block{
Type: "PUBLIC KEY",
Bytes: publicKeyAsnBytes,
})
return privateKey, publicKeyPemRaw, nil
},
}, nil
}
func newStaticKeySessionSupplier(privateKeyPemContent, passphrase []byte) (*genericKeySupplier, error) {
var err error
var privateKey *rsa.PrivateKey
if privateKey, err = common.PrivateKeyFromBytesWithPassword(privateKeyPemContent, passphrase); err != nil {
return nil, fmt.Errorf("can not create private privateKey, due to: %s", err.Error())
}
var publicKeyAsnBytes []byte
if publicKeyAsnBytes, err = x509.MarshalPKIXPublicKey(privateKey.Public()); err != nil {
return nil, fmt.Errorf("failed to marshal the public part of the new keypair: %s", err.Error())
}
publicKeyPemRaw := pem.EncodeToMemory(&pem.Block{
Type: "PUBLIC KEY",
Bytes: publicKeyAsnBytes,
})
return &genericKeySupplier{
RefreshFn: func() (key *rsa.PrivateKey, bytes []byte, err error) {
return privateKey, publicKeyPemRaw, nil
},
}, nil
}
// inMemorySessionKeySupplier implements sessionKeySupplier to vend an RSA keypair.
// Refresh() generates a new RSA keypair with a random source, and keeps it in memory.
//
// inMemorySessionKeySupplier is not thread-safe.
type inMemorySessionKeySupplier struct {
keySize int
privateKey *rsa.PrivateKey
publicKeyPemRaw []byte
}
// newSessionKeySupplier creates and returns a sessionKeySupplier instance which generates key pairs of size 2048.
func newSessionKeySupplier() sessionKeySupplier {
return &inMemorySessionKeySupplier{keySize: 2048}
}
// Refresh() is failure atomic, i.e., PrivateKey() and PublicKeyPemRaw() would return their previous values
// if Refresh() fails.
func (s *inMemorySessionKeySupplier) Refresh() (err error) {
common.Debugln("Refreshing session key")
var privateKey *rsa.PrivateKey
privateKey, err = rsa.GenerateKey(rand.Reader, s.keySize)
if err != nil {
return fmt.Errorf("failed to generate a new keypair: %s", err)
}
var publicKeyAsnBytes []byte
if publicKeyAsnBytes, err = x509.MarshalPKIXPublicKey(privateKey.Public()); err != nil {
return fmt.Errorf("failed to marshal the public part of the new keypair: %s", err.Error())
}
publicKeyPemRaw := pem.EncodeToMemory(&pem.Block{
Type: "PUBLIC KEY",
Bytes: publicKeyAsnBytes,
})
s.privateKey = privateKey
s.publicKeyPemRaw = publicKeyPemRaw
return nil
}
func (s *inMemorySessionKeySupplier) PrivateKey() *rsa.PrivateKey {
if s.privateKey == nil {
return nil
}
c := *s.privateKey
return &c
}
func (s *inMemorySessionKeySupplier) PublicKeyPemRaw() []byte {
if s.publicKeyPemRaw == nil {
return nil
}
c := make([]byte, len(s.publicKeyPemRaw))
copy(c, s.publicKeyPemRaw)
return c
}
type securityToken interface {
fmt.Stringer
Valid() bool
ClaimHolder
}
type principalToken struct {
tokenString string
jwtToken *jwtToken
}
func newPrincipalToken(tokenString string) (newToken securityToken, err error) {
var jwtToken *jwtToken
if jwtToken, err = parseJwt(tokenString); err != nil {
return nil, fmt.Errorf("failed to parse the token string \"%s\": %s", tokenString, err.Error())
}
return &principalToken{tokenString, jwtToken}, nil
}
func (t *principalToken) String() string {
return t.tokenString
}
func (t *principalToken) Valid() bool {
return !t.jwtToken.expired()
}
var (
// ErrNoSuchClaim is returned when a token does not hold the claim sought
ErrNoSuchClaim = errors.New("no such claim")
)
func (t *principalToken) GetClaim(key string) (interface{}, error) {
if value, ok := t.jwtToken.payload[key]; ok {
return value, nil
}
return nil, ErrNoSuchClaim
}

View file

@ -0,0 +1,83 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
package auth
import (
"crypto/rsa"
"fmt"
"github.com/oracle/oci-go-sdk/v54/common"
)
type instancePrincipalDelegationTokenConfigurationProvider struct {
instancePrincipalKeyProvider instancePrincipalKeyProvider
delegationToken string
region *common.Region
}
//InstancePrincipalDelegationTokenConfigurationProvider returns a configuration for obo token instance principals
func InstancePrincipalDelegationTokenConfigurationProvider(delegationToken *string) (common.ConfigurationProvider, error) {
if delegationToken == nil || len(*delegationToken) == 0 {
return nil, fmt.Errorf("failed to create a delagationTokenConfigurationProvider: token is a mondatory input paras")
}
return newInstancePrincipalDelegationTokenConfigurationProvider(delegationToken, "", nil)
}
//InstancePrincipalDelegationTokenConfigurationProviderForRegion returns a configuration for obo token instance principals with a given region
func InstancePrincipalDelegationTokenConfigurationProviderForRegion(delegationToken *string, region common.Region) (common.ConfigurationProvider, error) {
if delegationToken == nil || len(*delegationToken) == 0 {
return nil, fmt.Errorf("failed to create a delagationTokenConfigurationProvider: token is a mondatory input paras")
}
return newInstancePrincipalDelegationTokenConfigurationProvider(delegationToken, region, nil)
}
func newInstancePrincipalDelegationTokenConfigurationProvider(delegationToken *string, region common.Region, modifier func(common.HTTPRequestDispatcher) (common.HTTPRequestDispatcher,
error)) (common.ConfigurationProvider, error) {
keyProvider, err := newInstancePrincipalKeyProvider(modifier)
if err != nil {
return nil, fmt.Errorf("failed to create a new key provider for instance principal: %s", err.Error())
}
if len(region) > 0 {
return instancePrincipalDelegationTokenConfigurationProvider{*keyProvider, *delegationToken, &region}, err
}
return instancePrincipalDelegationTokenConfigurationProvider{*keyProvider, *delegationToken, nil}, err
}
func (p instancePrincipalDelegationTokenConfigurationProvider) getInstancePrincipalDelegationTokenConfigurationProvider() (instancePrincipalDelegationTokenConfigurationProvider, error) {
return p, nil
}
func (p instancePrincipalDelegationTokenConfigurationProvider) PrivateRSAKey() (*rsa.PrivateKey, error) {
return p.instancePrincipalKeyProvider.PrivateRSAKey()
}
func (p instancePrincipalDelegationTokenConfigurationProvider) KeyID() (string, error) {
return p.instancePrincipalKeyProvider.KeyID()
}
func (p instancePrincipalDelegationTokenConfigurationProvider) TenancyOCID() (string, error) {
return p.instancePrincipalKeyProvider.TenancyOCID()
}
func (p instancePrincipalDelegationTokenConfigurationProvider) UserOCID() (string, error) {
return "", nil
}
func (p instancePrincipalDelegationTokenConfigurationProvider) KeyFingerprint() (string, error) {
return "", nil
}
func (p instancePrincipalDelegationTokenConfigurationProvider) Region() (string, error) {
if p.region == nil {
region := p.instancePrincipalKeyProvider.RegionForFederationClient()
common.Debugf("Region in instance principal delegation token configuration provider is nil. Returning federation clients region: %s", region)
return string(region), nil
}
return string(*p.region), nil
}
func (p instancePrincipalDelegationTokenConfigurationProvider) AuthType() (common.AuthConfig, error) {
token := p.delegationToken
return common.AuthConfig{common.InstancePrincipalDelegationToken, false, &token}, nil
}

View file

@ -0,0 +1,146 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
package auth
import (
"bytes"
"crypto/rsa"
"fmt"
"net/http"
"strings"
"time"
"github.com/oracle/oci-go-sdk/v54/common"
)
const (
metadataBaseURL = `http://169.254.169.254/opc/v2`
metadataFallbackURL = `http://169.254.169.254/opc/v1`
regionPath = `/instance/region`
leafCertificatePath = `/identity/cert.pem`
leafCertificateKeyPath = `/identity/key.pem`
intermediateCertificatePath = `/identity/intermediate.pem`
leafCertificateKeyPassphrase = `` // No passphrase for the private key for Compute instances
intermediateCertificateKeyURL = ``
intermediateCertificateKeyPassphrase = `` // No passphrase for the private key for Compute instances
)
var (
regionURL, leafCertificateURL, leafCertificateKeyURL, intermediateCertificateURL string
)
// instancePrincipalKeyProvider implements KeyProvider to provide a key ID and its corresponding private key
// for an instance principal by getting a security token via x509FederationClient.
//
// The region name of the endpoint for x509FederationClient is obtained from the metadata service on the compute
// instance.
type instancePrincipalKeyProvider struct {
Region common.Region
FederationClient federationClient
TenancyID string
}
// newInstancePrincipalKeyProvider creates and returns an instancePrincipalKeyProvider instance based on
// x509FederationClient.
//
// NOTE: There is a race condition between PrivateRSAKey() and KeyID(). These two pieces are tightly coupled; KeyID
// includes a security token obtained from Auth service by giving a public key which is paired with PrivateRSAKey.
// The x509FederationClient caches the security token in memory until it is expired. Thus, even if a client obtains a
// KeyID that is not expired at the moment, the PrivateRSAKey that the client acquires at a next moment could be
// invalid because the KeyID could be already expired.
func newInstancePrincipalKeyProvider(modifier func(common.HTTPRequestDispatcher) (common.HTTPRequestDispatcher, error)) (provider *instancePrincipalKeyProvider, err error) {
updateX509CertRetrieverURLParas(metadataBaseURL)
clientModifier := newDispatcherModifier(modifier)
client, err := clientModifier.Modify(&http.Client{})
if err != nil {
err = fmt.Errorf("failed to modify client: %s", err.Error())
return nil, err
}
var region common.Region
if region, err = getRegionForFederationClient(client, regionURL); err != nil {
err = fmt.Errorf("failed to get the region name from %s: %s", regionURL, err.Error())
common.Logf("%v\n", err)
return nil, err
}
leafCertificateRetriever := newURLBasedX509CertificateRetriever(client,
leafCertificateURL, leafCertificateKeyURL, leafCertificateKeyPassphrase)
intermediateCertificateRetrievers := []x509CertificateRetriever{
newURLBasedX509CertificateRetriever(
client, intermediateCertificateURL, intermediateCertificateKeyURL,
intermediateCertificateKeyPassphrase),
}
if err = leafCertificateRetriever.Refresh(); err != nil {
err = fmt.Errorf("failed to refresh the leaf certificate: %s", err.Error())
return nil, err
}
tenancyID := extractTenancyIDFromCertificate(leafCertificateRetriever.Certificate())
federationClient, err := newX509FederationClient(region, tenancyID, leafCertificateRetriever, intermediateCertificateRetrievers, *clientModifier)
if err != nil {
err = fmt.Errorf("failed to create federation client: %s", err.Error())
return nil, err
}
provider = &instancePrincipalKeyProvider{FederationClient: federationClient, TenancyID: tenancyID, Region: region}
return
}
func getRegionForFederationClient(dispatcher common.HTTPRequestDispatcher, url string) (r common.Region, err error) {
var body bytes.Buffer
var statusCode int
MaxRetriesFederationClient := 3
for currTry := 0; currTry < MaxRetriesFederationClient; currTry++ {
body, statusCode, err = httpGet(dispatcher, url)
if err == nil && statusCode == 200 {
return common.StringToRegion(body.String()), nil
}
common.Logf("Error in getting region from url: %s, Status code: %v, Error: %s", url, statusCode, err.Error())
if statusCode == 404 && strings.Compare(url, metadataBaseURL+regionPath) == 0 {
common.Logf("Falling back to http://169.254.169.254/opc/v1 to try again...")
updateX509CertRetrieverURLParas(metadataFallbackURL)
url = regionURL
}
time.Sleep(1 * time.Second)
}
return
}
func updateX509CertRetrieverURLParas(baseURL string) {
regionURL = baseURL + regionPath
leafCertificateURL = baseURL + leafCertificatePath
leafCertificateKeyURL = baseURL + leafCertificateKeyPath
intermediateCertificateURL = baseURL + intermediateCertificatePath
}
func (p *instancePrincipalKeyProvider) RegionForFederationClient() common.Region {
return p.Region
}
func (p *instancePrincipalKeyProvider) PrivateRSAKey() (privateKey *rsa.PrivateKey, err error) {
if privateKey, err = p.FederationClient.PrivateKey(); err != nil {
err = fmt.Errorf("failed to get private key: %s", err.Error())
return nil, err
}
return privateKey, nil
}
func (p *instancePrincipalKeyProvider) KeyID() (string, error) {
var securityToken string
var err error
if securityToken, err = p.FederationClient.SecurityToken(); err != nil {
return "", fmt.Errorf("failed to get security token: %s", err.Error())
}
return fmt.Sprintf("ST$%s", securityToken), nil
}
func (p *instancePrincipalKeyProvider) TenancyOCID() (string, error) {
return p.TenancyID, nil
}

View file

@ -0,0 +1,70 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
package auth
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"github.com/oracle/oci-go-sdk/v54/common"
"strings"
"time"
)
type jwtToken struct {
raw string
header map[string]interface{}
payload map[string]interface{}
}
const bufferTimeBeforeTokenExpiration = 5 * time.Minute
func (t *jwtToken) expired() bool {
exp := int64(t.payload["exp"].(float64))
expTime := time.Unix(exp, 0)
expired := exp <= time.Now().Unix()+int64(bufferTimeBeforeTokenExpiration.Seconds())
if expired {
common.Debugf("Token expires at: %v, currently expired due to bufferTime: %v", expTime.Format("15:04:05.000"), expired)
}
return expired
}
func parseJwt(tokenString string) (*jwtToken, error) {
parts := strings.Split(tokenString, ".")
if len(parts) != 3 {
return nil, fmt.Errorf("the given token string contains an invalid number of parts")
}
token := &jwtToken{raw: tokenString}
var err error
// Parse Header part
var headerBytes []byte
if headerBytes, err = decodePart(parts[0]); err != nil {
return nil, fmt.Errorf("failed to decode the header bytes: %s", err.Error())
}
if err = json.Unmarshal(headerBytes, &token.header); err != nil {
return nil, err
}
// Parse Payload part
var payloadBytes []byte
if payloadBytes, err = decodePart(parts[1]); err != nil {
return nil, fmt.Errorf("failed to decode the payload bytes: %s", err.Error())
}
decoder := json.NewDecoder(bytes.NewBuffer(payloadBytes))
if err = decoder.Decode(&token.payload); err != nil {
return nil, fmt.Errorf("failed to decode the payload json: %s", err.Error())
}
return token, nil
}
func decodePart(partString string) ([]byte, error) {
if l := len(partString) % 4; 0 < l {
partString += strings.Repeat("=", 4-l)
}
return base64.URLEncoding.DecodeString(partString)
}

View file

@ -0,0 +1,231 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
package auth
import (
"crypto/rsa"
"errors"
"fmt"
"github.com/oracle/oci-go-sdk/v54/common"
"os"
"path"
)
const (
//ResourcePrincipalVersion2_2 is a supported version for resource principals
ResourcePrincipalVersion2_2 = "2.2"
//ResourcePrincipalVersionEnvVar environment var name for version
ResourcePrincipalVersionEnvVar = "OCI_RESOURCE_PRINCIPAL_VERSION"
//ResourcePrincipalRPSTEnvVar environment var name holding the token or a path to the token
ResourcePrincipalRPSTEnvVar = "OCI_RESOURCE_PRINCIPAL_RPST"
//ResourcePrincipalPrivatePEMEnvVar environment var holding a rsa private key in pem format or a path to one
ResourcePrincipalPrivatePEMEnvVar = "OCI_RESOURCE_PRINCIPAL_PRIVATE_PEM"
//ResourcePrincipalPrivatePEMPassphraseEnvVar environment var holding the passphrase to a key or a path to one
ResourcePrincipalPrivatePEMPassphraseEnvVar = "OCI_RESOURCE_PRINCIPAL_PRIVATE_PEM_PASSPHRASE"
//ResourcePrincipalRegionEnvVar environment variable holding a region
ResourcePrincipalRegionEnvVar = "OCI_RESOURCE_PRINCIPAL_REGION"
//ResourcePrincipalVersion1_1 is a supported version for resource principals
ResourcePrincipalVersion1_1 = "1.1"
//ResourcePrincipalSessionTokenEndpoint endpoint for retrieving the Resource Principal Session Token
ResourcePrincipalSessionTokenEndpoint = "OCI_RESOURCE_PRINCIPAL_RPST_ENDPOINT"
//ResourcePrincipalTokenEndpoint endpoint for retrieving the Resource Principal Token
ResourcePrincipalTokenEndpoint = "OCI_RESOURCE_PRINCIPAL_RPT_ENDPOINT"
// TenancyOCIDClaimKey is the key used to look up the resource tenancy in an RPST
TenancyOCIDClaimKey = "res_tenant"
// CompartmentOCIDClaimKey is the key used to look up the resource compartment in an RPST
CompartmentOCIDClaimKey = "res_compartment"
)
// ConfigurationProviderWithClaimAccess mixes in a method to access the claims held on the underlying security token
type ConfigurationProviderWithClaimAccess interface {
common.ConfigurationProvider
ClaimHolder
}
// ResourcePrincipalConfigurationProvider returns a resource principal configuration provider using well known
// environment variables to look up token information. The environment variables can either paths or contain the material value
// of the keys. However in the case of the keys and tokens paths and values can not be mixed
func ResourcePrincipalConfigurationProvider() (ConfigurationProviderWithClaimAccess, error) {
var version string
var ok bool
if version, ok = os.LookupEnv(ResourcePrincipalVersionEnvVar); !ok {
return nil, fmt.Errorf("can not create resource principal, environment variable: %s, not present", ResourcePrincipalVersionEnvVar)
}
switch version {
case ResourcePrincipalVersion2_2:
rpst := requireEnv(ResourcePrincipalRPSTEnvVar)
if rpst == nil {
return nil, fmt.Errorf("can not create resource principal, environment variable: %s, not present", ResourcePrincipalRPSTEnvVar)
}
private := requireEnv(ResourcePrincipalPrivatePEMEnvVar)
if private == nil {
return nil, fmt.Errorf("can not create resource principal, environment variable: %s, not present", ResourcePrincipalPrivatePEMEnvVar)
}
passphrase := requireEnv(ResourcePrincipalPrivatePEMPassphraseEnvVar)
region := requireEnv(ResourcePrincipalRegionEnvVar)
if region == nil {
return nil, fmt.Errorf("can not create resource principal, environment variable: %s, not present", ResourcePrincipalRegionEnvVar)
}
return newResourcePrincipalKeyProvider22(
*rpst, *private, passphrase, *region)
case ResourcePrincipalVersion1_1:
return newResourcePrincipalKeyProvider11(DefaultRptPathProvider{})
default:
return nil, fmt.Errorf("can not create resource principal, environment variable: %s, must be valid", ResourcePrincipalVersionEnvVar)
}
}
// ResourcePrincipalConfigurationProviderWithPathProvider returns a resource principal configuration provider using path provider.
func ResourcePrincipalConfigurationProviderWithPathProvider(pathProvider PathProvider) (ConfigurationProviderWithClaimAccess, error) {
var version string
var ok bool
if version, ok = os.LookupEnv(ResourcePrincipalVersionEnvVar); !ok {
return nil, fmt.Errorf("can not create resource principal, environment variable: %s, not present", ResourcePrincipalVersionEnvVar)
} else if version != ResourcePrincipalVersion1_1 {
return nil, fmt.Errorf("can not create resource principal, environment variable: %s, must be %s", ResourcePrincipalVersionEnvVar, ResourcePrincipalVersion1_1)
}
return newResourcePrincipalKeyProvider11(pathProvider)
}
func newResourcePrincipalKeyProvider11(pathProvider PathProvider) (ConfigurationProviderWithClaimAccess, error) {
rptEndpoint := requireEnv(ResourcePrincipalTokenEndpoint)
if rptEndpoint == nil {
return nil, fmt.Errorf("can not create resource principal, environment variable: %s, not present", ResourcePrincipalTokenEndpoint)
}
rptPath, err := pathProvider.Path()
if err != nil {
return nil, fmt.Errorf("can not create resource principal, due to: %s ", err.Error())
}
resourceID, err := pathProvider.ResourceID()
if err != nil {
return nil, fmt.Errorf("can not create resource principal, due to: %s ", err.Error())
}
rp, err := resourcePrincipalConfigurationProviderV1(*rptEndpoint+*rptPath, *resourceID)
if err != nil {
return nil, fmt.Errorf("can not create resource principal, due to: %s ", err.Error())
}
return rp, nil
}
func requireEnv(key string) *string {
if val, ok := os.LookupEnv(key); ok {
return &val
}
return nil
}
// resourcePrincipalKeyProvider22 is key provider that reads from specified the specified environment variables
// the environment variables can host the material keys/passphrases or they can be paths to files that need to be read
type resourcePrincipalKeyProvider struct {
FederationClient federationClient
KeyProviderRegion common.Region
}
func newResourcePrincipalKeyProvider22(sessionTokenLocation, privatePemLocation string,
passphraseLocation *string, region string) (*resourcePrincipalKeyProvider, error) {
//Check both the the passphrase and the key are paths
if passphraseLocation != nil && (!isPath(privatePemLocation) && isPath(*passphraseLocation) ||
isPath(privatePemLocation) && !isPath(*passphraseLocation)) {
return nil, fmt.Errorf("cant not create resource principal: both key and passphrase need to be path or none needs to be path")
}
var supplier sessionKeySupplier
var err error
//File based case
if isPath(privatePemLocation) {
supplier, err = newFileBasedKeySessionSupplier(privatePemLocation, passphraseLocation)
if err != nil {
return nil, fmt.Errorf("can not create resource principal, due to: %s ", err.Error())
}
} else {
//else the content is in the env vars
var passphrase []byte
if passphraseLocation != nil {
passphrase = []byte(*passphraseLocation)
}
supplier, err = newStaticKeySessionSupplier([]byte(privatePemLocation), passphrase)
if err != nil {
return nil, fmt.Errorf("can not create resource principal, due to: %s ", err.Error())
}
}
var fd federationClient
if isPath(sessionTokenLocation) {
fd, _ = newFileBasedFederationClient(sessionTokenLocation, supplier)
} else {
fd, err = newStaticFederationClient(sessionTokenLocation, supplier)
if err != nil {
return nil, fmt.Errorf("can not create resource principal, due to: %s ", err.Error())
}
}
rs := resourcePrincipalKeyProvider{
FederationClient: fd,
KeyProviderRegion: common.StringToRegion(region),
}
return &rs, nil
}
func (p *resourcePrincipalKeyProvider) PrivateRSAKey() (privateKey *rsa.PrivateKey, err error) {
if privateKey, err = p.FederationClient.PrivateKey(); err != nil {
err = fmt.Errorf("failed to get private key: %s", err.Error())
return nil, err
}
return privateKey, nil
}
func (p *resourcePrincipalKeyProvider) KeyID() (string, error) {
var securityToken string
var err error
if securityToken, err = p.FederationClient.SecurityToken(); err != nil {
return "", fmt.Errorf("failed to get security token: %s", err.Error())
}
return fmt.Sprintf("ST$%s", securityToken), nil
}
func (p *resourcePrincipalKeyProvider) Region() (string, error) {
return string(p.KeyProviderRegion), nil
}
var (
// ErrNonStringClaim is returned if the token has a claim for a key, but it's not a string value
ErrNonStringClaim = errors.New("claim does not have a string value")
)
func (p *resourcePrincipalKeyProvider) TenancyOCID() (string, error) {
if claim, err := p.GetClaim(TenancyOCIDClaimKey); err != nil {
return "", err
} else if tenancy, ok := claim.(string); ok {
return tenancy, nil
} else {
return "", ErrNonStringClaim
}
}
func (p *resourcePrincipalKeyProvider) GetClaim(claim string) (interface{}, error) {
return p.FederationClient.GetClaim(claim)
}
func (p *resourcePrincipalKeyProvider) KeyFingerprint() (string, error) {
return "", nil
}
func (p *resourcePrincipalKeyProvider) UserOCID() (string, error) {
return "", nil
}
func (p *resourcePrincipalKeyProvider) AuthType() (common.AuthConfig, error) {
return common.AuthConfig{common.UnknownAuthenticationType, false, nil}, fmt.Errorf("unsupported, keep the interface")
}
// By contract for the the content of a resource principal to be considered path, it needs to be
// an absolute path.
func isPath(str string) bool {
return path.IsAbs(str)
}

View file

@ -0,0 +1,138 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
package auth
import (
"fmt"
"io/ioutil"
"net/http"
)
const (
imdsPathTemplate = "/20180711/resourcePrincipalToken/{id}"
instanceIDURL = `http://169.254.169.254/opc/v2/instance/id`
//ResourcePrincipalTokenPath path for retrieving the Resource Principal Token
ResourcePrincipalTokenPath = "OCI_RESOURCE_PRINCIPAL_RPT_PATH"
//ResourceID OCID for the resource for Resource Principal
ResourceID = "OCI_RESOURCE_PRINCIPAL_RPT_ID"
)
// PathProvider is an interface that returns path and resource ID
type PathProvider interface {
Path() (*string, error)
ResourceID() (*string, error)
}
// StringRptPathProvider is a simple path provider that takes a string and returns it
type StringRptPathProvider struct {
path string
resourceID string
}
// Path returns the resource principal token path
func (pp StringRptPathProvider) Path() (*string, error) {
return &pp.path, nil
}
// ResourceID returns the resource associated with the resource principal
func (pp StringRptPathProvider) ResourceID() (*string, error) {
return &pp.resourceID, nil
}
// ImdsRptPathProvider sets the path from a default value and the resource ID from instance metadata
type ImdsRptPathProvider struct{}
// Path returns the resource principal token path
func (pp ImdsRptPathProvider) Path() (*string, error) {
path := imdsPathTemplate
return &path, nil
}
// ResourceID returns the resource associated with the resource principal
func (pp ImdsRptPathProvider) ResourceID() (*string, error) {
instanceID, err := getInstanceIDFromMetadata()
return &instanceID, err
}
// EnvRptPathProvider sets the path and resource ID from environment variables
type EnvRptPathProvider struct{}
// Path returns the resource principal token path
func (pp EnvRptPathProvider) Path() (*string, error) {
path := requireEnv(ResourcePrincipalTokenPath)
if path == nil {
return nil, fmt.Errorf("missing %s env var", ResourcePrincipalTokenPath)
}
return path, nil
}
// ResourceID returns the resource associated with the resource principal
func (pp EnvRptPathProvider) ResourceID() (*string, error) {
rpID := requireEnv(ResourceID)
if rpID == nil {
return nil, fmt.Errorf("missing %s env var", ResourceID)
}
return rpID, nil
}
//DefaultRptPathProvider path provider makes sure the behavior happens with the correct fallback.
//
//For the path,
//Use the contents of the OCI_RESOURCE_PRINCIPAL_RPT_PATH environment variable, if set.
//Otherwise, use the current path: "/20180711/resourcePrincipalToken/{id}"
//
//For the resource id,
//Use the contents of the OCI_RESOURCE_PRINCIPAL_RPT_ID environment variable, if set.
//Otherwise, use IMDS to get the instance id
//
//This path provider is used when the caller doesn't provide a specific path provider to the resource principals signer
type DefaultRptPathProvider struct {
path string
resourceID string
}
// Path returns the resource principal token path
func (pp DefaultRptPathProvider) Path() (*string, error) {
path := requireEnv(ResourcePrincipalTokenPath)
if path == nil {
rpPath := imdsPathTemplate
return &rpPath, nil
}
return path, nil
}
// ResourceID returns the resource associated with the resource principal
func (pp DefaultRptPathProvider) ResourceID() (*string, error) {
rpID := requireEnv(ResourceID)
if rpID == nil {
instanceID, err := getInstanceIDFromMetadata()
if err != nil {
return nil, err
}
return &instanceID, nil
}
return rpID, nil
}
func getInstanceIDFromMetadata() (instanceID string, err error) {
client := &http.Client{}
req, err := http.NewRequest("GET", instanceIDURL, nil)
if err != nil {
return "", err
}
req.Header.Set("Authorization", "Bearer Oracle")
resp, err := client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
bodyString := string(bodyBytes)
return bodyString, nil
}

View file

@ -0,0 +1,373 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
package auth
import (
"context"
"crypto/rsa"
"fmt"
"github.com/oracle/oci-go-sdk/v54/common"
"net/http"
"net/url"
"sync"
"time"
)
// resourcePrincipalFederationClient is the client used to to talk acquire resource principals
// No auth client, leaf or intermediate retrievers. We use certificates retrieved by instance principals to sign the operations of
// resource principals
type resourcePrincipalFederationClient struct {
tenancyID string
instanceID string
sessionKeySupplier sessionKeySupplier
mux sync.Mutex
securityToken securityToken
path string
//instancePrincipalKeyProvider the instance Principal Key container
instancePrincipalKeyProvider instancePrincipalKeyProvider
//ResourcePrincipalTargetServiceClient client that calls the target service to acquire a resource principal token
ResourcePrincipalTargetServiceClient common.BaseClient
//ResourcePrincipalSessionTokenClient. The client used to communicate with identity to exchange a resource principal for
// resource principal session token
ResourcePrincipalSessionTokenClient common.BaseClient
}
type resourcePrincipalTokenRequest struct {
InstanceID string `contributesTo:"path" name:"id"`
}
type resourcePrincipalTokenResponse struct {
Body struct {
ResourcePrincipalToken string `json:"resourcePrincipalToken"`
ServicePrincipalSessionToken string `json:"servicePrincipalSessionToken"`
} `presentIn:"body"`
}
type resourcePrincipalSessionTokenRequestBody struct {
ResourcePrincipalToken string `json:"resourcePrincipalToken,omitempty"`
ServicePrincipalSessionToken string `json:"servicePrincipalSessionToken,omitempty"`
SessionPublicKey string `json:"sessionPublicKey,omitempty"`
}
type resourcePrincipalSessionTokenRequest struct {
Body resourcePrincipalSessionTokenRequestBody `contributesTo:"body"`
}
//acquireResourcePrincipalToken acquires the resource principal from the target service
func (c *resourcePrincipalFederationClient) acquireResourcePrincipalToken() (tokenResponse resourcePrincipalTokenResponse, err error) {
rpServiceClient := c.ResourcePrincipalTargetServiceClient
//Set the signer of this client to be the instance principal provider
rpServiceClient.Signer = common.DefaultRequestSigner(&c.instancePrincipalKeyProvider)
//Create a request with the instanceId
request, err := common.MakeDefaultHTTPRequestWithTaggedStruct(http.MethodGet, c.path, resourcePrincipalTokenRequest{InstanceID: c.instanceID})
if err != nil {
return
}
//Call the target service
response, err := rpServiceClient.Call(context.Background(), &request)
if err != nil {
return
}
defer common.CloseBodyIfValid(response)
tokenResponse = resourcePrincipalTokenResponse{}
err = common.UnmarshalResponse(response, &tokenResponse)
return
}
//exchangeToken exchanges a resource principal token from the target service with a session token from identity
func (c *resourcePrincipalFederationClient) exchangeToken(publicKeyBase64 string, tokenResponse resourcePrincipalTokenResponse) (sessionToken string, err error) {
rpServiceClient := c.ResourcePrincipalSessionTokenClient
//Set the signer of this client to be the instance principal provider
rpServiceClient.Signer = common.DefaultRequestSigner(&c.instancePrincipalKeyProvider)
// Call identity service to get resource principal session token
sessionTokenReq := resourcePrincipalSessionTokenRequest{
resourcePrincipalSessionTokenRequestBody{
ServicePrincipalSessionToken: tokenResponse.Body.ServicePrincipalSessionToken,
ResourcePrincipalToken: tokenResponse.Body.ResourcePrincipalToken,
SessionPublicKey: publicKeyBase64,
},
}
sessionTokenHTTPReq, err := common.MakeDefaultHTTPRequestWithTaggedStruct(http.MethodPost,
"", sessionTokenReq)
if err != nil {
return
}
sessionTokenHTTPRes, err := rpServiceClient.Call(context.Background(), &sessionTokenHTTPReq)
if err != nil {
return
}
defer common.CloseBodyIfValid(sessionTokenHTTPRes)
sessionTokenRes := x509FederationResponse{}
err = common.UnmarshalResponse(sessionTokenHTTPRes, &sessionTokenRes)
if err != nil {
return
}
sessionToken = sessionTokenRes.Token.Token
return
}
//getSecurityToken makes the appropiate calls to acquire a resource principal security token
func (c *resourcePrincipalFederationClient) getSecurityToken() (securityToken, error) {
var err error
ipFederationClient := c.instancePrincipalKeyProvider.FederationClient
common.Debugf("Refreshing instance principal token")
//Refresh instance principal token
if refreshable, ok := ipFederationClient.(*x509FederationClient); ok {
err = refreshable.renewSecurityTokenIfNotValid()
if err != nil {
return nil, err
}
}
//Acquire resource principal token from target service
common.Debugf("Acquiring resource principal token from target service")
tokenResponse, err := c.acquireResourcePrincipalToken()
if err != nil {
return nil, err
}
//Read the public key from the session supplier.
pem := c.sessionKeySupplier.PublicKeyPemRaw()
pemSanitized := sanitizeCertificateString(string(pem))
//Exchange resource principal token for session token from identity
common.Debugf("Exchanging resource principal token for resource principal session token")
sessionToken, err := c.exchangeToken(pemSanitized, tokenResponse)
if err != nil {
return nil, err
}
return newPrincipalToken(sessionToken) // should be a resource principal token
}
func (c *resourcePrincipalFederationClient) renewSecurityToken() (err error) {
if err = c.sessionKeySupplier.Refresh(); err != nil {
return fmt.Errorf("failed to refresh session key: %s", err.Error())
}
common.Logf("Renewing resource principal security token at: %v\n", time.Now().Format("15:04:05.000"))
if c.securityToken, err = c.getSecurityToken(); err != nil {
return fmt.Errorf("failed to get security token: %s", err.Error())
}
common.Logf("Resource principal security token renewed at: %v\n", time.Now().Format("15:04:05.000"))
return nil
}
//ResourcePrincipal Key provider in charge of resource principal acquiring tokens
type resourcePrincipalKeyProviderV1 struct {
ResourcePrincipalClient resourcePrincipalFederationClient
}
func (c *resourcePrincipalFederationClient) renewSecurityTokenIfNotValid() (err error) {
if c.securityToken == nil || !c.securityToken.Valid() {
if err = c.renewSecurityToken(); err != nil {
return fmt.Errorf("failed to renew resource prinicipal security token: %s", err.Error())
}
}
return nil
}
func (c *resourcePrincipalFederationClient) PrivateKey() (*rsa.PrivateKey, error) {
c.mux.Lock()
defer c.mux.Unlock()
if err := c.renewSecurityTokenIfNotValid(); err != nil {
return nil, err
}
return c.sessionKeySupplier.PrivateKey(), nil
}
func (c *resourcePrincipalFederationClient) SecurityToken() (token string, err error) {
c.mux.Lock()
defer c.mux.Unlock()
if err = c.renewSecurityTokenIfNotValid(); err != nil {
return "", err
}
return c.securityToken.String(), nil
}
func (p *resourcePrincipalConfigurationProvider) PrivateRSAKey() (privateKey *rsa.PrivateKey, err error) {
if privateKey, err = p.keyProvider.ResourcePrincipalClient.PrivateKey(); err != nil {
err = fmt.Errorf("failed to get resource principal private key: %s", err.Error())
return nil, err
}
return privateKey, nil
}
func (p *resourcePrincipalConfigurationProvider) KeyID() (string, error) {
var securityToken string
var err error
if securityToken, err = p.keyProvider.ResourcePrincipalClient.SecurityToken(); err != nil {
return "", fmt.Errorf("failed to get resource principal security token: %s", err.Error())
}
return fmt.Sprintf("ST$%s", securityToken), nil
}
func (p *resourcePrincipalConfigurationProvider) TenancyOCID() (string, error) {
return p.keyProvider.ResourcePrincipalClient.instancePrincipalKeyProvider.TenancyOCID()
}
// todo what is this
func (p *resourcePrincipalConfigurationProvider) GetClaim(key string) (interface{}, error) {
return nil, nil
}
//Resource Principals
type resourcePrincipalConfigurationProvider struct {
keyProvider resourcePrincipalKeyProviderV1
region *common.Region
}
func newResourcePrincipalKeyProvider(ipKeyProvider instancePrincipalKeyProvider, rpTokenTargetServiceClient, rpSessionTokenClient common.BaseClient, instanceID, path string) (keyProvider resourcePrincipalKeyProviderV1, err error) {
rpFedClient := resourcePrincipalFederationClient{}
rpFedClient.tenancyID = ipKeyProvider.TenancyID
rpFedClient.instanceID = instanceID
rpFedClient.sessionKeySupplier = newSessionKeySupplier()
rpFedClient.ResourcePrincipalTargetServiceClient = rpTokenTargetServiceClient
rpFedClient.ResourcePrincipalSessionTokenClient = rpSessionTokenClient
rpFedClient.instancePrincipalKeyProvider = ipKeyProvider
rpFedClient.path = path
keyProvider = resourcePrincipalKeyProviderV1{ResourcePrincipalClient: rpFedClient}
return
}
func (p *resourcePrincipalConfigurationProvider) AuthType() (common.AuthConfig, error) {
return common.AuthConfig{common.UnknownAuthenticationType, false, nil},
fmt.Errorf("unsupported, keep the interface")
}
func (p resourcePrincipalConfigurationProvider) UserOCID() (string, error) {
return "", nil
}
func (p resourcePrincipalConfigurationProvider) KeyFingerprint() (string, error) {
return "", nil
}
func (p resourcePrincipalConfigurationProvider) Region() (string, error) {
if p.region == nil {
region := p.keyProvider.ResourcePrincipalClient.instancePrincipalKeyProvider.RegionForFederationClient()
common.Debugf("Region in resource principal configuration provider is nil. Returning instance principal federation clients region: %s", region)
return string(region), nil
}
return string(*p.region), nil
}
// resourcePrincipalConfigurationProviderForInstanceWithClients returns a configuration for instance principals
// resourcePrincipalTargetServiceTokenClient and resourcePrincipalSessionTokenClient are clients that at last need to have
// their base path and host properly set for their respective services. Additionally the clients can be further customized
// to provide mocking or any other customization for the requests/responses
func resourcePrincipalConfigurationProviderForInstanceWithClients(instancePrincipalProvider common.ConfigurationProvider,
resourcePrincipalTargetServiceTokenClient, resourcePrincipalSessionTokenClient common.BaseClient, instanceID, path string) (*resourcePrincipalConfigurationProvider, error) {
var ok bool
var ip instancePrincipalConfigurationProvider
if ip, ok = instancePrincipalProvider.(instancePrincipalConfigurationProvider); !ok {
return nil, fmt.Errorf("instancePrincipalConfigurationProvider needs to be of type vald Instance Principal Configuration Provider")
}
keyProvider, err := newResourcePrincipalKeyProvider(ip.keyProvider, resourcePrincipalTargetServiceTokenClient, resourcePrincipalSessionTokenClient, instanceID, path)
if err != nil {
return nil, err
}
provider := &resourcePrincipalConfigurationProvider{
region: nil,
keyProvider: keyProvider,
}
return provider, nil
}
const identityResourcePrincipalSessionTokenPath = "/v1/resourcePrincipalSessionToken"
// resourcePrincipalConfigurationProviderForInstanceWithInterceptor creates a resource principal configuration provider with
// a interceptor used to customize the call going to the resource principal token request to the target service
// for a given instance ID
func resourcePrincipalConfigurationProviderForInstanceWithInterceptor(instancePrincipalProvider common.ConfigurationProvider, resourcePrincipalTokenEndpoint, instanceID string, interceptor common.RequestInterceptor) (provider *resourcePrincipalConfigurationProvider, err error) {
//Build the target service client
rpTargetServiceClient, err := common.NewClientWithConfig(instancePrincipalProvider)
if err != nil {
return
}
rpTokenURL, err := url.Parse(resourcePrincipalTokenEndpoint)
if err != nil {
return
}
rpTargetServiceClient.Host = rpTokenURL.Scheme + "://" + rpTokenURL.Host
rpTargetServiceClient.Interceptor = interceptor
var path string
if rpTokenURL.Path != "" {
path = rpTokenURL.Path
} else {
path = identityResourcePrincipalSessionTokenPath
}
//Build the identity client for token service
rpTokenSessionClient, err := common.NewClientWithConfig(instancePrincipalProvider)
if err != nil {
return
}
// Set RPST endpoint if passed in from env var, otherwise create it from region
resourcePrincipalSessionTokenEndpoint := requireEnv(ResourcePrincipalSessionTokenEndpoint)
if resourcePrincipalSessionTokenEndpoint != nil {
rpSessionTokenURL, err := url.Parse(*resourcePrincipalSessionTokenEndpoint)
if err != nil {
return nil, err
}
rpTokenSessionClient.Host = rpSessionTokenURL.Scheme + "://" + rpSessionTokenURL.Host
} else {
regionStr, err := instancePrincipalProvider.Region()
if err != nil {
return nil, fmt.Errorf("missing RPST env var and cannot determine region: %v", err)
}
region := common.StringToRegion(regionStr)
rpTokenSessionClient.Host = fmt.Sprintf("https://%s", region.Endpoint("auth"))
}
rpTokenSessionClient.BasePath = identityResourcePrincipalSessionTokenPath
return resourcePrincipalConfigurationProviderForInstanceWithClients(instancePrincipalProvider, rpTargetServiceClient, rpTokenSessionClient, instanceID, path)
}
// ResourcePrincipalConfigurationProviderWithInterceptor creates a resource principal configuration provider with endpoints
// a interceptor used to customize the call going to the resource principal token request to the target service
// see https://godoc.org/github.com/oracle/oci-go-sdk/common#RequestInterceptor
func ResourcePrincipalConfigurationProviderWithInterceptor(instancePrincipalProvider common.ConfigurationProvider,
resourcePrincipalTokenEndpoint, resourcePrincipalSessionTokenEndpoint string,
interceptor common.RequestInterceptor) (common.ConfigurationProvider, error) {
return resourcePrincipalConfigurationProviderForInstanceWithInterceptor(instancePrincipalProvider, resourcePrincipalTokenEndpoint, "", interceptor)
}
// resourcePrincipalConfigurationProviderV1 creates a resource principal configuration provider with
// endpoints for both resource principal token and resource principal token session
func resourcePrincipalConfigurationProviderV1(resourcePrincipalTokenEndpoint, resourceID string) (*resourcePrincipalConfigurationProvider, error) {
instancePrincipalProvider, err := InstancePrincipalConfigurationProvider()
if err != nil {
return nil, err
}
return resourcePrincipalConfigurationProviderForInstanceWithInterceptor(instancePrincipalProvider, resourcePrincipalTokenEndpoint, resourceID, nil)
}

View file

@ -0,0 +1,97 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
package auth
import (
"bytes"
"crypto/sha1"
"crypto/x509"
"fmt"
"github.com/oracle/oci-go-sdk/v54/common"
"net/http"
"net/http/httputil"
"strings"
)
// httpGet makes a simple HTTP GET request to the given URL, expecting only "200 OK" status code.
// This is basically for the Instance Metadata Service.
func httpGet(dispatcher common.HTTPRequestDispatcher, url string) (body bytes.Buffer, statusCode int, err error) {
var response *http.Response
request, err := http.NewRequest(http.MethodGet, url, nil)
request.Header.Add("Authorization", "Bearer Oracle")
if response, err = dispatcher.Do(request); err != nil {
return
}
statusCode = response.StatusCode
common.IfDebug(func() {
if dump, e := httputil.DumpResponse(response, true); e == nil {
common.Logf("Dump Response %v", string(dump))
} else {
common.Debugln(e)
}
})
defer response.Body.Close()
if _, err = body.ReadFrom(response.Body); err != nil {
return
}
if statusCode != http.StatusOK {
err = fmt.Errorf("HTTP Get failed: URL: %s, Status: %s, Message: %s",
url, response.Status, body.String())
return
}
return
}
func extractTenancyIDFromCertificate(cert *x509.Certificate) string {
for _, nameAttr := range cert.Subject.Names {
value := nameAttr.Value.(string)
if strings.HasPrefix(value, "opc-tenant:") {
return value[len("opc-tenant:"):]
}
}
return ""
}
func fingerprint(certificate *x509.Certificate) string {
fingerprint := sha1.Sum(certificate.Raw)
return colonSeparatedString(fingerprint)
}
func colonSeparatedString(fingerprint [sha1.Size]byte) string {
spaceSeparated := fmt.Sprintf("% x", fingerprint)
return strings.Replace(spaceSeparated, " ", ":", -1)
}
func sanitizeCertificateString(certString string) string {
certString = strings.Replace(certString, "-----BEGIN CERTIFICATE-----", "", -1)
certString = strings.Replace(certString, "-----END CERTIFICATE-----", "", -1)
certString = strings.Replace(certString, "-----BEGIN PUBLIC KEY-----", "", -1)
certString = strings.Replace(certString, "-----END PUBLIC KEY-----", "", -1)
certString = strings.Replace(certString, "\n", "", -1)
return certString
}
// GetGenericConfigurationProvider checks auth config paras in config file and return the final configuration provider
func GetGenericConfigurationProvider(configProvider common.ConfigurationProvider) (common.ConfigurationProvider, error) {
if authConfig, err := configProvider.AuthType(); err == nil && authConfig.IsFromConfigFile {
switch authConfig.AuthType {
case common.InstancePrincipalDelegationToken:
if region, err := configProvider.Region(); err == nil {
return InstancePrincipalDelegationTokenConfigurationProviderForRegion(authConfig.OboToken, common.StringToRegion(region))
}
return InstancePrincipalDelegationTokenConfigurationProvider(authConfig.OboToken)
case common.InstancePrincipal:
return InstancePrincipalConfigurationProvider()
case common.UserPrincipal:
return configProvider, nil
}
}
return configProvider, nil
}

View file

@ -0,0 +1,235 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
package common
import (
"fmt"
"time"
"github.com/sony/gobreaker"
)
const (
// CircuitBreakerDefaultFailureRateThreshold is the requests failure rate which calculates in at most 120 seconds, once reaches to this rate, the circuit breaker state changes from closed to open
CircuitBreakerDefaultFailureRateThreshold float64 = 0.80
// CircuitBreakerDefaultClosedWindow is the default value of closeStateWindow, which is the cyclic period of the closed state
CircuitBreakerDefaultClosedWindow time.Duration = 120 * time.Second
// CircuitBreakerDefaultResetTimeout is the default value of openStateWindow, which is the wait time before setting the breaker to halfOpen state from open state
CircuitBreakerDefaultResetTimeout time.Duration = 30 * time.Second
// CircuitBreakerDefaultVolumeThreshold is the default value of minimumRequests in closed status
CircuitBreakerDefaultVolumeThreshold uint32 = 10
// DefaultCircuitBreakerName is the name of the circuit breaker
DefaultCircuitBreakerName string = "DefaultCircuitBreaker"
)
// CircuitBreakerSetting wraps all exposed configurable params of circuit breaker
type CircuitBreakerSetting struct {
// Name is the Circuit Breaker's identifier
name string
// isEnabled is the switch of the circuit breaker, used for disable circuit breaker
isEnabled bool
// closeStateWindow is the cyclic period of the closed state, the default value is 120 seconds
closeStateWindow time.Duration
// openStateWindow is the wait time before setting the breaker to halfOpen state from open state, the default value is 30 seconds
openStateWindow time.Duration
// failureRateThreshold is the failure rate which calculates in at most closeStateWindow seconds, once reaches to this rate, the circuit breaker state changes from closed to open
// the circuit will transition from closed to open, the default value is 80%
failureRateThreshold float64
// minimumRequests is the minimum number of counted requests in closed state, the default value is 10 requests
minimumRequests uint32
// successStatCodeMap is the error(s) of StatusCode returned from service, which should be considered as the success or failure accounted by circuit breaker
// successStatCodeMap and successStatErrCodeMap are combined to use, if both StatusCode and ErrorCode are required, no need to add it to successStatCodeMap,
// the default value is [429, 500, 502, 503, 504]
successStatCodeMap map[int]bool
// successStatErrCodeMap is the error(s) of StatusCode and ErrorCode returned from service, which should be considered
// as the success or failure accounted by circuit breaker
// the default value is {409, "IncorrectState"}
successStatErrCodeMap map[StatErrCode]bool
}
// Convert CircuitBreakerSetting to human-readable string representation
func (cbst CircuitBreakerSetting) String() string {
return fmt.Sprintf("{name=%v, isEnabled=%v, closeStateWindow=%v, openStateWindow=%v, failureRateThreshold=%v, minimumRequests=%v, successStatCodeMap=%v, successStatErrCodeMap=%v}",
cbst.name, cbst.isEnabled, cbst.closeStateWindow, cbst.openStateWindow, cbst.failureRateThreshold, cbst.minimumRequests, cbst.successStatCodeMap, cbst.successStatErrCodeMap)
}
// CircuitBreakerOption is the type of the options for NewCircuitBreakerWithOptions.
type CircuitBreakerOption func(cbst *CircuitBreakerSetting)
// NewGoCircuitBreaker is a function to initialize a CircuitBreaker object with the specified configuration
// Add the interface, to allow the user directly use the 3P gobreaker.Setting's params.
func NewGoCircuitBreaker(st gobreaker.Settings) *gobreaker.CircuitBreaker {
return gobreaker.NewCircuitBreaker(st)
}
// DefaultCircuitBreakerSetting is used for set circuit breaker with default config
func DefaultCircuitBreakerSetting() *CircuitBreakerSetting {
successStatErrCodeMap := map[StatErrCode]bool{
{409, "IncorrectState"}: false,
}
successStatCodeMap := map[int]bool{
429: false,
500: false,
502: false,
503: false,
504: false,
}
return newCircuitBreakerSetting(
WithName(DefaultCircuitBreakerName),
WithIsEnabled(true),
WithCloseStateWindow(CircuitBreakerDefaultClosedWindow),
WithOpenStateWindow(CircuitBreakerDefaultResetTimeout),
WithFailureRateThreshold(CircuitBreakerDefaultFailureRateThreshold),
WithMinimumRequests(CircuitBreakerDefaultVolumeThreshold),
WithSuccessStatErrCodeMap(successStatErrCodeMap),
WithSuccessStatCodeMap(successStatCodeMap))
}
// NoCircuitBreakerSetting is used for disable Circuit Breaker
func NoCircuitBreakerSetting() *CircuitBreakerSetting {
return NewCircuitBreakerSettingWithOptions(WithIsEnabled(false))
}
// NewCircuitBreakerSettingWithOptions is a helper method to assemble a CircuitBreakerSetting object.
// It starts out with the values returned by defaultCircuitBreakerSetting().
func NewCircuitBreakerSettingWithOptions(opts ...CircuitBreakerOption) *CircuitBreakerSetting {
cbst := DefaultCircuitBreakerSetting()
// allow changing values
for _, opt := range opts {
opt(cbst)
}
if defaultLogger.LogLevel() == verboseLogging {
Debugf("Circuit Breaker setting: %s\n", cbst.String())
}
return cbst
}
// NewCircuitBreaker is used for initialing specified circuit breaker configuration with base client
func NewCircuitBreaker(cbst *CircuitBreakerSetting) *gobreaker.CircuitBreaker {
if !cbst.isEnabled {
return nil
}
st := gobreaker.Settings{}
customizeGoBreakerSetting(&st, cbst)
return gobreaker.NewCircuitBreaker(st)
}
func newCircuitBreakerSetting(opts ...CircuitBreakerOption) *CircuitBreakerSetting {
cbSetting := CircuitBreakerSetting{}
// allow changing values
for _, opt := range opts {
opt(&cbSetting)
}
return &cbSetting
}
// customizeGoBreakerSetting is used for converting CircuitBreakerSetting to 3P gobreaker's setting type
func customizeGoBreakerSetting(st *gobreaker.Settings, cbst *CircuitBreakerSetting) {
st.Name = cbst.name
st.Timeout = cbst.openStateWindow
st.Interval = cbst.closeStateWindow
st.ReadyToTrip = func(counts gobreaker.Counts) bool {
failureRatio := float64(counts.TotalFailures) / float64(counts.Requests)
return counts.Requests >= cbst.minimumRequests && failureRatio >= cbst.failureRateThreshold
}
st.IsSuccessful = func(err error) bool {
if serviceErr, ok := IsServiceError(err); ok {
if isSuccessful, ok := cbst.successStatCodeMap[serviceErr.GetHTTPStatusCode()]; ok {
return isSuccessful
}
if isSuccessful, ok := cbst.successStatErrCodeMap[StatErrCode{serviceErr.GetHTTPStatusCode(), serviceErr.GetCode()}]; ok {
return isSuccessful
}
}
return true
}
}
// WithName is the option for NewCircuitBreaker that sets the Name.
func WithName(name string) CircuitBreakerOption {
// this is the CircuitBreakerOption function type
return func(cbst *CircuitBreakerSetting) {
cbst.name = name
}
}
// WithIsEnabled is the option for NewCircuitBreaker that sets the isEnabled.
func WithIsEnabled(isEnabled bool) CircuitBreakerOption {
// this is the CircuitBreakerOption function type
return func(cbst *CircuitBreakerSetting) {
cbst.isEnabled = isEnabled
}
}
// WithCloseStateWindow is the option for NewCircuitBreaker that sets the closeStateWindow.
func WithCloseStateWindow(window time.Duration) CircuitBreakerOption {
// this is the CircuitBreakerOption function type
return func(cbst *CircuitBreakerSetting) {
cbst.closeStateWindow = window
}
}
// WithOpenStateWindow is the option for NewCircuitBreaker that sets the openStateWindow.
func WithOpenStateWindow(window time.Duration) CircuitBreakerOption {
// this is the CircuitBreakerOption function type
return func(cbst *CircuitBreakerSetting) {
cbst.openStateWindow = window
}
}
// WithFailureRateThreshold is the option for NewCircuitBreaker that sets the failureRateThreshold.
func WithFailureRateThreshold(threshold float64) CircuitBreakerOption {
// this is the CircuitBreakerOption function type
return func(cbst *CircuitBreakerSetting) {
cbst.failureRateThreshold = threshold
}
}
// WithMinimumRequests is the option for NewCircuitBreaker that sets the minimumRequests.
func WithMinimumRequests(num uint32) CircuitBreakerOption {
// this is the CircuitBreakerOption function type
return func(cbst *CircuitBreakerSetting) {
cbst.minimumRequests = num
}
}
// WithSuccessStatCodeMap is the option for NewCircuitBreaker that sets the successStatCodeMap.
func WithSuccessStatCodeMap(successStatCodeMap map[int]bool) CircuitBreakerOption {
// this is the CircuitBreakerOption function type
return func(cbst *CircuitBreakerSetting) {
cbst.successStatCodeMap = successStatCodeMap
}
}
// WithSuccessStatErrCodeMap is the option for NewCircuitBreaker that sets the successStatErrCodeMap.
func WithSuccessStatErrCodeMap(successStatErrCodeMap map[StatErrCode]bool) CircuitBreakerOption {
// this is the CircuitBreakerOption function type
return func(cbst *CircuitBreakerSetting) {
cbst.successStatErrCodeMap = successStatErrCodeMap
}
}
// GlobalCircuitBreakerSetting is global level circuit breaker setting, it would impact all services, the precedence is lower
// than client level circuit breaker
var GlobalCircuitBreakerSetting *CircuitBreakerSetting = nil
// ConfigCircuitBreakerFromEnvVar is used for checking the circuit breaker environment variable setting, default value is nil
func ConfigCircuitBreakerFromEnvVar(baseClient *BaseClient) {
if IsEnvVarTrue(isDefaultCircuitBreakerEnabled) {
baseClient.Configuration.CircuitBreaker = NewCircuitBreaker(DefaultCircuitBreakerSetting())
return
}
if IsEnvVarFalse(isDefaultCircuitBreakerEnabled) {
baseClient.Configuration.CircuitBreaker = nil
}
}
// ConfigCircuitBreakerFromGlobalVar is used for checking if global circuitBreakerSetting is configured, the priority is higher than cb env var
func ConfigCircuitBreakerFromGlobalVar(baseClient *BaseClient) {
if GlobalCircuitBreakerSetting != nil {
baseClient.Configuration.CircuitBreaker = NewCircuitBreaker(GlobalCircuitBreakerSetting)
}
}

View file

@ -0,0 +1,630 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Package common provides supporting functions and structs used by service packages
package common
import (
"bytes"
"context"
"fmt"
"io"
"io/ioutil"
"math/rand"
"net"
"net/http"
"net/http/httputil"
"net/url"
"os"
"os/user"
"path"
"reflect"
"runtime"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/sony/gobreaker"
)
const (
// DefaultHostURLTemplate The default url template for service hosts
DefaultHostURLTemplate = "%s.%s.oraclecloud.com"
// requestHeaderAccept The key for passing a header to indicate Accept
requestHeaderAccept = "Accept"
// requestHeaderAuthorization The key for passing a header to indicate Authorization
requestHeaderAuthorization = "Authorization"
// requestHeaderContentLength The key for passing a header to indicate Content Length
requestHeaderContentLength = "Content-Length"
// requestHeaderContentType The key for passing a header to indicate Content Type
requestHeaderContentType = "Content-Type"
// requestHeaderExpect The key for passing a header to indicate Expect/100-Continue
requestHeaderExpect = "Expect"
// requestHeaderDate The key for passing a header to indicate Date
requestHeaderDate = "Date"
// requestHeaderIfMatch The key for passing a header to indicate If Match
requestHeaderIfMatch = "if-match"
// requestHeaderOpcClientInfo The key for passing a header to indicate OPC Client Info
requestHeaderOpcClientInfo = "opc-client-info"
// requestHeaderOpcRetryToken The key for passing a header to indicate OPC Retry Token
requestHeaderOpcRetryToken = "opc-retry-token"
// requestHeaderOpcRequestID The key for unique Oracle-assigned identifier for the request.
requestHeaderOpcRequestID = "opc-request-id"
// requestHeaderOpcClientRequestID The key for unique Oracle-assigned identifier for the request.
requestHeaderOpcClientRequestID = "opc-client-request-id"
// requestHeaderUserAgent The key for passing a header to indicate User Agent
requestHeaderUserAgent = "User-Agent"
// requestHeaderXContentSHA256 The key for passing a header to indicate SHA256 hash
requestHeaderXContentSHA256 = "X-Content-SHA256"
// requestHeaderOpcOboToken The key for passing a header to use obo token
requestHeaderOpcOboToken = "opc-obo-token"
// private constants
defaultScheme = "https"
defaultSDKMarker = "Oracle-GoSDK"
defaultUserAgentTemplate = "%s/%s (%s/%s; go/%s)" //SDK/SDKVersion (OS/OSVersion; Lang/LangVersion)
// http.Client.Timeout includes Dial, TLSHandshake, Request, Response header and body
defaultTimeout = 60 * time.Second
defaultConfigFileName = "config"
defaultConfigDirName = ".oci"
configFilePathEnvVarName = "OCI_CONFIG_FILE"
secondaryConfigDirName = ".oraclebmc"
maxBodyLenForDebug = 1024 * 1000
// appendUserAgentEnv The key for retrieving append user agent value from env var
appendUserAgentEnv = "OCI_SDK_APPEND_USER_AGENT"
// requestHeaderOpcClientRetries The key for passing a header to set client retries info
requestHeaderOpcClientRetries = "opc-client-retries"
// isDefaultRetryEnabled The key for set default retry disabled from env var
isDefaultRetryEnabled = "OCI_SDK_DEFAULT_RETRY_ENABLED"
// isDefaultCircuitBreakerEnabled is the key for set default circuit breaker disabled from env var
isDefaultCircuitBreakerEnabled = "OCI_SDK_DEFAULT_CIRCUITBREAKER_ENABLED"
)
// RequestInterceptor function used to customize the request before calling the underlying service
type RequestInterceptor func(*http.Request) error
// HTTPRequestDispatcher wraps the execution of a http request, it is generally implemented by
// http.Client.Do, but can be customized for testing
type HTTPRequestDispatcher interface {
Do(req *http.Request) (*http.Response, error)
}
// CustomClientConfiguration contains configurations set at client level, currently it only includes RetryPolicy
type CustomClientConfiguration struct {
RetryPolicy *RetryPolicy
CircuitBreaker *gobreaker.CircuitBreaker
}
// BaseClient struct implements all basic operations to call oci web services.
type BaseClient struct {
//HTTPClient performs the http network operations
HTTPClient HTTPRequestDispatcher
//Signer performs auth operation
Signer HTTPRequestSigner
//A request interceptor can be used to customize the request before signing and dispatching
Interceptor RequestInterceptor
//The host of the service
Host string
//The user agent
UserAgent string
//Base path for all operations of this client
BasePath string
Configuration CustomClientConfiguration
}
// SetCustomClientConfiguration sets client with retry and other custom configurations
func (client *BaseClient) SetCustomClientConfiguration(config CustomClientConfiguration) {
client.Configuration = config
}
// RetryPolicy returns the retryPolicy configured for client
func (client *BaseClient) RetryPolicy() *RetryPolicy {
return client.Configuration.RetryPolicy
}
// Endpoint returns the endpoint configured for client
func (client *BaseClient) Endpoint() string {
host := client.Host
if !strings.Contains(host, "http") &&
!strings.Contains(host, "https") {
host = fmt.Sprintf("%s://%s", defaultScheme, host)
}
return host
}
func defaultUserAgent() string {
userAgent := fmt.Sprintf(defaultUserAgentTemplate, defaultSDKMarker, Version(), runtime.GOOS, runtime.GOARCH, runtime.Version())
appendUA := os.Getenv(appendUserAgentEnv)
if appendUA != "" {
userAgent = fmt.Sprintf("%s %s", userAgent, appendUA)
}
return userAgent
}
var clientCounter int64
func getNextSeed() int64 {
newCounterValue := atomic.AddInt64(&clientCounter, 1)
return newCounterValue + time.Now().UnixNano()
}
func newBaseClient(signer HTTPRequestSigner, dispatcher HTTPRequestDispatcher) BaseClient {
rand.Seed(getNextSeed())
baseClient := BaseClient{
UserAgent: defaultUserAgent(),
Interceptor: nil,
Signer: signer,
HTTPClient: dispatcher,
}
// check the default retry environment variable setting
if IsEnvVarTrue(isDefaultRetryEnabled) {
defaultRetry := DefaultRetryPolicy()
baseClient.Configuration.RetryPolicy = &defaultRetry
} else if IsEnvVarFalse(isDefaultRetryEnabled) {
policy := NoRetryPolicy()
baseClient.Configuration.RetryPolicy = &policy
}
// check if user defined global retry is configured
if GlobalRetry != nil {
baseClient.Configuration.RetryPolicy = GlobalRetry
}
return baseClient
}
func defaultHTTPDispatcher() http.Client {
var httpClient http.Client
if isExpectHeaderDisabled := IsEnvVarFalse(UsingExpectHeaderEnvVar); !isExpectHeaderDisabled {
var tp http.RoundTripper = &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
DualStack: true,
}).DialContext,
ForceAttemptHTTP2: true,
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 3 * time.Second,
}
httpClient = http.Client{
Transport: tp,
Timeout: defaultTimeout,
}
} else {
httpClient = http.Client{
Timeout: defaultTimeout,
}
}
return httpClient
}
func defaultBaseClient(provider KeyProvider) BaseClient {
dispatcher := defaultHTTPDispatcher()
signer := DefaultRequestSigner(provider)
return newBaseClient(signer, &dispatcher)
}
//DefaultBaseClientWithSigner creates a default base client with a given signer
func DefaultBaseClientWithSigner(signer HTTPRequestSigner) BaseClient {
dispatcher := defaultHTTPDispatcher()
return newBaseClient(signer, &dispatcher)
}
// NewClientWithConfig Create a new client with a configuration provider, the configuration provider
// will be used for the default signer as well as reading the region
// This function does not check for valid regions to implement forward compatibility
func NewClientWithConfig(configProvider ConfigurationProvider) (client BaseClient, err error) {
var ok bool
if ok, err = IsConfigurationProviderValid(configProvider); !ok {
err = fmt.Errorf("can not create client, bad configuration: %s", err.Error())
return
}
client = defaultBaseClient(configProvider)
if authConfig, e := configProvider.AuthType(); e == nil && authConfig.OboToken != nil {
Debugf("authConfig's authType is %s, and token content is %s", authConfig.AuthType, *authConfig.OboToken)
signOboToken(&client, *authConfig.OboToken, configProvider)
}
return
}
// NewClientWithOboToken Create a new client that will use oboToken for auth
func NewClientWithOboToken(configProvider ConfigurationProvider, oboToken string) (client BaseClient, err error) {
client, err = NewClientWithConfig(configProvider)
if err != nil {
return
}
signOboToken(&client, oboToken, configProvider)
return
}
// Add obo token header to Interceptor and sign to client
func signOboToken(client *BaseClient, oboToken string, configProvider ConfigurationProvider) {
// Interceptor to add obo token header
client.Interceptor = func(request *http.Request) error {
request.Header.Add(requestHeaderOpcOboToken, oboToken)
return nil
}
// Obo token will also be signed
defaultHeaders := append(DefaultGenericHeaders(), requestHeaderOpcOboToken)
client.Signer = RequestSigner(configProvider, defaultHeaders, DefaultBodyHeaders())
}
func getHomeFolder() string {
current, e := user.Current()
if e != nil {
//Give up and try to return something sensible
home := os.Getenv("HOME")
if home == "" {
home = os.Getenv("USERPROFILE")
}
return home
}
return current.HomeDir
}
// DefaultConfigProvider returns the default config provider. The default config provider
// will look for configurations in 3 places: file in $HOME/.oci/config, HOME/.obmcs/config and
// variables names starting with the string TF_VAR. If the same configuration is found in multiple
// places the provider will prefer the first one.
// If the config file is not placed in the default location, the environment variable
// OCI_CONFIG_FILE can provide the config file location.
func DefaultConfigProvider() ConfigurationProvider {
defaultConfigFile := getDefaultConfigFilePath()
homeFolder := getHomeFolder()
secondaryConfigFile := path.Join(homeFolder, secondaryConfigDirName, defaultConfigFileName)
defaultFileProvider, _ := ConfigurationProviderFromFile(defaultConfigFile, "")
secondaryFileProvider, _ := ConfigurationProviderFromFile(secondaryConfigFile, "")
environmentProvider := environmentConfigurationProvider{EnvironmentVariablePrefix: "TF_VAR"}
provider, _ := ComposingConfigurationProvider([]ConfigurationProvider{defaultFileProvider, secondaryFileProvider, environmentProvider})
Debugf("Configuration provided by: %s", provider)
return provider
}
func getDefaultConfigFilePath() string {
homeFolder := getHomeFolder()
defaultConfigFile := path.Join(homeFolder, defaultConfigDirName, defaultConfigFileName)
if _, err := os.Stat(defaultConfigFile); err == nil {
return defaultConfigFile
}
Debugf("The %s does not exist, will check env var %s for file path.", defaultConfigFile, configFilePathEnvVarName)
// Read configuration file path from OCI_CONFIG_FILE env var
fallbackConfigFile, existed := os.LookupEnv(configFilePathEnvVarName)
if !existed {
Debugf("The env var %s does not exist...", configFilePathEnvVarName)
return defaultConfigFile
}
if _, err := os.Stat(fallbackConfigFile); os.IsNotExist(err) {
Debugf("The specified cfg file path in the env var %s does not exist: %s", configFilePathEnvVarName, fallbackConfigFile)
return defaultConfigFile
}
return fallbackConfigFile
}
// CustomProfileConfigProvider returns the config provider of given profile. The custom profile config provider
// will look for configurations in 2 places: file in $HOME/.oci/config, and variables names starting with the
// string TF_VAR. If the same configuration is found in multiple places the provider will prefer the first one.
func CustomProfileConfigProvider(customConfigPath string, profile string) ConfigurationProvider {
homeFolder := getHomeFolder()
if customConfigPath == "" {
customConfigPath = path.Join(homeFolder, defaultConfigDirName, defaultConfigFileName)
}
customFileProvider, _ := ConfigurationProviderFromFileWithProfile(customConfigPath, profile, "")
defaultFileProvider, _ := ConfigurationProviderFromFileWithProfile(customConfigPath, "DEFAULT", "")
environmentProvider := environmentConfigurationProvider{EnvironmentVariablePrefix: "TF_VAR"}
provider, _ := ComposingConfigurationProvider([]ConfigurationProvider{customFileProvider, defaultFileProvider, environmentProvider})
Debugf("Configuration provided by: %s", provider)
return provider
}
func (client *BaseClient) prepareRequest(request *http.Request) (err error) {
if client.UserAgent == "" {
return fmt.Errorf("user agent can not be blank")
}
if request.Header == nil {
request.Header = http.Header{}
}
request.Header.Set(requestHeaderUserAgent, client.UserAgent)
request.Header.Set(requestHeaderDate, time.Now().UTC().Format(http.TimeFormat))
if !strings.Contains(client.Host, "http") &&
!strings.Contains(client.Host, "https") {
client.Host = fmt.Sprintf("%s://%s", defaultScheme, client.Host)
}
clientURL, err := url.Parse(client.Host)
if err != nil {
return fmt.Errorf("host is invalid. %s", err.Error())
}
request.URL.Host = clientURL.Host
request.URL.Scheme = clientURL.Scheme
currentPath := request.URL.Path
if !strings.Contains(currentPath, fmt.Sprintf("/%s", client.BasePath)) {
request.URL.Path = path.Clean(fmt.Sprintf("/%s/%s", client.BasePath, currentPath))
}
return
}
func (client BaseClient) intercept(request *http.Request) (err error) {
if client.Interceptor != nil {
err = client.Interceptor(request)
}
return
}
// checkForSuccessfulResponse checks if the response is successful
// If Error Code is 4XX/5XX and debug level is set to info, will log the request and response
func checkForSuccessfulResponse(res *http.Response, requestBody *io.ReadCloser) error {
familyStatusCode := res.StatusCode / 100
if familyStatusCode == 4 || familyStatusCode == 5 {
IfInfo(func() {
// If debug level is set to verbose, the request and request body will be dumped and logged under debug level, this is to avoid duplicate logging
if defaultLogger.LogLevel() < verboseLogging {
logRequest(res.Request, Logf, noLogging)
if requestBody != nil && *requestBody != http.NoBody {
bodyContent, _ := ioutil.ReadAll(*requestBody)
Logf("Dump Request Body: \n%s", string(bodyContent))
}
}
logResponse(res, Logf, infoLogging)
})
return newServiceFailureFromResponse(res)
}
IfDebug(func() {
logResponse(res, Debugf, verboseLogging)
})
return nil
}
func logRequest(request *http.Request, fn func(format string, v ...interface{}), bodyLoggingLevel int) {
if request == nil {
return
}
dumpBody := true
if checkBodyLengthExceedLimit(request.ContentLength) {
fn("not dumping body too big\n")
dumpBody = false
}
dumpBody = dumpBody && defaultLogger.LogLevel() >= bodyLoggingLevel && bodyLoggingLevel != noLogging
if dump, e := httputil.DumpRequestOut(request, dumpBody); e == nil {
fn("Dump Request %s", string(dump))
} else {
fn("%v\n", e)
}
}
func logResponse(response *http.Response, fn func(format string, v ...interface{}), bodyLoggingLevel int) {
if response == nil {
return
}
dumpBody := true
if checkBodyLengthExceedLimit(response.ContentLength) {
fn("not dumping body too big\n")
dumpBody = false
}
dumpBody = dumpBody && defaultLogger.LogLevel() >= bodyLoggingLevel && bodyLoggingLevel != noLogging
if dump, e := httputil.DumpResponse(response, dumpBody); e == nil {
fn("Dump Response %s", string(dump))
} else {
fn("%v\n", e)
}
}
func checkBodyLengthExceedLimit(contentLength int64) bool {
if contentLength > maxBodyLenForDebug {
return true
}
return false
}
// OCIRequest is any request made to an OCI service.
type OCIRequest interface {
// HTTPRequest assembles an HTTP request.
HTTPRequest(method, path string, binaryRequestBody *OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error)
}
// RequestMetadata is metadata about an OCIRequest. This structure represents the behavior exhibited by the SDK when
// issuing (or reissuing) a request.
type RequestMetadata struct {
// RetryPolicy is the policy for reissuing the request. If no retry policy is set on the request,
// then the request will be issued exactly once.
RetryPolicy *RetryPolicy
}
// OCIReadSeekCloser is a thread-safe io.ReadSeekCloser to prevent racing with retrying binary requests
type OCIReadSeekCloser struct {
rc io.ReadCloser
lock sync.Mutex
isClosed bool
}
// NewOCIReadSeekCloser constructs OCIReadSeekCloser, the only input is binary request body
func NewOCIReadSeekCloser(rc io.ReadCloser) *OCIReadSeekCloser {
rsc := OCIReadSeekCloser{}
rsc.rc = rc
return &rsc
}
// Seek is a thread-safe operation, it implements io.seek() interface, if the original request body implements io.seek()
// interface, or implements "well-known" data type like os.File, io.SectionReader, or wrapped by ioutil.NopCloser can be supported
func (rsc *OCIReadSeekCloser) Seek(offset int64, whence int) (int64, error) {
rsc.lock.Lock()
defer rsc.lock.Unlock()
if _, ok := rsc.rc.(io.Seeker); ok {
return rsc.rc.(io.Seeker).Seek(offset, whence)
}
// once the binary request body is wrapped with ioutil.NopCloser:
if reflect.TypeOf(rsc.rc) == reflect.TypeOf(ioutil.NopCloser(nil)) {
unwrappedInterface := reflect.ValueOf(rsc.rc).Field(0).Interface()
if _, ok := unwrappedInterface.(io.Seeker); ok {
return unwrappedInterface.(io.Seeker).Seek(offset, whence)
}
}
return 0, fmt.Errorf("current binary request body type is not seekable, if want to use retry feature, please make sure the request body implements seek() method")
}
// Close is a thread-safe operation, it closes the instance of the OCIReadSeekCloser's access to the underlying io.ReadCloser.
func (rsc *OCIReadSeekCloser) Close() error {
rsc.lock.Lock()
defer rsc.lock.Unlock()
rsc.isClosed = true
return nil
}
// Read is a thread-safe operation, it implements io.Read() interface
func (rsc *OCIReadSeekCloser) Read(p []byte) (n int, err error) {
rsc.lock.Lock()
defer rsc.lock.Unlock()
if rsc.isClosed {
return 0, io.EOF
}
return rsc.rc.Read(p)
}
// Seekable is used for check if the binary request body can be seek or no
func (rsc *OCIReadSeekCloser) Seekable() bool {
if rsc == nil {
return false
}
if _, ok := rsc.rc.(io.Seeker); ok {
return true
}
// once the binary request body is wrapped with ioutil.NopCloser:
if reflect.TypeOf(rsc.rc) == reflect.TypeOf(ioutil.NopCloser(nil)) {
if _, ok := reflect.ValueOf(rsc.rc).Field(0).Interface().(io.Seeker); ok {
return true
}
}
return false
}
// OCIResponse is the response from issuing a request to an OCI service.
type OCIResponse interface {
// HTTPResponse returns the raw HTTP response.
HTTPResponse() *http.Response
}
// OCIOperation is the generalization of a request-response cycle undergone by an OCI service.
type OCIOperation func(context.Context, OCIRequest, *OCIReadSeekCloser, map[string]string) (OCIResponse, error)
//ClientCallDetails a set of settings used by the a single Call operation of the http Client
type ClientCallDetails struct {
Signer HTTPRequestSigner
}
// Call executes the http request with the given context
func (client BaseClient) Call(ctx context.Context, request *http.Request) (response *http.Response, err error) {
return client.CallWithDetails(ctx, request, ClientCallDetails{Signer: client.Signer})
}
// CallWithDetails executes the http request, the given context using details specified in the parameters, this function
// provides a way to override some settings present in the client
func (client BaseClient) CallWithDetails(ctx context.Context, request *http.Request, details ClientCallDetails) (response *http.Response, err error) {
Debugln("Attempting to call downstream service")
request = request.WithContext(ctx)
err = client.prepareRequest(request)
if err != nil {
return
}
//Intercept
err = client.intercept(request)
if err != nil {
return
}
//Sign the request
err = details.Signer.Sign(request)
if err != nil {
return
}
//Execute the http request
if goBreaker := client.Configuration.CircuitBreaker; goBreaker != nil {
resp, cbErr := goBreaker.Execute(func() (interface{}, error) {
return client.httpDo(request)
})
if cbErr != nil {
return resp.(*http.Response), cbErr
}
return resp.(*http.Response), nil
}
return client.httpDo(request)
}
func (client BaseClient) httpDo(request *http.Request) (response *http.Response, err error) {
//Copy request body and save for logging
dumpRequestBody := ioutil.NopCloser(bytes.NewBuffer(nil))
if request.Body != nil && !checkBodyLengthExceedLimit(request.ContentLength) {
if dumpRequestBody, request.Body, err = drainBody(request.Body); err != nil {
dumpRequestBody = ioutil.NopCloser(bytes.NewBuffer(nil))
}
}
IfDebug(func() {
logRequest(request, Debugf, verboseLogging)
})
//Execute the http request
response, err = client.HTTPClient.Do(request)
if err != nil {
IfInfo(func() {
Logf("%v\n", err)
})
return response, err
}
err = checkForSuccessfulResponse(response, &dumpRequestBody)
return response, err
}
//CloseBodyIfValid closes the body of an http response if the response and the body are valid
func CloseBodyIfValid(httpResponse *http.Response) {
if httpResponse != nil && httpResponse.Body != nil {
httpResponse.Body.Close()
}
}

View file

@ -0,0 +1,339 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
package common
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"path"
"regexp"
"strings"
"time"
)
//Region type for regions
type Region string
const (
instanceMetadataRegionInfoURLV2 = "http://169.254.169.254/opc/v2/instance/regionInfo"
// Region Metadata Configuration File
regionMetadataCfgDirName = ".oci"
regionMetadataCfgFileName = "regions-config.json"
// Region Metadata Environment Variable
regionMetadataEnvVarName = "OCI_REGION_METADATA"
// Default Realm Environment Variable
defaultRealmEnvVarName = "OCI_DEFAULT_REALM"
// Region Metadata
regionIdentifierPropertyName = "regionIdentifier" // e.g. "ap-sydney-1"
realmKeyPropertyName = "realmKey" // e.g. "oc1"
realmDomainComponentPropertyName = "realmDomainComponent" // e.g. "oraclecloud.com"
regionKeyPropertyName = "regionKey" // e.g. "SYD"
)
// External region metadata info flag, used to control adding these metadata region info only once.
var readCfgFile, readEnvVar, visitIMDS bool = true, true, false
// getRegionInfoFromInstanceMetadataService gets the region information
var getRegionInfoFromInstanceMetadataService = getRegionInfoFromInstanceMetadataServiceProd
// Endpoint returns a endpoint for a service
func (region Region) Endpoint(service string) string {
return fmt.Sprintf("%s.%s.%s", service, region, region.secondLevelDomain())
}
// EndpointForTemplate returns a endpoint for a service based on template, only unknown region name can fall back to "oc1", but not short code region name.
func (region Region) EndpointForTemplate(service string, serviceEndpointTemplate string) string {
if serviceEndpointTemplate == "" {
return region.Endpoint(service)
}
// replace service prefix
endpoint := strings.Replace(serviceEndpointTemplate, "{serviceEndpointPrefix}", service, 1)
// replace region
endpoint = strings.Replace(endpoint, "{region}", string(region), 1)
// replace second level domain
endpoint = strings.Replace(endpoint, "{secondLevelDomain}", region.secondLevelDomain(), 1)
return endpoint
}
func (region Region) secondLevelDomain() string {
if realmID, ok := regionRealm[region]; ok {
if secondLevelDomain, ok := realm[realmID]; ok {
return secondLevelDomain
}
}
if value, ok := os.LookupEnv(defaultRealmEnvVarName); ok {
return value
}
Debugf("cannot find realm for region : %s, return default realm value.", region)
return realm["oc1"]
}
// RealmID is used for getting realmID from region, if no region found, directly throw error
func (region Region) RealmID() (string, error) {
if realmID, ok := regionRealm[region]; ok {
return realmID, nil
}
return "", fmt.Errorf("cannot find realm for region : %s", region)
}
//StringToRegion convert a string to Region type
func StringToRegion(stringRegion string) (r Region) {
regionStr := strings.ToLower(stringRegion)
// check if short region name provided
if region, ok := shortNameRegion[regionStr]; ok {
r = region
return
}
// check if normal region name provided
potentialRegion := Region(regionStr)
if _, ok := regionRealm[potentialRegion]; ok {
r = potentialRegion
return
}
Debugf("region named: %s, is not recognized from hard-coded region list, will check Region metadata info", stringRegion)
r = checkAndAddRegionMetadata(stringRegion)
return
}
// canStringBeRegion test if the string can be a region, if it can, returns the string as is, otherwise it
// returns an error
var blankRegex = regexp.MustCompile("\\s")
func canStringBeRegion(stringRegion string) (region string, err error) {
if blankRegex.MatchString(stringRegion) || stringRegion == "" {
return "", fmt.Errorf("region can not be empty or have spaces")
}
return stringRegion, nil
}
// check region info from original map
func checkAndAddRegionMetadata(region string) Region {
switch {
case setRegionMetadataFromCfgFile(&region):
case setRegionMetadataFromEnvVar(&region):
case setRegionFromInstanceMetadataService(&region):
default:
//err := fmt.Errorf("failed to get region metadata information.")
return Region(region)
}
return Region(region)
}
// EnableInstanceMetadataServiceLookup provides the interface to lookup IMDS region info
func EnableInstanceMetadataServiceLookup() {
Debugf("Set visitIMDS 'true' to enable IMDS Lookup.")
visitIMDS = true
}
// setRegionMetadataFromEnvVar checks if region metadata env variable is provided, once it's there, parse and added it
// to region map, and it can make sure the env var can only be visited once.
// Once successfully find the expected region(region name or short code), return true, region name will be stored in
// the input pointer.
func setRegionMetadataFromEnvVar(region *string) bool {
if readEnvVar == false {
Debugf("metadata region env variable had already been checked, no need to check again.")
return false //no need to check it again.
}
// Mark readEnvVar Flag as false since it has already been visited.
readEnvVar = false
// check from env variable
if jsonStr, existed := os.LookupEnv(regionMetadataEnvVarName); existed {
Debugf("Raw content of region metadata env var:", jsonStr)
var regionSchema map[string]string
if err := json.Unmarshal([]byte(jsonStr), &regionSchema); err != nil {
Debugf("Can't unmarshal env var, the error info is", err)
return false
}
// check if the specified region is in the env var.
if checkSchemaItems(regionSchema) {
// set mapping table
addRegionSchema(regionSchema)
if regionSchema[regionKeyPropertyName] == *region ||
regionSchema[regionIdentifierPropertyName] == *region {
*region = regionSchema[regionIdentifierPropertyName]
return true
}
}
return false
}
Debugf("The Region Metadata Schema wasn't set in env variable - OCI_REGION_METADATA.")
return false
}
// setRegionMetadataFromCfgFile checks if region metadata config file is provided, once it's there, parse and add all
// the valid regions to region map, the configuration file can only be visited once.
// Once successfully find the expected region(region name or short code), return true, region name will be stored in
// the input pointer.
func setRegionMetadataFromCfgFile(region *string) bool {
if readCfgFile == false {
Debugf("metadata region config file had already been checked, no need to check again.")
return false //no need to check it again.
}
// Mark readCfgFile Flag as false since it has already been visited.
readCfgFile = false
homeFolder := getHomeFolder()
configFile := path.Join(homeFolder, regionMetadataCfgDirName, regionMetadataCfgFileName)
if jsonArr, ok := readAndParseConfigFile(&configFile); ok {
added := false
for _, jsonItem := range jsonArr {
if checkSchemaItems(jsonItem) {
addRegionSchema(jsonItem)
if jsonItem[regionKeyPropertyName] == *region ||
jsonItem[regionIdentifierPropertyName] == *region {
*region = jsonItem[regionIdentifierPropertyName]
added = true
}
}
}
return added
}
return false
}
func readAndParseConfigFile(configFileName *string) (fileContent []map[string]string, ok bool) {
if content, err := ioutil.ReadFile(*configFileName); err == nil {
Debugf("Raw content of region metadata config file content:", string(content[:]))
if err := json.Unmarshal(content, &fileContent); err != nil {
Debugf("Can't unmarshal config file, the error info is", err)
return
}
ok = true
return
}
Debugf("No Region Metadata Config File provided.")
return
}
// check map regionRealm's region name, if it's already there, no need to add it.
func addRegionSchema(regionSchema map[string]string) {
r := Region(strings.ToLower(regionSchema[regionIdentifierPropertyName]))
if _, ok := regionRealm[r]; !ok {
// set mapping table
shortNameRegion[regionSchema[regionKeyPropertyName]] = r
realm[regionSchema[realmKeyPropertyName]] = regionSchema[realmDomainComponentPropertyName]
regionRealm[r] = regionSchema[realmKeyPropertyName]
return
}
Debugf("Region {} has already been added, no need to add again.", regionSchema[regionIdentifierPropertyName])
}
// check region schema content if all the required contents are provided
func checkSchemaItems(regionSchema map[string]string) bool {
if checkSchemaItem(regionSchema, regionIdentifierPropertyName) &&
checkSchemaItem(regionSchema, realmKeyPropertyName) &&
checkSchemaItem(regionSchema, realmDomainComponentPropertyName) &&
checkSchemaItem(regionSchema, regionKeyPropertyName) {
return true
}
return false
}
// check region schema item is valid, if so, convert it to lower case.
func checkSchemaItem(regionSchema map[string]string, key string) bool {
if val, ok := regionSchema[key]; ok {
if val != "" {
regionSchema[key] = strings.ToLower(val)
return true
}
Debugf("Region metadata schema {} is provided,but content is empty.", key)
return false
}
Debugf("Region metadata schema {} is not provided, please update the content", key)
return false
}
// setRegionFromInstanceMetadataService checks if region metadata can be provided from InstanceMetadataService.
// Once successfully find the expected region(region name or short code), return true, region name will be stored in
// the input pointer.
// setRegionFromInstanceMetadataService will only be checked on the instance, by default it will not be enabled unless
// user explicitly enable it.
func setRegionFromInstanceMetadataService(region *string) bool {
// example of content:
// {
// "realmKey" : "oc1",
// "realmDomainComponent" : "oraclecloud.com",
// "regionKey" : "YUL",
// "regionIdentifier" : "ca-montreal-1"
// }
// Mark visitIMDS Flag as false since it has already been visited.
if visitIMDS == false {
Debugf("check from IMDS is disabled or IMDS had already been successfully visited, no need to check again.")
return false
}
content, err := getRegionInfoFromInstanceMetadataService()
if err != nil {
Debugf("Failed to get instance metadata. Error: %v", err)
return false
}
// Mark visitIMDS Flag as false since we have already successfully get the region info from IMDS.
visitIMDS = false
var regionInfo map[string]string
err = json.Unmarshal(content, &regionInfo)
if err != nil {
Debugf("Failed to unmarshal the response content: %v \nError: %v", string(content), err)
return false
}
if checkSchemaItems(regionInfo) {
addRegionSchema(regionInfo)
if regionInfo[regionKeyPropertyName] == *region ||
regionInfo[regionIdentifierPropertyName] == *region {
*region = regionInfo[regionIdentifierPropertyName]
}
} else {
Debugf("Region information is not valid.")
return false
}
return true
}
// getRegionInfoFromInstanceMetadataServiceProd calls instance metadata service and get the region information
func getRegionInfoFromInstanceMetadataServiceProd() ([]byte, error) {
request, err := http.NewRequest(http.MethodGet, instanceMetadataRegionInfoURLV2, nil)
request.Header.Add("Authorization", "Bearer Oracle")
client := &http.Client{
Timeout: time.Second * 10,
}
resp, err := client.Do(request)
if err != nil {
return nil, fmt.Errorf("Failed to call instance metadata service. Error: %v", err)
}
statusCode := resp.StatusCode
defer resp.Body.Close()
content, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("Failed to get region information from response body. Error: %v", err)
}
if statusCode != http.StatusOK {
err = fmt.Errorf("HTTP Get failed: URL: %s, Status: %s, Message: %s",
instanceMetadataRegionInfoURLV2, resp.Status, string(content))
return nil, err
}
return content, nil
}

View file

@ -0,0 +1,659 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
package common
import (
"crypto/rsa"
"errors"
"fmt"
"io/ioutil"
"os"
"path"
"regexp"
"strings"
)
// AuthenticationType for auth
type AuthenticationType string
const (
// UserPrincipal is default auth type
UserPrincipal AuthenticationType = "user_principal"
// InstancePrincipal is used for instance principle auth type
InstancePrincipal AuthenticationType = "instance_principal"
// InstancePrincipalDelegationToken is used for instance principle delegation token auth type
InstancePrincipalDelegationToken AuthenticationType = "instance_principle_delegation_token"
// UnknownAuthenticationType is used for none meaningful auth type
UnknownAuthenticationType AuthenticationType = "unknown_auth_type"
)
// AuthConfig is used for getting auth related paras in config file
type AuthConfig struct {
AuthType AuthenticationType
// IsFromConfigFile is used to point out if the authConfig is from configuration file
IsFromConfigFile bool
OboToken *string
}
// ConfigurationProvider wraps information about the account owner
type ConfigurationProvider interface {
KeyProvider
TenancyOCID() (string, error)
UserOCID() (string, error)
KeyFingerprint() (string, error)
Region() (string, error)
// AuthType() is used for specify the needed auth type, like UserPrincipal, InstancePrincipal, etc.
AuthType() (AuthConfig, error)
}
// IsConfigurationProviderValid Tests all parts of the configuration provider do not return an error, this method will
// not check AuthType(), since authType() is not required to be there.
func IsConfigurationProviderValid(conf ConfigurationProvider) (ok bool, err error) {
baseFn := []func() (string, error){conf.TenancyOCID, conf.UserOCID, conf.KeyFingerprint, conf.Region, conf.KeyID}
for _, fn := range baseFn {
_, err = fn()
ok = err == nil
if err != nil {
return
}
}
_, err = conf.PrivateRSAKey()
ok = err == nil
if err != nil {
return
}
return true, nil
}
// rawConfigurationProvider allows a user to simply construct a configuration provider from raw values.
type rawConfigurationProvider struct {
tenancy string
user string
region string
fingerprint string
privateKey string
privateKeyPassphrase *string
}
// NewRawConfigurationProvider will create a ConfigurationProvider with the arguments of the function
func NewRawConfigurationProvider(tenancy, user, region, fingerprint, privateKey string, privateKeyPassphrase *string) ConfigurationProvider {
return rawConfigurationProvider{tenancy, user, region, fingerprint, privateKey, privateKeyPassphrase}
}
func (p rawConfigurationProvider) PrivateRSAKey() (key *rsa.PrivateKey, err error) {
return PrivateKeyFromBytes([]byte(p.privateKey), p.privateKeyPassphrase)
}
func (p rawConfigurationProvider) KeyID() (keyID string, err error) {
tenancy, err := p.TenancyOCID()
if err != nil {
return
}
user, err := p.UserOCID()
if err != nil {
return
}
fingerprint, err := p.KeyFingerprint()
if err != nil {
return
}
return fmt.Sprintf("%s/%s/%s", tenancy, user, fingerprint), nil
}
func (p rawConfigurationProvider) TenancyOCID() (string, error) {
if p.tenancy == "" {
return "", fmt.Errorf("tenancy OCID can not be empty")
}
return p.tenancy, nil
}
func (p rawConfigurationProvider) UserOCID() (string, error) {
if p.user == "" {
return "", fmt.Errorf("user OCID can not be empty")
}
return p.user, nil
}
func (p rawConfigurationProvider) KeyFingerprint() (string, error) {
if p.fingerprint == "" {
return "", fmt.Errorf("fingerprint can not be empty")
}
return p.fingerprint, nil
}
func (p rawConfigurationProvider) Region() (string, error) {
return canStringBeRegion(p.region)
}
func (p rawConfigurationProvider) AuthType() (AuthConfig, error) {
return AuthConfig{UnknownAuthenticationType, false, nil}, nil
}
// environmentConfigurationProvider reads configuration from environment variables
type environmentConfigurationProvider struct {
PrivateKeyPassword string
EnvironmentVariablePrefix string
}
// ConfigurationProviderEnvironmentVariables creates a ConfigurationProvider from a uniform set of environment variables starting with a prefix
// The env variables should look like: [prefix]_private_key_path, [prefix]_tenancy_ocid, [prefix]_user_ocid, [prefix]_fingerprint
// [prefix]_region
func ConfigurationProviderEnvironmentVariables(environmentVariablePrefix, privateKeyPassword string) ConfigurationProvider {
return environmentConfigurationProvider{EnvironmentVariablePrefix: environmentVariablePrefix,
PrivateKeyPassword: privateKeyPassword}
}
func (p environmentConfigurationProvider) String() string {
return fmt.Sprintf("Configuration provided by environment variables prefixed with: %s", p.EnvironmentVariablePrefix)
}
func (p environmentConfigurationProvider) PrivateRSAKey() (key *rsa.PrivateKey, err error) {
environmentVariable := fmt.Sprintf("%s_%s", p.EnvironmentVariablePrefix, "private_key_path")
var ok bool
var value string
if value, ok = os.LookupEnv(environmentVariable); !ok {
return nil, fmt.Errorf("can not read PrivateKey from env variable: %s", environmentVariable)
}
expandedPath := expandPath(value)
pemFileContent, err := ioutil.ReadFile(expandedPath)
if err != nil {
Debugln("Can not read PrivateKey location from environment variable: " + environmentVariable)
return
}
key, err = PrivateKeyFromBytes(pemFileContent, &p.PrivateKeyPassword)
return
}
func (p environmentConfigurationProvider) KeyID() (keyID string, err error) {
ocid, err := p.TenancyOCID()
if err != nil {
return
}
userocid, err := p.UserOCID()
if err != nil {
return
}
fingerprint, err := p.KeyFingerprint()
if err != nil {
return
}
return fmt.Sprintf("%s/%s/%s", ocid, userocid, fingerprint), nil
}
func (p environmentConfigurationProvider) TenancyOCID() (value string, err error) {
environmentVariable := fmt.Sprintf("%s_%s", p.EnvironmentVariablePrefix, "tenancy_ocid")
var ok bool
if value, ok = os.LookupEnv(environmentVariable); !ok {
err = fmt.Errorf("can not read Tenancy from environment variable %s", environmentVariable)
}
return
}
func (p environmentConfigurationProvider) UserOCID() (value string, err error) {
environmentVariable := fmt.Sprintf("%s_%s", p.EnvironmentVariablePrefix, "user_ocid")
var ok bool
if value, ok = os.LookupEnv(environmentVariable); !ok {
err = fmt.Errorf("can not read user id from environment variable %s", environmentVariable)
}
return
}
func (p environmentConfigurationProvider) KeyFingerprint() (value string, err error) {
environmentVariable := fmt.Sprintf("%s_%s", p.EnvironmentVariablePrefix, "fingerprint")
var ok bool
if value, ok = os.LookupEnv(environmentVariable); !ok {
err = fmt.Errorf("can not read fingerprint from environment variable %s", environmentVariable)
}
return
}
func (p environmentConfigurationProvider) Region() (value string, err error) {
environmentVariable := fmt.Sprintf("%s_%s", p.EnvironmentVariablePrefix, "region")
var ok bool
if value, ok = os.LookupEnv(environmentVariable); !ok {
err = fmt.Errorf("can not read region from environment variable %s", environmentVariable)
return value, err
}
return canStringBeRegion(value)
}
func (p environmentConfigurationProvider) AuthType() (AuthConfig, error) {
return AuthConfig{UnknownAuthenticationType, false, nil},
fmt.Errorf("unsupported, keep the interface")
}
// fileConfigurationProvider. reads configuration information from a file
type fileConfigurationProvider struct {
//The path to the configuration file
ConfigPath string
//The password for the private key
PrivateKeyPassword string
//The profile for the configuration
Profile string
//ConfigFileInfo
FileInfo *configFileInfo
}
// ConfigurationProviderFromFile creates a configuration provider from a configuration file
// by reading the "DEFAULT" profile
func ConfigurationProviderFromFile(configFilePath, privateKeyPassword string) (ConfigurationProvider, error) {
if configFilePath == "" {
return nil, fmt.Errorf("config file path can not be empty")
}
return fileConfigurationProvider{
ConfigPath: configFilePath,
PrivateKeyPassword: privateKeyPassword,
Profile: "DEFAULT"}, nil
}
// ConfigurationProviderFromFileWithProfile creates a configuration provider from a configuration file
// and the given profile
func ConfigurationProviderFromFileWithProfile(configFilePath, profile, privateKeyPassword string) (ConfigurationProvider, error) {
if configFilePath == "" {
return nil, fmt.Errorf("config file path can not be empty")
}
return fileConfigurationProvider{
ConfigPath: configFilePath,
PrivateKeyPassword: privateKeyPassword,
Profile: profile}, nil
}
type configFileInfo struct {
UserOcid, Fingerprint, KeyFilePath, TenancyOcid, Region, Passphrase, SecurityTokenFilePath, DelegationTokenFilePath,
AuthenticationType string
PresentConfiguration rune
}
const (
hasTenancy = 1 << iota
hasUser
hasFingerprint
hasRegion
hasKeyFile
hasPassphrase
hasSecurityTokenFile
hasDelegationTokenFile
hasAuthenticationType
none
)
var profileRegex = regexp.MustCompile(`^\[(.*)\]`)
func parseConfigFile(data []byte, profile string) (info *configFileInfo, err error) {
if len(data) == 0 {
return nil, fmt.Errorf("configuration file content is empty")
}
content := string(data)
splitContent := strings.Split(content, "\n")
//Look for profile
for i, line := range splitContent {
if match := profileRegex.FindStringSubmatch(line); match != nil && len(match) > 1 && match[1] == profile {
start := i + 1
return parseConfigAtLine(start, splitContent)
}
}
return nil, fmt.Errorf("configuration file did not contain profile: %s", profile)
}
func parseConfigAtLine(start int, content []string) (info *configFileInfo, err error) {
var configurationPresent rune
info = &configFileInfo{}
for i := start; i < len(content); i++ {
line := content[i]
if profileRegex.MatchString(line) {
break
}
if !strings.Contains(line, "=") {
continue
}
splits := strings.Split(line, "=")
switch key, value := strings.TrimSpace(splits[0]), strings.TrimSpace(splits[1]); strings.ToLower(key) {
case "passphrase", "pass_phrase":
configurationPresent = configurationPresent | hasPassphrase
info.Passphrase = value
case "user":
configurationPresent = configurationPresent | hasUser
info.UserOcid = value
case "fingerprint":
configurationPresent = configurationPresent | hasFingerprint
info.Fingerprint = value
case "key_file":
configurationPresent = configurationPresent | hasKeyFile
info.KeyFilePath = value
case "tenancy":
configurationPresent = configurationPresent | hasTenancy
info.TenancyOcid = value
case "region":
configurationPresent = configurationPresent | hasRegion
info.Region = value
case "security_token_file":
configurationPresent = configurationPresent | hasSecurityTokenFile
info.SecurityTokenFilePath = value
case "delegation_token_file":
configurationPresent = configurationPresent | hasDelegationTokenFile
info.DelegationTokenFilePath = value
case "authentication_type":
configurationPresent = configurationPresent | hasAuthenticationType
info.AuthenticationType = value
}
}
info.PresentConfiguration = configurationPresent
return
}
// cleans and expands the path if it contains a tilde , returns the expanded path or the input path as is if not expansion
// was performed
func expandPath(filepath string) (expandedPath string) {
cleanedPath := path.Clean(filepath)
expandedPath = cleanedPath
if strings.HasPrefix(cleanedPath, "~") {
rest := cleanedPath[2:]
expandedPath = path.Join(getHomeFolder(), rest)
}
return
}
func openConfigFile(configFilePath string) (data []byte, err error) {
expandedPath := expandPath(configFilePath)
data, err = ioutil.ReadFile(expandedPath)
if err != nil {
err = fmt.Errorf("can not read config file: %s due to: %s", configFilePath, err.Error())
}
return
}
func (p fileConfigurationProvider) String() string {
return fmt.Sprintf("Configuration provided by file: %s", p.ConfigPath)
}
func (p fileConfigurationProvider) readAndParseConfigFile() (info *configFileInfo, err error) {
if p.FileInfo != nil {
return p.FileInfo, nil
}
if p.ConfigPath == "" {
return nil, fmt.Errorf("configuration path can not be empty")
}
data, err := openConfigFile(p.ConfigPath)
if err != nil {
err = fmt.Errorf("error while parsing config file: %s. Due to: %s", p.ConfigPath, err.Error())
return
}
p.FileInfo, err = parseConfigFile(data, p.Profile)
return p.FileInfo, err
}
func presentOrError(value string, expectedConf, presentConf rune, confMissing string) (string, error) {
if presentConf&expectedConf == expectedConf {
return value, nil
}
return "", errors.New(confMissing + " configuration is missing from file")
}
func (p fileConfigurationProvider) TenancyOCID() (value string, err error) {
info, err := p.readAndParseConfigFile()
if err != nil {
err = fmt.Errorf("can not read tenancy configuration due to: %s", err.Error())
return
}
value, err = presentOrError(info.TenancyOcid, hasTenancy, info.PresentConfiguration, "tenancy")
return
}
func (p fileConfigurationProvider) UserOCID() (value string, err error) {
info, err := p.readAndParseConfigFile()
if err != nil {
err = fmt.Errorf("can not read tenancy configuration due to: %s", err.Error())
return
}
if value, err = presentOrError(info.UserOcid, hasUser, info.PresentConfiguration, "user"); err != nil {
// need to check if securityTokenPath is provided, if security token is provided, userOCID can be "".
if _, stErr := presentOrError(info.SecurityTokenFilePath, hasSecurityTokenFile, info.PresentConfiguration,
"securityTokenPath"); stErr == nil {
err = nil
}
}
return
}
func (p fileConfigurationProvider) KeyFingerprint() (value string, err error) {
info, err := p.readAndParseConfigFile()
if err != nil {
err = fmt.Errorf("can not read tenancy configuration due to: %s", err.Error())
return
}
value, err = presentOrError(info.Fingerprint, hasFingerprint, info.PresentConfiguration, "fingerprint")
return
}
func (p fileConfigurationProvider) KeyID() (keyID string, err error) {
info, err := p.readAndParseConfigFile()
if err != nil {
err = fmt.Errorf("can not read tenancy configuration due to: %s", err.Error())
return
}
if info.PresentConfiguration&hasUser == hasUser {
return fmt.Sprintf("%s/%s/%s", info.TenancyOcid, info.UserOcid, info.Fingerprint), nil
}
if filePath, err := presentOrError(info.SecurityTokenFilePath, hasSecurityTokenFile, info.PresentConfiguration, "securityTokenFilePath"); err == nil {
rawString, err := getTokenContent(filePath)
if err != nil {
return "", err
}
return "ST$" + rawString, nil
}
err = fmt.Errorf("can not read SecurityTokenFilePath from configuration file due to: %s", err.Error())
return
}
func (p fileConfigurationProvider) PrivateRSAKey() (key *rsa.PrivateKey, err error) {
info, err := p.readAndParseConfigFile()
if err != nil {
err = fmt.Errorf("can not read tenancy configuration due to: %s", err.Error())
return
}
filePath, err := presentOrError(info.KeyFilePath, hasKeyFile, info.PresentConfiguration, "key file path")
if err != nil {
return
}
expandedPath := expandPath(filePath)
pemFileContent, err := ioutil.ReadFile(expandedPath)
if err != nil {
err = fmt.Errorf("can not read PrivateKey from configuration file due to: %s", err.Error())
return
}
password := p.PrivateKeyPassword
if password == "" && ((info.PresentConfiguration & hasPassphrase) == hasPassphrase) {
password = info.Passphrase
}
key, err = PrivateKeyFromBytes(pemFileContent, &password)
return
}
func (p fileConfigurationProvider) Region() (value string, err error) {
info, err := p.readAndParseConfigFile()
if err != nil {
err = fmt.Errorf("can not read region configuration due to: %s", err.Error())
return
}
value, err = presentOrError(info.Region, hasRegion, info.PresentConfiguration, "region")
if err != nil {
val, error := getRegionFromEnvVar()
if error != nil {
err = fmt.Errorf("region configuration is missing from file, nor for OCI_REGION env var")
return
}
value = val
}
return canStringBeRegion(value)
}
func (p fileConfigurationProvider) AuthType() (AuthConfig, error) {
info, err := p.readAndParseConfigFile()
if err != nil {
err = fmt.Errorf("can not read tenancy configuration due to: %s", err.Error())
return AuthConfig{UnknownAuthenticationType, true, nil}, err
}
val, err := presentOrError(info.AuthenticationType, hasAuthenticationType, info.PresentConfiguration, "authentication_type")
if val == "instance_principal" {
if filePath, err := presentOrError(info.DelegationTokenFilePath, hasDelegationTokenFile, info.PresentConfiguration, "delegationTokenFilePath"); err == nil {
if delegationToken, err := getTokenContent(filePath); err == nil && delegationToken != "" {
Debugf("delegation token content is %s, and error is %s ", delegationToken, err)
return AuthConfig{InstancePrincipalDelegationToken, true, &delegationToken}, nil
}
return AuthConfig{UnknownAuthenticationType, true, nil}, err
}
// normal instance principle
return AuthConfig{InstancePrincipal, true, nil}, nil
}
// by default, if no "authentication_type" is provided, just treated as user principle type, and will not return error
return AuthConfig{UserPrincipal, true, nil}, nil
}
func getTokenContent(filePath string) (string, error) {
expandedPath := expandPath(filePath)
tokenFileContent, err := ioutil.ReadFile(expandedPath)
if err != nil {
err = fmt.Errorf("can not read token content from configuration file due to: %s", err.Error())
return "", err
}
return fmt.Sprintf("%s", tokenFileContent), nil
}
// A configuration provider that look for information in multiple configuration providers
type composingConfigurationProvider struct {
Providers []ConfigurationProvider
}
// ComposingConfigurationProvider creates a composing configuration provider with the given slice of configuration providers
// A composing provider will return the configuration of the first provider that has the required property
// if no provider has the property it will return an error.
func ComposingConfigurationProvider(providers []ConfigurationProvider) (ConfigurationProvider, error) {
if len(providers) == 0 {
return nil, fmt.Errorf("providers can not be an empty slice")
}
for i, p := range providers {
if p == nil {
return nil, fmt.Errorf("provider in position: %d is nil. ComposingConfiurationProvider does not support nil values", i)
}
}
return composingConfigurationProvider{Providers: providers}, nil
}
func (c composingConfigurationProvider) TenancyOCID() (string, error) {
for _, p := range c.Providers {
val, err := p.TenancyOCID()
if err == nil {
return val, nil
}
}
return "", fmt.Errorf("did not find a proper configuration for tenancy")
}
func (c composingConfigurationProvider) UserOCID() (string, error) {
for _, p := range c.Providers {
val, err := p.UserOCID()
if err == nil {
return val, nil
}
}
return "", fmt.Errorf("did not find a proper configuration for user")
}
func (c composingConfigurationProvider) KeyFingerprint() (string, error) {
for _, p := range c.Providers {
val, err := p.KeyFingerprint()
if err == nil {
return val, nil
}
}
return "", fmt.Errorf("did not find a proper configuration for keyFingerprint")
}
func (c composingConfigurationProvider) Region() (string, error) {
for _, p := range c.Providers {
val, err := p.Region()
if err == nil {
return val, nil
}
}
if val, err := getRegionFromEnvVar(); err == nil {
return val, nil
}
return "", fmt.Errorf("did not find a proper configuration for region, nor for OCI_REGION env var")
}
func (c composingConfigurationProvider) KeyID() (string, error) {
for _, p := range c.Providers {
val, err := p.KeyID()
if err == nil {
return val, nil
}
}
return "", fmt.Errorf("did not find a proper configuration for key id")
}
func (c composingConfigurationProvider) PrivateRSAKey() (*rsa.PrivateKey, error) {
for _, p := range c.Providers {
val, err := p.PrivateRSAKey()
if err == nil {
return val, nil
}
}
return nil, fmt.Errorf("did not find a proper configuration for private key")
}
func (c composingConfigurationProvider) AuthType() (AuthConfig, error) {
// only check the first default fileConfigProvider
authConfig, err := c.Providers[0].AuthType()
if err == nil && authConfig.AuthType != UnknownAuthenticationType {
return authConfig, nil
}
return AuthConfig{UnknownAuthenticationType, false, nil}, fmt.Errorf("did not find a proper configuration for auth type")
}
func getRegionFromEnvVar() (string, error) {
regionEnvVar := "OCI_REGION"
if region, existed := os.LookupEnv(regionEnvVar); existed {
return region, nil
}
return "", fmt.Errorf("did not find OCI_REGION env var")
}

View file

@ -0,0 +1,136 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
package common
import (
"encoding/json"
"fmt"
"github.com/sony/gobreaker"
"io/ioutil"
"net"
"net/http"
)
// ServiceError models all potential errors generated the service call
type ServiceError interface {
// The http status code of the error
GetHTTPStatusCode() int
// The human-readable error string as sent by the service
GetMessage() string
// A short error code that defines the error, meant for programmatic parsing.
// See https://docs.cloud.oracle.com/Content/API/References/apierrors.htm
GetCode() string
// Unique Oracle-assigned identifier for the request.
// If you need to contact Oracle about a particular request, please provide the request ID.
GetOpcRequestID() string
}
type servicefailure struct {
StatusCode int
Code string `json:"code,omitempty"`
Message string `json:"message,omitempty"`
OpcRequestID string `json:"opc-request-id"`
}
func newServiceFailureFromResponse(response *http.Response) error {
var err error
se := servicefailure{
StatusCode: response.StatusCode,
Code: "BadErrorResponse",
OpcRequestID: response.Header.Get("opc-request-id")}
//If there is an error consume the body, entirely
body, err := ioutil.ReadAll(response.Body)
if err != nil {
se.Message = fmt.Sprintf("The body of the response was not readable, due to :%s", err.Error())
return se
}
err = json.Unmarshal(body, &se)
if err != nil {
Debugf("Error response could not be parsed due to: %s", err.Error())
se.Message = fmt.Sprintf("Failed to parse json from response body due to: %s. With response body %s.", err.Error(), string(body[:]))
return se
}
return se
}
func (se servicefailure) Error() string {
return fmt.Sprintf("Service error:%s. %s. http status code: %d. Opc request id: %s",
se.Code, se.Message, se.StatusCode, se.OpcRequestID)
}
func (se servicefailure) GetHTTPStatusCode() int {
return se.StatusCode
}
func (se servicefailure) GetMessage() string {
return se.Message
}
func (se servicefailure) GetCode() string {
return se.Code
}
func (se servicefailure) GetOpcRequestID() string {
return se.OpcRequestID
}
// IsServiceError returns false if the error is not service side, otherwise true
// additionally it returns an interface representing the ServiceError
func IsServiceError(err error) (failure ServiceError, ok bool) {
failure, ok = err.(servicefailure)
return
}
type deadlineExceededByBackoffError struct{}
func (deadlineExceededByBackoffError) Error() string {
return "now() + computed backoff duration exceeds request deadline"
}
// DeadlineExceededByBackoff is the error returned by Call() when GetNextDuration() returns a time.Duration that would
// force the user to wait past the request deadline before re-issuing a request. This enables us to exit early, since
// we cannot succeed based on the configured retry policy.
var DeadlineExceededByBackoff error = deadlineExceededByBackoffError{}
// NonSeekableRequestRetryFailure is the error returned when the request is with binary request body, and is configured
// retry, but the request body is not retryable
type NonSeekableRequestRetryFailure struct {
err error
}
func (ne NonSeekableRequestRetryFailure) Error() string {
if ne.err == nil {
return fmt.Sprintf("Unable to perform Retry on this request body type, which did not implement seek() interface")
}
return fmt.Sprintf("%s. Unable to perform Retry on this request body type, which did not implement seek() interface", ne.err.Error())
}
// IsNetworkError validates if an error is a net.Error and check if it's temporary or timeout
func IsNetworkError(err error) bool {
if r, ok := err.(net.Error); ok && (r.Temporary() || r.Timeout()) {
return true
}
return false
}
// IsCircuitBreakerError validates if an error's text is Open state ErrOpenState or HalfOpen state ErrTooManyRequests
func IsCircuitBreakerError(err error) bool {
if err.Error() == gobreaker.ErrOpenState.Error() || err.Error() == gobreaker.ErrTooManyRequests.Error() {
return true
}
return false
}
// StatErrCode is a type which wraps error's statusCode and errorCode from service end
type StatErrCode struct {
statusCode int
errorCode string
}

View file

@ -0,0 +1,298 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
package common
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"fmt"
"net/textproto"
"os"
"reflect"
"strconv"
"strings"
"time"
)
// String returns a pointer to the provided string
func String(value string) *string {
return &value
}
// Int returns a pointer to the provided int
func Int(value int) *int {
return &value
}
// Int64 returns a pointer to the provided int64
func Int64(value int64) *int64 {
return &value
}
// Uint returns a pointer to the provided uint
func Uint(value uint) *uint {
return &value
}
//Float32 returns a pointer to the provided float32
func Float32(value float32) *float32 {
return &value
}
//Float64 returns a pointer to the provided float64
func Float64(value float64) *float64 {
return &value
}
//Bool returns a pointer to the provided bool
func Bool(value bool) *bool {
return &value
}
//PointerString prints the values of pointers in a struct
//Producing a human friendly string for an struct with pointers.
//useful when debugging the values of a struct
func PointerString(datastruct interface{}) (representation string) {
val := reflect.ValueOf(datastruct)
typ := reflect.TypeOf(datastruct)
all := make([]string, 2)
all = append(all, "{")
for i := 0; i < typ.NumField(); i++ {
sf := typ.Field(i)
//unexported
if sf.PkgPath != "" && !sf.Anonymous {
continue
}
sv := val.Field(i)
stringValue := ""
if isNil(sv) {
stringValue = fmt.Sprintf("%s=<nil>", sf.Name)
} else {
if sv.Type().Kind() == reflect.Ptr {
sv = sv.Elem()
}
stringValue = fmt.Sprintf("%s=%v", sf.Name, sv)
}
all = append(all, stringValue)
}
all = append(all, "}")
representation = strings.TrimSpace(strings.Join(all, " "))
return
}
// SDKTime a struct that parses/renders to/from json using RFC339 date-time information
type SDKTime struct {
time.Time
}
// SDKDate a struct that parses/renders to/from json using only date information
type SDKDate struct {
//Date date information
Date time.Time
}
func sdkTimeFromTime(t time.Time) SDKTime {
return SDKTime{t}
}
func sdkDateFromTime(t time.Time) SDKDate {
return SDKDate{Date: t}
}
func formatTime(t SDKTime) string {
return t.Format(sdkTimeFormat)
}
func formatDate(t SDKDate) string {
return t.Date.Format(sdkDateFormat)
}
func now() *SDKTime {
t := SDKTime{time.Now()}
return &t
}
var timeType = reflect.TypeOf(SDKTime{})
var timeTypePtr = reflect.TypeOf(&SDKTime{})
var sdkDateType = reflect.TypeOf(SDKDate{})
var sdkDateTypePtr = reflect.TypeOf(&SDKDate{})
//Formats for sdk supported time representations
const sdkTimeFormat = time.RFC3339Nano
const rfc1123OptionalLeadingDigitsInDay = "Mon, _2 Jan 2006 15:04:05 MST"
const sdkDateFormat = "2006-01-02"
func tryParsingTimeWithValidFormatsForHeaders(data []byte, headerName string) (t time.Time, err error) {
header := strings.ToLower(headerName)
switch header {
case "lastmodified", "date":
t, err = tryParsing(data, time.RFC3339Nano, time.RFC3339, time.RFC1123, rfc1123OptionalLeadingDigitsInDay, time.RFC850, time.ANSIC)
return
default: //By default we parse with RFC3339
t, err = time.Parse(sdkTimeFormat, string(data))
return
}
}
func tryParsing(data []byte, layouts ...string) (tm time.Time, err error) {
datestring := string(data)
for _, l := range layouts {
tm, err = time.Parse(l, datestring)
if err == nil {
return
}
}
err = fmt.Errorf("Could not parse time: %s with formats: %s", datestring, layouts[:])
return
}
// String returns string representation of SDKDate
func (t *SDKDate) String() string {
return t.Date.Format(sdkDateFormat)
}
// NewSDKDateFromString parses the dateString into SDKDate
func NewSDKDateFromString(dateString string) (*SDKDate, error) {
parsedTime, err := time.Parse(sdkDateFormat, dateString)
if err != nil {
return nil, err
}
return &SDKDate{Date: parsedTime}, nil
}
// UnmarshalJSON unmarshals from json
func (t *SDKTime) UnmarshalJSON(data []byte) (e error) {
s := string(data)
if s == "null" {
t.Time = time.Time{}
} else {
//Try parsing with RFC3339
t.Time, e = time.Parse(`"`+sdkTimeFormat+`"`, string(data))
}
return
}
// MarshalJSON marshals to JSON
func (t *SDKTime) MarshalJSON() (buff []byte, e error) {
s := t.Format(sdkTimeFormat)
buff = []byte(`"` + s + `"`)
return
}
// UnmarshalJSON unmarshals from json
func (t *SDKDate) UnmarshalJSON(data []byte) (e error) {
if string(data) == `"null"` {
t.Date = time.Time{}
return
}
t.Date, e = tryParsing(data,
strconv.Quote(sdkDateFormat),
)
return
}
// MarshalJSON marshals to JSON
func (t *SDKDate) MarshalJSON() (buff []byte, e error) {
s := t.Date.Format(sdkDateFormat)
buff = []byte(strconv.Quote(s))
return
}
// PrivateKeyFromBytes is a helper function that will produce a RSA private
// key from bytes. This function is deprecated in favour of PrivateKeyFromBytesWithPassword
// Deprecated
func PrivateKeyFromBytes(pemData []byte, password *string) (key *rsa.PrivateKey, e error) {
if password == nil {
return PrivateKeyFromBytesWithPassword(pemData, nil)
}
return PrivateKeyFromBytesWithPassword(pemData, []byte(*password))
}
// PrivateKeyFromBytesWithPassword is a helper function that will produce a RSA private
// key from bytes and a password.
func PrivateKeyFromBytesWithPassword(pemData, password []byte) (key *rsa.PrivateKey, e error) {
if pemBlock, _ := pem.Decode(pemData); pemBlock != nil {
decrypted := pemBlock.Bytes
if x509.IsEncryptedPEMBlock(pemBlock) {
if password == nil {
e = fmt.Errorf("private key password is required for encrypted private keys")
return
}
if decrypted, e = x509.DecryptPEMBlock(pemBlock, password); e != nil {
return
}
}
key, e = parsePKCSPrivateKey(decrypted)
} else {
e = fmt.Errorf("PEM data was not found in buffer")
return
}
return
}
// ParsePrivateKey using PKCS1 or PKCS8
func parsePKCSPrivateKey(decryptedKey []byte) (*rsa.PrivateKey, error) {
if key, err := x509.ParsePKCS1PrivateKey(decryptedKey); err == nil {
return key, nil
}
if key, err := x509.ParsePKCS8PrivateKey(decryptedKey); err == nil {
switch key := key.(type) {
case *rsa.PrivateKey:
return key, nil
default:
return nil, fmt.Errorf("unsupportesd private key type in PKCS8 wrapping")
}
}
return nil, fmt.Errorf("failed to parse private key")
}
// parseContentLength trims whitespace from cl and returns -1 if can't purse uint, or the value if it's no less than 0
func parseContentLength(cl string) int64 {
cl = textproto.TrimString(cl)
n, err := strconv.ParseUint(cl, 10, 63)
if err != nil {
return -1
}
return int64(n)
}
func generateRandUUID() (string, error) {
b := make([]byte, 16)
_, err := rand.Read(b)
if err != nil {
return "", err
}
uuid := fmt.Sprintf("%x%x%x%x%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:])
return uuid, nil
}
func makeACopy(original []string) []string {
tmp := make([]string, len(original))
copy(tmp, original)
return tmp
}
// IsEnvVarFalse is used for checking if an environment variable is explicitly set to false, otherwise would set it true by default
func IsEnvVarFalse(envVarKey string) bool {
return false
val, existed := os.LookupEnv(envVarKey)
return existed && strings.ToLower(val) == "false"
}
// IsEnvVarTrue is used for checking if an environment variable is explicitly set to true, otherwise would set it true by default
func IsEnvVarTrue(envVarKey string) bool {
val, existed := os.LookupEnv(envVarKey)
return existed && strings.ToLower(val) == "true"
}

1070
vendor/github.com/oracle/oci-go-sdk/v54/common/http.go generated vendored Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,270 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
package common
import (
"bytes"
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"encoding/base64"
"fmt"
"io"
"io/ioutil"
"net/http"
"strings"
)
// HTTPRequestSigner the interface to sign a request
type HTTPRequestSigner interface {
Sign(r *http.Request) error
}
// KeyProvider interface that wraps information about the key's account owner
type KeyProvider interface {
PrivateRSAKey() (*rsa.PrivateKey, error)
KeyID() (string, error)
}
const signerVersion = "1"
// SignerBodyHashPredicate a function that allows to disable/enable body hashing
// of requests and headers associated with body content
type SignerBodyHashPredicate func(r *http.Request) bool
// ociRequestSigner implements the http-signatures-draft spec
// as described in https://tools.ietf.org/html/draft-cavage-http-signatures-08
type ociRequestSigner struct {
KeyProvider KeyProvider
GenericHeaders []string
BodyHeaders []string
ShouldHashBody SignerBodyHashPredicate
}
var (
defaultGenericHeaders = []string{"date", "(request-target)", "host"}
defaultBodyHeaders = []string{"content-length", "content-type", "x-content-sha256"}
defaultBodyHashPredicate = func(r *http.Request) bool {
return r.Method == http.MethodPost || r.Method == http.MethodPut || r.Method == http.MethodPatch
}
)
// DefaultGenericHeaders list of default generic headers that is used in signing
func DefaultGenericHeaders() []string {
return makeACopy(defaultGenericHeaders)
}
// DefaultBodyHeaders list of default body headers that is used in signing
func DefaultBodyHeaders() []string {
return makeACopy(defaultBodyHeaders)
}
// DefaultRequestSigner creates a signer with default parameters.
func DefaultRequestSigner(provider KeyProvider) HTTPRequestSigner {
return RequestSigner(provider, defaultGenericHeaders, defaultBodyHeaders)
}
// RequestSignerExcludeBody creates a signer without hash the body.
func RequestSignerExcludeBody(provider KeyProvider) HTTPRequestSigner {
bodyHashPredicate := func(r *http.Request) bool {
// week request signer will not hash the body
return false
}
return RequestSignerWithBodyHashingPredicate(provider, defaultGenericHeaders, defaultBodyHeaders, bodyHashPredicate)
}
// NewSignerFromOCIRequestSigner creates a copy of the request signer and attaches the new SignerBodyHashPredicate
// returns an error if the passed signer is not of type ociRequestSigner
func NewSignerFromOCIRequestSigner(oldSigner HTTPRequestSigner, predicate SignerBodyHashPredicate) (HTTPRequestSigner, error) {
if oldS, ok := oldSigner.(ociRequestSigner); ok {
s := ociRequestSigner{
KeyProvider: oldS.KeyProvider,
GenericHeaders: oldS.GenericHeaders,
BodyHeaders: oldS.BodyHeaders,
ShouldHashBody: predicate,
}
return s, nil
}
return nil, fmt.Errorf("can not create a signer, input signer needs to be of type ociRequestSigner")
}
// RequestSigner creates a signer that utilizes the specified headers for signing
// and the default predicate for using the body of the request as part of the signature
func RequestSigner(provider KeyProvider, genericHeaders, bodyHeaders []string) HTTPRequestSigner {
return ociRequestSigner{
KeyProvider: provider,
GenericHeaders: genericHeaders,
BodyHeaders: bodyHeaders,
ShouldHashBody: defaultBodyHashPredicate}
}
// RequestSignerWithBodyHashingPredicate creates a signer that utilizes the specified headers for signing, as well as a predicate for using
// the body of the request and bodyHeaders parameter as part of the signature
func RequestSignerWithBodyHashingPredicate(provider KeyProvider, genericHeaders, bodyHeaders []string, shouldHashBody SignerBodyHashPredicate) HTTPRequestSigner {
return ociRequestSigner{
KeyProvider: provider,
GenericHeaders: genericHeaders,
BodyHeaders: bodyHeaders,
ShouldHashBody: shouldHashBody}
}
func (signer ociRequestSigner) getSigningHeaders(r *http.Request) []string {
var result []string
result = append(result, signer.GenericHeaders...)
if signer.ShouldHashBody(r) {
result = append(result, signer.BodyHeaders...)
}
return result
}
func (signer ociRequestSigner) getSigningString(request *http.Request) string {
signingHeaders := signer.getSigningHeaders(request)
signingParts := make([]string, len(signingHeaders))
for i, part := range signingHeaders {
var value string
part = strings.ToLower(part)
switch part {
case "(request-target)":
value = getRequestTarget(request)
case "host":
value = request.URL.Host
if len(value) == 0 {
value = request.Host
}
default:
value = request.Header.Get(part)
}
signingParts[i] = fmt.Sprintf("%s: %s", part, value)
}
signingString := strings.Join(signingParts, "\n")
return signingString
}
func getRequestTarget(request *http.Request) string {
lowercaseMethod := strings.ToLower(request.Method)
return fmt.Sprintf("%s %s", lowercaseMethod, request.URL.RequestURI())
}
func calculateHashOfBody(request *http.Request) (err error) {
var hash string
hash, err = GetBodyHash(request)
if err != nil {
return
}
request.Header.Set(requestHeaderXContentSHA256, hash)
return
}
// drainBody reads all of b to memory and then returns two equivalent
// ReadClosers yielding the same bytes.
//
// It returns an error if the initial slurp of all bytes fails. It does not attempt
// to make the returned ReadClosers have identical error-matching behavior.
func drainBody(b io.ReadCloser) (r1, r2 io.ReadCloser, err error) {
if b == http.NoBody {
// No copying needed. Preserve the magic sentinel meaning of NoBody.
return http.NoBody, http.NoBody, nil
}
var buf bytes.Buffer
if _, err = buf.ReadFrom(b); err != nil {
return nil, b, err
}
if err = b.Close(); err != nil {
return nil, b, err
}
return ioutil.NopCloser(&buf), ioutil.NopCloser(bytes.NewReader(buf.Bytes())), nil
}
func hashAndEncode(data []byte) string {
hashedContent := sha256.Sum256(data)
hash := base64.StdEncoding.EncodeToString(hashedContent[:])
return hash
}
// GetBodyHash creates a base64 string from the hash of body the request
func GetBodyHash(request *http.Request) (hashString string, err error) {
if request.Body == nil {
request.ContentLength = 0
request.Header.Set(requestHeaderContentLength, fmt.Sprintf("%v", request.ContentLength))
return hashAndEncode([]byte("")), nil
}
var data []byte
bReader := request.Body
bReader, request.Body, err = drainBody(request.Body)
if err != nil {
return "", fmt.Errorf("can not read body of request while calculating body hash: %s", err.Error())
}
data, err = ioutil.ReadAll(bReader)
if err != nil {
return "", fmt.Errorf("can not read body of request while calculating body hash: %s", err.Error())
}
// Since the request can be coming from a binary body. Make an attempt to set the body length
request.ContentLength = int64(len(data))
request.Header.Set(requestHeaderContentLength, fmt.Sprintf("%v", request.ContentLength))
hashString = hashAndEncode(data)
return
}
func (signer ociRequestSigner) computeSignature(request *http.Request) (signature string, err error) {
signingString := signer.getSigningString(request)
hasher := sha256.New()
hasher.Write([]byte(signingString))
hashed := hasher.Sum(nil)
privateKey, err := signer.KeyProvider.PrivateRSAKey()
if err != nil {
return
}
var unencodedSig []byte
unencodedSig, e := rsa.SignPKCS1v15(rand.Reader, privateKey, crypto.SHA256, hashed)
if e != nil {
err = fmt.Errorf("can not compute signature while signing the request %s: ", e.Error())
return
}
signature = base64.StdEncoding.EncodeToString(unencodedSig)
return
}
// Sign signs the http request, by inspecting the necessary headers. Once signed
// the request will have the proper 'Authorization' header set, otherwise
// and error is returned
func (signer ociRequestSigner) Sign(request *http.Request) (err error) {
if signer.ShouldHashBody(request) {
err = calculateHashOfBody(request)
if err != nil {
return
}
}
var signature string
if signature, err = signer.computeSignature(request); err != nil {
return
}
signingHeaders := strings.Join(signer.getSigningHeaders(request), " ")
var keyID string
if keyID, err = signer.KeyProvider.KeyID(); err != nil {
return
}
authValue := fmt.Sprintf("Signature version=\"%s\",headers=\"%s\",keyId=\"%s\",algorithm=\"rsa-sha256\",signature=\"%s\"",
signerVersion, signingHeaders, keyID, signature)
request.Header.Set(requestHeaderAuthorization, authValue)
return
}

230
vendor/github.com/oracle/oci-go-sdk/v54/common/log.go generated vendored Normal file
View file

@ -0,0 +1,230 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
package common
import (
"fmt"
"io"
"io/ioutil"
"log"
"os"
"strings"
"sync"
"time"
)
//sdkLogger an interface for logging in the SDK
type sdkLogger interface {
//LogLevel returns the log level of sdkLogger
LogLevel() int
//Log logs v with the provided format if the current log level is loglevel
Log(logLevel int, format string, v ...interface{}) error
}
//noLogging no logging messages
const noLogging = 0
//infoLogging minimal logging messages
const infoLogging = 1
//debugLogging some logging messages
const debugLogging = 2
//verboseLogging all logging messages
const verboseLogging = 3
//defaultSDKLogger the default implementation of the sdkLogger
type defaultSDKLogger struct {
currentLoggingLevel int
verboseLogger *log.Logger
debugLogger *log.Logger
infoLogger *log.Logger
nullLogger *log.Logger
}
//defaultLogger is the defaultLogger in the SDK
var defaultLogger sdkLogger
var loggerLock sync.Mutex
var file *os.File
//initializes the SDK defaultLogger as a defaultLogger
func init() {
l, _ := newSDKLogger()
setSDKLogger(l)
}
//setSDKLogger sets the logger used by the sdk
func setSDKLogger(logger sdkLogger) {
loggerLock.Lock()
defaultLogger = logger
loggerLock.Unlock()
}
// newSDKLogger creates a defaultSDKLogger
// Debug logging is turned on/off by the presence of the environment variable "OCI_GO_SDK_DEBUG"
// The value of the "OCI_GO_SDK_DEBUG" environment variable controls the logging level.
// "null" outputs no log messages
// "i" or "info" outputs minimal log messages
// "d" or "debug" outputs some logs messages
// "v" or "verbose" outputs all logs messages, including body of requests
func newSDKLogger() (defaultSDKLogger, error) {
logger := defaultSDKLogger{}
logger.currentLoggingLevel = noLogging
logger.verboseLogger = log.New(os.Stderr, "VERBOSE ", log.Ldate|log.Lmicroseconds|log.Lshortfile)
logger.debugLogger = log.New(os.Stderr, "DEBUG ", log.Ldate|log.Lmicroseconds|log.Lshortfile)
logger.infoLogger = log.New(os.Stderr, "INFO ", log.Ldate|log.Lmicroseconds|log.Lshortfile)
logger.nullLogger = log.New(ioutil.Discard, "", log.Ldate|log.Lmicroseconds|log.Lshortfile)
configured, isLogEnabled := os.LookupEnv("OCI_GO_SDK_DEBUG")
// If env variable not present turn logging off
if !isLogEnabled {
logger.currentLoggingLevel = noLogging
} else {
logOutputModeConfig(logger)
switch strings.ToLower(configured) {
case "null":
logger.currentLoggingLevel = noLogging
break
case "i", "info":
logger.currentLoggingLevel = infoLogging
break
case "d", "debug":
logger.currentLoggingLevel = debugLogging
break
//1 here for backwards compatibility
case "v", "verbose", "1":
logger.currentLoggingLevel = verboseLogging
break
default:
logger.currentLoggingLevel = infoLogging
}
logger.infoLogger.Println("logger level set to: ", logger.currentLoggingLevel)
}
return logger, nil
}
func (l defaultSDKLogger) getLoggerForLevel(logLevel int) *log.Logger {
if logLevel > l.currentLoggingLevel {
return l.nullLogger
}
switch logLevel {
case noLogging:
return l.nullLogger
case infoLogging:
return l.infoLogger
case debugLogging:
return l.debugLogger
case verboseLogging:
return l.verboseLogger
default:
return l.nullLogger
}
}
// Set SDK Log output mode
// Output mode is switched based on environment variable "OCI_GO_SDK_LOG_OUPUT_MODE"
// "file" outputs log to a specific file
// "combine" outputs log to both stderr and specific file
// other unsupported value outputs log to stderr
// output file can be set via environment variable "OCI_GO_SDK_LOG_FILE"
// if this environment variable is not set, a default log file will be created under project root path
func logOutputModeConfig(logger defaultSDKLogger) {
logMode, isLogOutputModeEnabled := os.LookupEnv("OCI_GO_SDK_LOG_OUTPUT_MODE")
if !isLogOutputModeEnabled {
return
}
fileName, isLogFileNameProvided := os.LookupEnv("OCI_GO_SDK_LOG_FILE")
if !isLogFileNameProvided {
fileName = fmt.Sprintf("logging_%v%s", time.Now().Unix(), ".log")
}
switch strings.ToLower(logMode) {
case "file", "f":
file = openLogOutputFile(logger, fileName)
logger.infoLogger.SetOutput(file)
logger.debugLogger.SetOutput(file)
logger.verboseLogger.SetOutput(file)
break
case "combine", "c":
file = openLogOutputFile(logger, fileName)
wrt := io.MultiWriter(os.Stderr, file)
logger.infoLogger.SetOutput(wrt)
logger.debugLogger.SetOutput(wrt)
logger.verboseLogger.SetOutput(wrt)
break
}
}
func openLogOutputFile(logger defaultSDKLogger, fileName string) *os.File {
file, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
if err != nil {
logger.verboseLogger.Fatal(err)
}
return file
}
//CloseLogFile close the logging file and return error
func CloseLogFile() error {
return file.Close()
}
//LogLevel returns the current debug level
func (l defaultSDKLogger) LogLevel() int {
return l.currentLoggingLevel
}
func (l defaultSDKLogger) Log(logLevel int, format string, v ...interface{}) error {
logger := l.getLoggerForLevel(logLevel)
logger.Output(4, fmt.Sprintf(format, v...))
return nil
}
//Logln logs v appending a new line at the end
//Deprecated
func Logln(v ...interface{}) {
defaultLogger.Log(infoLogging, "%v\n", v...)
}
// Logf logs v with the provided format
func Logf(format string, v ...interface{}) {
defaultLogger.Log(infoLogging, format, v...)
}
// Debugf logs v with the provided format if debug mode is set
func Debugf(format string, v ...interface{}) {
defaultLogger.Log(debugLogging, format, v...)
}
// Debug logs v if debug mode is set
func Debug(v ...interface{}) {
m := fmt.Sprint(v...)
defaultLogger.Log(debugLogging, "%s", m)
}
// Debugln logs v appending a new line if debug mode is set
func Debugln(v ...interface{}) {
m := fmt.Sprint(v...)
defaultLogger.Log(debugLogging, "%s\n", m)
}
// IfDebug executes closure if debug is enabled
func IfDebug(fn func()) {
if defaultLogger.LogLevel() >= debugLogging {
fn()
}
}
// IfInfo executes closure if info is enabled
func IfInfo(fn func()) {
if defaultLogger.LogLevel() >= infoLogging {
fn()
}
}

View file

@ -0,0 +1,173 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
package common
const (
//RegionAPChuncheon1 region Chuncheon
RegionAPChuncheon1 Region = "ap-chuncheon-1"
//RegionAPHyderabad1 region Hyderabad
RegionAPHyderabad1 Region = "ap-hyderabad-1"
//RegionAPMelbourne1 region Melbourne
RegionAPMelbourne1 Region = "ap-melbourne-1"
//RegionAPMumbai1 region Mumbai
RegionAPMumbai1 Region = "ap-mumbai-1"
//RegionAPOsaka1 region Osaka
RegionAPOsaka1 Region = "ap-osaka-1"
//RegionAPSeoul1 region Seoul
RegionAPSeoul1 Region = "ap-seoul-1"
//RegionAPSydney1 region Sydney
RegionAPSydney1 Region = "ap-sydney-1"
//RegionAPTokyo1 region Tokyo
RegionAPTokyo1 Region = "ap-tokyo-1"
//RegionCAMontreal1 region Montreal
RegionCAMontreal1 Region = "ca-montreal-1"
//RegionCAToronto1 region Toronto
RegionCAToronto1 Region = "ca-toronto-1"
//RegionEUAmsterdam1 region Amsterdam
RegionEUAmsterdam1 Region = "eu-amsterdam-1"
//RegionFRA region Frankfurt
RegionFRA Region = "eu-frankfurt-1"
//RegionEUZurich1 region Zurich
RegionEUZurich1 Region = "eu-zurich-1"
//RegionMEJeddah1 region Jeddah
RegionMEJeddah1 Region = "me-jeddah-1"
//RegionMEDubai1 region Dubai
RegionMEDubai1 Region = "me-dubai-1"
//RegionSASaopaulo1 region Saopaulo
RegionSASaopaulo1 Region = "sa-saopaulo-1"
//RegionUKCardiff1 region Cardiff
RegionUKCardiff1 Region = "uk-cardiff-1"
//RegionLHR region London
RegionLHR Region = "uk-london-1"
//RegionIAD region Ashburn
RegionIAD Region = "us-ashburn-1"
//RegionPHX region Phoenix
RegionPHX Region = "us-phoenix-1"
//RegionSJC1 region Sanjose
RegionSJC1 Region = "us-sanjose-1"
//RegionSAVinhedo1 region Vinhedo
RegionSAVinhedo1 Region = "sa-vinhedo-1"
//RegionSASantiago1 region Santiago
RegionSASantiago1 Region = "sa-santiago-1"
//RegionILJerusalem1 region Jerusalem
RegionILJerusalem1 Region = "il-jerusalem-1"
//RegionEUMarseille1 region Marseille
RegionEUMarseille1 Region = "eu-marseille-1"
//RegionAPSingapore1 region Singapore
RegionAPSingapore1 Region = "ap-singapore-1"
//RegionMEAbudhabi1 region Abudhabi
RegionMEAbudhabi1 Region = "me-abudhabi-1"
//RegionEUMilan1 region Milan
RegionEUMilan1 Region = "eu-milan-1"
//RegionUSLangley1 region Langley
RegionUSLangley1 Region = "us-langley-1"
//RegionUSLuke1 region Luke
RegionUSLuke1 Region = "us-luke-1"
//RegionUSGovAshburn1 gov region Ashburn
RegionUSGovAshburn1 Region = "us-gov-ashburn-1"
//RegionUSGovChicago1 gov region Chicago
RegionUSGovChicago1 Region = "us-gov-chicago-1"
//RegionUSGovPhoenix1 gov region Phoenix
RegionUSGovPhoenix1 Region = "us-gov-phoenix-1"
//RegionUKGovLondon1 gov region London
RegionUKGovLondon1 Region = "uk-gov-london-1"
//RegionUKGovCardiff1 gov region Cardiff
RegionUKGovCardiff1 Region = "uk-gov-cardiff-1"
//RegionAPChiyoda1 region Chiyoda
RegionAPChiyoda1 Region = "ap-chiyoda-1"
//RegionAPIbaraki1 region Ibaraki
RegionAPIbaraki1 Region = "ap-ibaraki-1"
)
var shortNameRegion = map[string]Region{
"yny": RegionAPChuncheon1,
"hyd": RegionAPHyderabad1,
"mel": RegionAPMelbourne1,
"bom": RegionAPMumbai1,
"kix": RegionAPOsaka1,
"icn": RegionAPSeoul1,
"syd": RegionAPSydney1,
"nrt": RegionAPTokyo1,
"yul": RegionCAMontreal1,
"yyz": RegionCAToronto1,
"ams": RegionEUAmsterdam1,
"fra": RegionFRA,
"zrh": RegionEUZurich1,
"jed": RegionMEJeddah1,
"dxb": RegionMEDubai1,
"gru": RegionSASaopaulo1,
"cwl": RegionUKCardiff1,
"lhr": RegionLHR,
"iad": RegionIAD,
"phx": RegionPHX,
"sjc": RegionSJC1,
"vcp": RegionSAVinhedo1,
"scl": RegionSASantiago1,
"mtz": RegionILJerusalem1,
"mrs": RegionEUMarseille1,
"sin": RegionAPSingapore1,
"auh": RegionMEAbudhabi1,
"lin": RegionEUMilan1,
"lfi": RegionUSLangley1,
"luf": RegionUSLuke1,
"ric": RegionUSGovAshburn1,
"pia": RegionUSGovChicago1,
"tus": RegionUSGovPhoenix1,
"ltn": RegionUKGovLondon1,
"brs": RegionUKGovCardiff1,
"nja": RegionAPChiyoda1,
"ukb": RegionAPIbaraki1,
}
var realm = map[string]string{
"oc1": "oraclecloud.com",
"oc2": "oraclegovcloud.com",
"oc3": "oraclegovcloud.com",
"oc4": "oraclegovcloud.uk",
"oc8": "oraclecloud8.com",
}
var regionRealm = map[Region]string{
RegionAPChuncheon1: "oc1",
RegionAPHyderabad1: "oc1",
RegionAPMelbourne1: "oc1",
RegionAPMumbai1: "oc1",
RegionAPOsaka1: "oc1",
RegionAPSeoul1: "oc1",
RegionAPSydney1: "oc1",
RegionAPTokyo1: "oc1",
RegionCAMontreal1: "oc1",
RegionCAToronto1: "oc1",
RegionEUAmsterdam1: "oc1",
RegionFRA: "oc1",
RegionEUZurich1: "oc1",
RegionMEJeddah1: "oc1",
RegionMEDubai1: "oc1",
RegionSASaopaulo1: "oc1",
RegionUKCardiff1: "oc1",
RegionLHR: "oc1",
RegionIAD: "oc1",
RegionPHX: "oc1",
RegionSJC1: "oc1",
RegionSAVinhedo1: "oc1",
RegionSASantiago1: "oc1",
RegionILJerusalem1: "oc1",
RegionEUMarseille1: "oc1",
RegionAPSingapore1: "oc1",
RegionMEAbudhabi1: "oc1",
RegionEUMilan1: "oc1",
RegionUSLangley1: "oc2",
RegionUSLuke1: "oc2",
RegionUSGovAshburn1: "oc3",
RegionUSGovChicago1: "oc3",
RegionUSGovPhoenix1: "oc3",
RegionUKGovLondon1: "oc4",
RegionUKGovCardiff1: "oc4",
RegionAPChiyoda1: "oc8",
RegionAPIbaraki1: "oc8",
}

View file

@ -0,0 +1,224 @@
[
{
"regionKey": "yny",
"realmDomainComponent": "oraclecloud.com",
"regionIdentifier": "ap-chuncheon-1",
"realmKey": "oc1"
},
{
"regionKey": "hyd",
"realmDomainComponent": "oraclecloud.com",
"regionIdentifier": "ap-hyderabad-1",
"realmKey": "oc1"
},
{
"regionKey": "mel",
"realmDomainComponent": "oraclecloud.com",
"regionIdentifier": "ap-melbourne-1",
"realmKey": "oc1"
},
{
"regionKey": "bom",
"realmDomainComponent": "oraclecloud.com",
"regionIdentifier": "ap-mumbai-1",
"realmKey": "oc1"
},
{
"regionKey": "kix",
"realmDomainComponent": "oraclecloud.com",
"regionIdentifier": "ap-osaka-1",
"realmKey": "oc1"
},
{
"regionKey": "icn",
"realmDomainComponent": "oraclecloud.com",
"regionIdentifier": "ap-seoul-1",
"realmKey": "oc1"
},
{
"regionKey": "syd",
"realmDomainComponent": "oraclecloud.com",
"regionIdentifier": "ap-sydney-1",
"realmKey": "oc1"
},
{
"regionKey": "nrt",
"realmDomainComponent": "oraclecloud.com",
"regionIdentifier": "ap-tokyo-1",
"realmKey": "oc1"
},
{
"regionKey": "yul",
"realmDomainComponent": "oraclecloud.com",
"regionIdentifier": "ca-montreal-1",
"realmKey": "oc1"
},
{
"regionKey": "yyz",
"realmDomainComponent": "oraclecloud.com",
"regionIdentifier": "ca-toronto-1",
"realmKey": "oc1"
},
{
"regionKey": "ams",
"realmDomainComponent": "oraclecloud.com",
"regionIdentifier": "eu-amsterdam-1",
"realmKey": "oc1"
},
{
"regionKey": "fra",
"realmDomainComponent": "oraclecloud.com",
"regionIdentifier": "eu-frankfurt-1",
"realmKey": "oc1"
},
{
"regionKey": "zrh",
"realmDomainComponent": "oraclecloud.com",
"regionIdentifier": "eu-zurich-1",
"realmKey": "oc1"
},
{
"regionKey": "jed",
"realmDomainComponent": "oraclecloud.com",
"regionIdentifier": "me-jeddah-1",
"realmKey": "oc1"
},
{
"regionKey": "dxb",
"realmDomainComponent": "oraclecloud.com",
"regionIdentifier": "me-dubai-1",
"realmKey": "oc1"
},
{
"regionKey": "gru",
"realmDomainComponent": "oraclecloud.com",
"regionIdentifier": "sa-saopaulo-1",
"realmKey": "oc1"
},
{
"regionKey": "cwl",
"realmDomainComponent": "oraclecloud.com",
"regionIdentifier": "uk-cardiff-1",
"realmKey": "oc1"
},
{
"regionKey": "lhr",
"realmDomainComponent": "oraclecloud.com",
"regionIdentifier": "uk-london-1",
"realmKey": "oc1"
},
{
"regionKey": "iad",
"realmDomainComponent": "oraclecloud.com",
"regionIdentifier": "us-ashburn-1",
"realmKey": "oc1"
},
{
"regionKey": "phx",
"realmDomainComponent": "oraclecloud.com",
"regionIdentifier": "us-phoenix-1",
"realmKey": "oc1"
},
{
"regionKey": "sjc",
"realmDomainComponent": "oraclecloud.com",
"regionIdentifier": "us-sanjose-1",
"realmKey": "oc1"
},
{
"regionKey": "vcp",
"realmDomainComponent": "oraclecloud.com",
"regionIdentifier": "sa-vinhedo-1",
"realmKey": "oc1"
},
{
"regionKey": "scl",
"realmDomainComponent": "oraclecloud.com",
"regionIdentifier": "sa-santiago-1",
"realmKey": "oc1"
},
{
"regionKey": "lfi",
"realmDomainComponent": "oraclegovcloud.com",
"regionIdentifier": "us-langley-1",
"realmKey": "oc2"
},
{
"regionKey": "luf",
"realmDomainComponent": "oraclegovcloud.com",
"regionIdentifier": "us-luke-1",
"realmKey": "oc2"
},
{
"regionKey": "ric",
"realmDomainComponent": "oraclegovcloud.com",
"regionIdentifier": "us-gov-ashburn-1",
"realmKey": "oc3"
},
{
"regionKey": "pia",
"realmDomainComponent": "oraclegovcloud.com",
"regionIdentifier": "us-gov-chicago-1",
"realmKey": "oc3"
},
{
"regionKey": "tus",
"realmDomainComponent": "oraclegovcloud.com",
"regionIdentifier": "us-gov-phoenix-1",
"realmKey": "oc3"
},
{
"regionKey": "ltn",
"realmDomainComponent": "oraclegovcloud.uk",
"regionIdentifier": "uk-gov-london-1",
"realmKey": "oc4"
},
{
"regionKey": "brs",
"realmDomainComponent": "oraclegovcloud.uk",
"regionIdentifier": "uk-gov-cardiff-1",
"realmKey": "oc4"
},
{
"regionKey": "nja",
"realmDomainComponent": "oraclecloud8.com",
"regionIdentifier": "ap-chiyoda-1",
"realmKey": "oc8"
},
{
"regionKey": "ukb",
"realmDomainComponent": "oraclecloud8.com",
"regionIdentifier": "ap-ibaraki-1",
"realmKey": "oc8"
},
{
"regionKey": "mtz",
"realmDomainComponent": "oraclecloud.com",
"regionIdentifier": "il-jerusalem-1",
"realmKey": "oc1"
},
{
"regionKey": "mrs",
"realmDomainComponent": "oraclecloud.com",
"regionIdentifier": "eu-marseille-1",
"realmKey": "oc1"
},
{
"regionKey": "sin",
"realmDomainComponent": "oraclecloud.com",
"regionIdentifier": "ap-singapore-1",
"realmKey": "oc1"
},
{
"regionKey": "auh",
"realmDomainComponent": "oraclecloud.com",
"regionIdentifier": "me-abudhabi-1",
"realmKey": "oc1"
},
{
"regionKey": "lin",
"realmDomainComponent": "oraclecloud.com",
"regionIdentifier": "eu-milan-1",
"realmKey": "oc1"
}
]

1052
vendor/github.com/oracle/oci-go-sdk/v54/common/retry.go generated vendored Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,37 @@
// Copyright (c) 2016, 2018, 2020, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated by go generate; DO NOT EDIT
package common
import (
"bytes"
"fmt"
"sync"
)
const (
major = "54"
minor = "0"
patch = "0"
tag = ""
)
var once sync.Once
var version string
// Version returns semantic version of the sdk
func Version() string {
once.Do(func() {
ver := fmt.Sprintf("%s.%s.%s", major, minor, patch)
verBuilder := bytes.NewBufferString(ver)
if tag != "" && tag != "-" {
_, err := verBuilder.WriteString(tag)
if err != nil {
verBuilder = bytes.NewBufferString(ver)
}
}
version = verBuilder.String()
})
return version
}

View file

@ -0,0 +1,83 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
package core
import (
"github.com/oracle/oci-go-sdk/v54/common"
"net/http"
)
// AcceptShieldedIntegrityPolicyRequest wrapper for the AcceptShieldedIntegrityPolicy operation
//
// See also
//
// Click https://docs.cloud.oracle.com/en-us/iaas/tools/go-sdk-examples/latest/core/AcceptShieldedIntegrityPolicy.go.html to see an example of how to use AcceptShieldedIntegrityPolicyRequest.
type AcceptShieldedIntegrityPolicyRequest struct {
// The OCID (https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm) of the instance.
InstanceId *string `mandatory:"true" contributesTo:"path" name:"instanceId"`
// Unique identifier for the request.
// If you need to contact Oracle about a particular request, please provide the request ID.
OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"`
// For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match`
// parameter to the value of the etag from a previous GET or POST response for that resource. The resource
// will be updated or deleted only if the etag you provide matches the resource's current etag value.
IfMatch *string `mandatory:"false" contributesTo:"header" name:"if-match"`
// A token that uniquely identifies a request so it can be retried in case of a timeout or
// server error without risk of executing that same action again. Retry tokens expire after 24
// hours, but can be invalidated before then due to conflicting operations (for example, if a resource
// has been deleted and purged from the system, then a retry of the original creation request
// may be rejected).
OpcRetryToken *string `mandatory:"false" contributesTo:"header" name:"opc-retry-token"`
// Metadata about the request. This information will not be transmitted to the service, but
// represents information that the SDK will consume to drive retry behavior.
RequestMetadata common.RequestMetadata
}
func (request AcceptShieldedIntegrityPolicyRequest) String() string {
return common.PointerString(request)
}
// HTTPRequest implements the OCIRequest interface
func (request AcceptShieldedIntegrityPolicyRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {
return common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)
}
// BinaryRequestBody implements the OCIRequest interface
func (request AcceptShieldedIntegrityPolicyRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {
return nil, false
}
// RetryPolicy implements the OCIRetryableRequest interface. This retrieves the specified retry policy.
func (request AcceptShieldedIntegrityPolicyRequest) RetryPolicy() *common.RetryPolicy {
return request.RequestMetadata.RetryPolicy
}
// AcceptShieldedIntegrityPolicyResponse wrapper for the AcceptShieldedIntegrityPolicy operation
type AcceptShieldedIntegrityPolicyResponse struct {
// The underlying http response
RawResponse *http.Response
// Unique Oracle-assigned identifier for the request. If you need to contact
// Oracle about a particular request, please provide the request ID.
OpcRequestId *string `presentIn:"header" name:"opc-request-id"`
}
func (response AcceptShieldedIntegrityPolicyResponse) String() string {
return common.PointerString(response)
}
// HTTPResponse implements the OCIResponse interface
func (response AcceptShieldedIntegrityPolicyResponse) HTTPResponse() *http.Response {
return response.RawResponse
}

View file

@ -0,0 +1,95 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
// Core Services API
//
// Use the Core Services API to manage resources such as virtual cloud networks (VCNs),
// compute instances, and block storage volumes. For more information, see the console
// documentation for the Networking (https://docs.cloud.oracle.com/iaas/Content/Network/Concepts/overview.htm),
// Compute (https://docs.cloud.oracle.com/iaas/Content/Compute/Concepts/computeoverview.htm), and
// Block Volume (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/overview.htm) services.
//
package core
import (
"encoding/json"
"github.com/oracle/oci-go-sdk/v54/common"
)
// AddDrgRouteDistributionStatementDetails Details used to add a route distribution statement.
type AddDrgRouteDistributionStatementDetails struct {
// The action is applied only if all of the match criteria is met.
// If there are no match criteria in a statement, match ALL is implied.
MatchCriteria []DrgRouteDistributionMatchCriteria `mandatory:"true" json:"matchCriteria"`
// Accept: import/export the route "as is"
Action AddDrgRouteDistributionStatementDetailsActionEnum `mandatory:"true" json:"action"`
// This field is used to specify the priority of each statement in a route distribution.
// The priority will be represented as a number between 0 and 65535 where a lower number
// indicates a higher priority. When a route is processed, statements are applied in the order
// defined by their priority. The first matching rule dictates the action that will be taken
// on the route.
Priority *int `mandatory:"true" json:"priority"`
}
func (m AddDrgRouteDistributionStatementDetails) String() string {
return common.PointerString(m)
}
// UnmarshalJSON unmarshals from json
func (m *AddDrgRouteDistributionStatementDetails) UnmarshalJSON(data []byte) (e error) {
model := struct {
MatchCriteria []drgroutedistributionmatchcriteria `json:"matchCriteria"`
Action AddDrgRouteDistributionStatementDetailsActionEnum `json:"action"`
Priority *int `json:"priority"`
}{}
e = json.Unmarshal(data, &model)
if e != nil {
return
}
var nn interface{}
m.MatchCriteria = make([]DrgRouteDistributionMatchCriteria, len(model.MatchCriteria))
for i, n := range model.MatchCriteria {
nn, e = n.UnmarshalPolymorphicJSON(n.JsonData)
if e != nil {
return e
}
if nn != nil {
m.MatchCriteria[i] = nn.(DrgRouteDistributionMatchCriteria)
} else {
m.MatchCriteria[i] = nil
}
}
m.Action = model.Action
m.Priority = model.Priority
return
}
// AddDrgRouteDistributionStatementDetailsActionEnum Enum with underlying type: string
type AddDrgRouteDistributionStatementDetailsActionEnum string
// Set of constants representing the allowable values for AddDrgRouteDistributionStatementDetailsActionEnum
const (
AddDrgRouteDistributionStatementDetailsActionAccept AddDrgRouteDistributionStatementDetailsActionEnum = "ACCEPT"
)
var mappingAddDrgRouteDistributionStatementDetailsAction = map[string]AddDrgRouteDistributionStatementDetailsActionEnum{
"ACCEPT": AddDrgRouteDistributionStatementDetailsActionAccept,
}
// GetAddDrgRouteDistributionStatementDetailsActionEnumValues Enumerates the set of values for AddDrgRouteDistributionStatementDetailsActionEnum
func GetAddDrgRouteDistributionStatementDetailsActionEnumValues() []AddDrgRouteDistributionStatementDetailsActionEnum {
values := make([]AddDrgRouteDistributionStatementDetailsActionEnum, 0)
for _, v := range mappingAddDrgRouteDistributionStatementDetailsAction {
values = append(values, v)
}
return values
}

View file

@ -0,0 +1,29 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
// Core Services API
//
// Use the Core Services API to manage resources such as virtual cloud networks (VCNs),
// compute instances, and block storage volumes. For more information, see the console
// documentation for the Networking (https://docs.cloud.oracle.com/iaas/Content/Network/Concepts/overview.htm),
// Compute (https://docs.cloud.oracle.com/iaas/Content/Compute/Concepts/computeoverview.htm), and
// Block Volume (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/overview.htm) services.
//
package core
import (
"github.com/oracle/oci-go-sdk/v54/common"
)
// AddDrgRouteDistributionStatementsDetails Details request to add statements to a route distribution.
type AddDrgRouteDistributionStatementsDetails struct {
// The collection of route distribution statements to insert into the route distribution.
Statements []AddDrgRouteDistributionStatementDetails `mandatory:"true" json:"statements"`
}
func (m AddDrgRouteDistributionStatementsDetails) String() string {
return common.PointerString(m)
}

View file

@ -0,0 +1,77 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
package core
import (
"github.com/oracle/oci-go-sdk/v54/common"
"net/http"
)
// AddDrgRouteDistributionStatementsRequest wrapper for the AddDrgRouteDistributionStatements operation
//
// See also
//
// Click https://docs.cloud.oracle.com/en-us/iaas/tools/go-sdk-examples/latest/core/AddDrgRouteDistributionStatements.go.html to see an example of how to use AddDrgRouteDistributionStatementsRequest.
type AddDrgRouteDistributionStatementsRequest struct {
// The OCID (https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm) of the route distribution.
DrgRouteDistributionId *string `mandatory:"true" contributesTo:"path" name:"drgRouteDistributionId"`
// Request with one or more route distribution statements to be inserted into the route distribution.
AddDrgRouteDistributionStatementsDetails `contributesTo:"body"`
// Unique Oracle-assigned identifier for the request.
// If you need to contact Oracle about a particular request, please provide the request ID.
OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"`
// Metadata about the request. This information will not be transmitted to the service, but
// represents information that the SDK will consume to drive retry behavior.
RequestMetadata common.RequestMetadata
}
func (request AddDrgRouteDistributionStatementsRequest) String() string {
return common.PointerString(request)
}
// HTTPRequest implements the OCIRequest interface
func (request AddDrgRouteDistributionStatementsRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {
return common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)
}
// BinaryRequestBody implements the OCIRequest interface
func (request AddDrgRouteDistributionStatementsRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {
return nil, false
}
// RetryPolicy implements the OCIRetryableRequest interface. This retrieves the specified retry policy.
func (request AddDrgRouteDistributionStatementsRequest) RetryPolicy() *common.RetryPolicy {
return request.RequestMetadata.RetryPolicy
}
// AddDrgRouteDistributionStatementsResponse wrapper for the AddDrgRouteDistributionStatements operation
type AddDrgRouteDistributionStatementsResponse struct {
// The underlying http response
RawResponse *http.Response
// The []DrgRouteDistributionStatement instance
Items []DrgRouteDistributionStatement `presentIn:"body"`
// Unique Oracle-assigned identifier for the request. If you need to contact
// Oracle about a particular request, please provide the request ID.
OpcRequestId *string `presentIn:"header" name:"opc-request-id"`
}
func (response AddDrgRouteDistributionStatementsResponse) String() string {
return common.PointerString(response)
}
// HTTPResponse implements the OCIResponse interface
func (response AddDrgRouteDistributionStatementsResponse) HTTPResponse() *http.Response {
return response.RawResponse
}

View file

@ -0,0 +1,63 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
// Core Services API
//
// Use the Core Services API to manage resources such as virtual cloud networks (VCNs),
// compute instances, and block storage volumes. For more information, see the console
// documentation for the Networking (https://docs.cloud.oracle.com/iaas/Content/Network/Concepts/overview.htm),
// Compute (https://docs.cloud.oracle.com/iaas/Content/Compute/Concepts/computeoverview.htm), and
// Block Volume (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/overview.htm) services.
//
package core
import (
"github.com/oracle/oci-go-sdk/v54/common"
)
// AddDrgRouteRuleDetails Details needed when adding a DRG route rule.
type AddDrgRouteRuleDetails struct {
// Type of destination for the rule. Required if `direction` = `EGRESS`.
// Allowed values:
// * `CIDR_BLOCK`: If the rule's `destination` is an IP address range in CIDR notation.
DestinationType AddDrgRouteRuleDetailsDestinationTypeEnum `mandatory:"true" json:"destinationType"`
// This is the range of IP addresses used for matching when routing
// traffic. Only CIDR_BLOCK values are allowed.
// Potential values:
// * IP address range in CIDR notation. This can be an IPv4 or IPv6 CIDR. For example: `192.168.1.0/24`
// or `2001:0db8:0123:45::/56`.
Destination *string `mandatory:"true" json:"destination"`
// The OCID (https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm) of the next hop DRG attachment. The next hop DRG attachment is responsible
// for reaching the network destination.
NextHopDrgAttachmentId *string `mandatory:"true" json:"nextHopDrgAttachmentId"`
}
func (m AddDrgRouteRuleDetails) String() string {
return common.PointerString(m)
}
// AddDrgRouteRuleDetailsDestinationTypeEnum Enum with underlying type: string
type AddDrgRouteRuleDetailsDestinationTypeEnum string
// Set of constants representing the allowable values for AddDrgRouteRuleDetailsDestinationTypeEnum
const (
AddDrgRouteRuleDetailsDestinationTypeCidrBlock AddDrgRouteRuleDetailsDestinationTypeEnum = "CIDR_BLOCK"
)
var mappingAddDrgRouteRuleDetailsDestinationType = map[string]AddDrgRouteRuleDetailsDestinationTypeEnum{
"CIDR_BLOCK": AddDrgRouteRuleDetailsDestinationTypeCidrBlock,
}
// GetAddDrgRouteRuleDetailsDestinationTypeEnumValues Enumerates the set of values for AddDrgRouteRuleDetailsDestinationTypeEnum
func GetAddDrgRouteRuleDetailsDestinationTypeEnumValues() []AddDrgRouteRuleDetailsDestinationTypeEnum {
values := make([]AddDrgRouteRuleDetailsDestinationTypeEnum, 0)
for _, v := range mappingAddDrgRouteRuleDetailsDestinationType {
values = append(values, v)
}
return values
}

View file

@ -0,0 +1,29 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
// Core Services API
//
// Use the Core Services API to manage resources such as virtual cloud networks (VCNs),
// compute instances, and block storage volumes. For more information, see the console
// documentation for the Networking (https://docs.cloud.oracle.com/iaas/Content/Network/Concepts/overview.htm),
// Compute (https://docs.cloud.oracle.com/iaas/Content/Compute/Concepts/computeoverview.htm), and
// Block Volume (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/overview.htm) services.
//
package core
import (
"github.com/oracle/oci-go-sdk/v54/common"
)
// AddDrgRouteRulesDetails Details used in a request to add static routes to a DRG route table.
type AddDrgRouteRulesDetails struct {
// The collection of static rules used to insert routes into the DRG route table.
RouteRules []AddDrgRouteRuleDetails `mandatory:"false" json:"routeRules"`
}
func (m AddDrgRouteRulesDetails) String() string {
return common.PointerString(m)
}

View file

@ -0,0 +1,84 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
package core
import (
"github.com/oracle/oci-go-sdk/v54/common"
"net/http"
)
// AddDrgRouteRulesRequest wrapper for the AddDrgRouteRules operation
//
// See also
//
// Click https://docs.cloud.oracle.com/en-us/iaas/tools/go-sdk-examples/latest/core/AddDrgRouteRules.go.html to see an example of how to use AddDrgRouteRulesRequest.
type AddDrgRouteRulesRequest struct {
// The OCID (https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm) of the DRG route table.
DrgRouteTableId *string `mandatory:"true" contributesTo:"path" name:"drgRouteTableId"`
// Request for one or more route rules to be inserted into the DRG route table.
AddDrgRouteRulesDetails `contributesTo:"body"`
// A token that uniquely identifies a request so it can be retried in case of a timeout or
// server error without risk of executing that same action again. Retry tokens expire after 24
// hours, but can be invalidated before then due to conflicting operations (for example, if a resource
// has been deleted and purged from the system, then a retry of the original creation request
// may be rejected).
OpcRetryToken *string `mandatory:"false" contributesTo:"header" name:"opc-retry-token"`
// Unique Oracle-assigned identifier for the request.
// If you need to contact Oracle about a particular request, please provide the request ID.
OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"`
// Metadata about the request. This information will not be transmitted to the service, but
// represents information that the SDK will consume to drive retry behavior.
RequestMetadata common.RequestMetadata
}
func (request AddDrgRouteRulesRequest) String() string {
return common.PointerString(request)
}
// HTTPRequest implements the OCIRequest interface
func (request AddDrgRouteRulesRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {
return common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)
}
// BinaryRequestBody implements the OCIRequest interface
func (request AddDrgRouteRulesRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {
return nil, false
}
// RetryPolicy implements the OCIRetryableRequest interface. This retrieves the specified retry policy.
func (request AddDrgRouteRulesRequest) RetryPolicy() *common.RetryPolicy {
return request.RequestMetadata.RetryPolicy
}
// AddDrgRouteRulesResponse wrapper for the AddDrgRouteRules operation
type AddDrgRouteRulesResponse struct {
// The underlying http response
RawResponse *http.Response
// The []DrgRouteRule instance
Items []DrgRouteRule `presentIn:"body"`
// Unique Oracle-assigned identifier for the request. If you need to contact
// Oracle about a particular request, please provide the request ID.
OpcRequestId *string `presentIn:"header" name:"opc-request-id"`
}
func (response AddDrgRouteRulesResponse) String() string {
return common.PointerString(response)
}
// HTTPResponse implements the OCIResponse interface
func (response AddDrgRouteRulesResponse) HTTPResponse() *http.Response {
return response.RawResponse
}

View file

@ -0,0 +1,29 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
// Core Services API
//
// Use the Core Services API to manage resources such as virtual cloud networks (VCNs),
// compute instances, and block storage volumes. For more information, see the console
// documentation for the Networking (https://docs.cloud.oracle.com/iaas/Content/Network/Concepts/overview.htm),
// Compute (https://docs.cloud.oracle.com/iaas/Content/Compute/Concepts/computeoverview.htm), and
// Block Volume (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/overview.htm) services.
//
package core
import (
"github.com/oracle/oci-go-sdk/v54/common"
)
// AddImageShapeCompatibilityEntryDetails Image shape compatibility details.
type AddImageShapeCompatibilityEntryDetails struct {
MemoryConstraints *ImageMemoryConstraints `mandatory:"false" json:"memoryConstraints"`
OcpuConstraints *ImageOcpuConstraints `mandatory:"false" json:"ocpuConstraints"`
}
func (m AddImageShapeCompatibilityEntryDetails) String() string {
return common.PointerString(m)
}

View file

@ -0,0 +1,80 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
package core
import (
"github.com/oracle/oci-go-sdk/v54/common"
"net/http"
)
// AddImageShapeCompatibilityEntryRequest wrapper for the AddImageShapeCompatibilityEntry operation
//
// See also
//
// Click https://docs.cloud.oracle.com/en-us/iaas/tools/go-sdk-examples/latest/core/AddImageShapeCompatibilityEntry.go.html to see an example of how to use AddImageShapeCompatibilityEntryRequest.
type AddImageShapeCompatibilityEntryRequest struct {
// The OCID (https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm) of the image.
ImageId *string `mandatory:"true" contributesTo:"path" name:"imageId"`
// Shape name.
ShapeName *string `mandatory:"true" contributesTo:"path" name:"shapeName"`
// Image shape compatibility details
AddImageShapeCompatibilityEntryDetails `contributesTo:"body"`
// Unique Oracle-assigned identifier for the request.
// If you need to contact Oracle about a particular request, please provide the request ID.
OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"`
// Metadata about the request. This information will not be transmitted to the service, but
// represents information that the SDK will consume to drive retry behavior.
RequestMetadata common.RequestMetadata
}
func (request AddImageShapeCompatibilityEntryRequest) String() string {
return common.PointerString(request)
}
// HTTPRequest implements the OCIRequest interface
func (request AddImageShapeCompatibilityEntryRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {
return common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)
}
// BinaryRequestBody implements the OCIRequest interface
func (request AddImageShapeCompatibilityEntryRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {
return nil, false
}
// RetryPolicy implements the OCIRetryableRequest interface. This retrieves the specified retry policy.
func (request AddImageShapeCompatibilityEntryRequest) RetryPolicy() *common.RetryPolicy {
return request.RequestMetadata.RetryPolicy
}
// AddImageShapeCompatibilityEntryResponse wrapper for the AddImageShapeCompatibilityEntry operation
type AddImageShapeCompatibilityEntryResponse struct {
// The underlying http response
RawResponse *http.Response
// The ImageShapeCompatibilityEntry instance
ImageShapeCompatibilityEntry `presentIn:"body"`
// Unique Oracle-assigned identifier for the request. If you need to contact
// Oracle about a particular request, please provide the request ID.
OpcRequestId *string `presentIn:"header" name:"opc-request-id"`
}
func (response AddImageShapeCompatibilityEntryResponse) String() string {
return common.PointerString(response)
}
// HTTPResponse implements the OCIResponse interface
func (response AddImageShapeCompatibilityEntryResponse) HTTPResponse() *http.Response {
return response.RawResponse
}

View file

@ -0,0 +1,87 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
package core
import (
"github.com/oracle/oci-go-sdk/v54/common"
"net/http"
)
// AddIpv6VcnCidrRequest wrapper for the AddIpv6VcnCidr operation
//
// See also
//
// Click https://docs.cloud.oracle.com/en-us/iaas/tools/go-sdk-examples/latest/core/AddIpv6VcnCidr.go.html to see an example of how to use AddIpv6VcnCidrRequest.
type AddIpv6VcnCidrRequest struct {
// The OCID (https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm) of the VCN.
VcnId *string `mandatory:"true" contributesTo:"path" name:"vcnId"`
// Unique identifier for the request.
// If you need to contact Oracle about a particular request, please provide the request ID.
OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"`
// A token that uniquely identifies a request so it can be retried in case of a timeout or
// server error without risk of executing that same action again. Retry tokens expire after 24
// hours, but can be invalidated before then due to conflicting operations (for example, if a resource
// has been deleted and purged from the system, then a retry of the original creation request
// may be rejected).
OpcRetryToken *string `mandatory:"false" contributesTo:"header" name:"opc-retry-token"`
// For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match`
// parameter to the value of the etag from a previous GET or POST response for that resource. The resource
// will be updated or deleted only if the etag you provide matches the resource's current etag value.
IfMatch *string `mandatory:"false" contributesTo:"header" name:"if-match"`
// Metadata about the request. This information will not be transmitted to the service, but
// represents information that the SDK will consume to drive retry behavior.
RequestMetadata common.RequestMetadata
}
func (request AddIpv6VcnCidrRequest) String() string {
return common.PointerString(request)
}
// HTTPRequest implements the OCIRequest interface
func (request AddIpv6VcnCidrRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {
return common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)
}
// BinaryRequestBody implements the OCIRequest interface
func (request AddIpv6VcnCidrRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {
return nil, false
}
// RetryPolicy implements the OCIRetryableRequest interface. This retrieves the specified retry policy.
func (request AddIpv6VcnCidrRequest) RetryPolicy() *common.RetryPolicy {
return request.RequestMetadata.RetryPolicy
}
// AddIpv6VcnCidrResponse wrapper for the AddIpv6VcnCidr operation
type AddIpv6VcnCidrResponse struct {
// The underlying http response
RawResponse *http.Response
// Unique Oracle-assigned identifier for the request. If you need to contact
// Oracle about a particular request, please provide the request ID.
OpcRequestId *string `presentIn:"header" name:"opc-request-id"`
// The OCID (https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm) of the work request. Use GetWorkRequest (https://docs.cloud.oracle.com/api/#/en/workrequests/20160918/WorkRequest/GetWorkRequest)
// with this ID to track the status of the request.
OpcWorkRequestId *string `presentIn:"header" name:"opc-work-request-id"`
}
func (response AddIpv6VcnCidrResponse) String() string {
return common.PointerString(response)
}
// HTTPResponse implements the OCIResponse interface
func (response AddIpv6VcnCidrResponse) HTTPResponse() *http.Response {
return response.RawResponse
}

View file

@ -0,0 +1,29 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
// Core Services API
//
// Use the Core Services API to manage resources such as virtual cloud networks (VCNs),
// compute instances, and block storage volumes. For more information, see the console
// documentation for the Networking (https://docs.cloud.oracle.com/iaas/Content/Network/Concepts/overview.htm),
// Compute (https://docs.cloud.oracle.com/iaas/Content/Compute/Concepts/computeoverview.htm), and
// Block Volume (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/overview.htm) services.
//
package core
import (
"github.com/oracle/oci-go-sdk/v54/common"
)
// AddNetworkSecurityGroupSecurityRulesDetails The representation of AddNetworkSecurityGroupSecurityRulesDetails
type AddNetworkSecurityGroupSecurityRulesDetails struct {
// The NSG security rules to add.
SecurityRules []AddSecurityRuleDetails `mandatory:"false" json:"securityRules"`
}
func (m AddNetworkSecurityGroupSecurityRulesDetails) String() string {
return common.PointerString(m)
}

View file

@ -0,0 +1,77 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
package core
import (
"github.com/oracle/oci-go-sdk/v54/common"
"net/http"
)
// AddNetworkSecurityGroupSecurityRulesRequest wrapper for the AddNetworkSecurityGroupSecurityRules operation
//
// See also
//
// Click https://docs.cloud.oracle.com/en-us/iaas/tools/go-sdk-examples/latest/core/AddNetworkSecurityGroupSecurityRules.go.html to see an example of how to use AddNetworkSecurityGroupSecurityRulesRequest.
type AddNetworkSecurityGroupSecurityRulesRequest struct {
// The OCID (https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm) of the network security group.
NetworkSecurityGroupId *string `mandatory:"true" contributesTo:"path" name:"networkSecurityGroupId"`
// Request with one or more security rules to be associated with the network security group.
AddNetworkSecurityGroupSecurityRulesDetails `contributesTo:"body"`
// Unique Oracle-assigned identifier for the request.
// If you need to contact Oracle about a particular request, please provide the request ID.
OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"`
// Metadata about the request. This information will not be transmitted to the service, but
// represents information that the SDK will consume to drive retry behavior.
RequestMetadata common.RequestMetadata
}
func (request AddNetworkSecurityGroupSecurityRulesRequest) String() string {
return common.PointerString(request)
}
// HTTPRequest implements the OCIRequest interface
func (request AddNetworkSecurityGroupSecurityRulesRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {
return common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)
}
// BinaryRequestBody implements the OCIRequest interface
func (request AddNetworkSecurityGroupSecurityRulesRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {
return nil, false
}
// RetryPolicy implements the OCIRetryableRequest interface. This retrieves the specified retry policy.
func (request AddNetworkSecurityGroupSecurityRulesRequest) RetryPolicy() *common.RetryPolicy {
return request.RequestMetadata.RetryPolicy
}
// AddNetworkSecurityGroupSecurityRulesResponse wrapper for the AddNetworkSecurityGroupSecurityRules operation
type AddNetworkSecurityGroupSecurityRulesResponse struct {
// The underlying http response
RawResponse *http.Response
// The AddedNetworkSecurityGroupSecurityRules instance
AddedNetworkSecurityGroupSecurityRules `presentIn:"body"`
// Unique Oracle-assigned identifier for the request. If you need to contact
// Oracle about a particular request, please provide the request ID.
OpcRequestId *string `presentIn:"header" name:"opc-request-id"`
}
func (response AddNetworkSecurityGroupSecurityRulesResponse) String() string {
return common.PointerString(response)
}
// HTTPResponse implements the OCIResponse interface
func (response AddNetworkSecurityGroupSecurityRulesResponse) HTTPResponse() *http.Response {
return response.RawResponse
}

View file

@ -0,0 +1,33 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
// Core Services API
//
// Use the Core Services API to manage resources such as virtual cloud networks (VCNs),
// compute instances, and block storage volumes. For more information, see the console
// documentation for the Networking (https://docs.cloud.oracle.com/iaas/Content/Network/Concepts/overview.htm),
// Compute (https://docs.cloud.oracle.com/iaas/Content/Compute/Concepts/computeoverview.htm), and
// Block Volume (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/overview.htm) services.
//
package core
import (
"github.com/oracle/oci-go-sdk/v54/common"
)
// AddPublicIpPoolCapacityDetails The information used to add capacity to an IP pool.
type AddPublicIpPoolCapacityDetails struct {
// The OCID (https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm) of the `ByoipRange` resource to which the CIDR block belongs.
ByoipRangeId *string `mandatory:"true" json:"byoipRangeId"`
// The CIDR block to add to the public IP pool. It could be all of the CIDR block identified in `byoipRangeId`, or a subrange.
// Example: `10.0.1.0/24`
CidrBlock *string `mandatory:"true" json:"cidrBlock"`
}
func (m AddPublicIpPoolCapacityDetails) String() string {
return common.PointerString(m)
}

View file

@ -0,0 +1,87 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
package core
import (
"github.com/oracle/oci-go-sdk/v54/common"
"net/http"
)
// AddPublicIpPoolCapacityRequest wrapper for the AddPublicIpPoolCapacity operation
//
// See also
//
// Click https://docs.cloud.oracle.com/en-us/iaas/tools/go-sdk-examples/latest/core/AddPublicIpPoolCapacity.go.html to see an example of how to use AddPublicIpPoolCapacityRequest.
type AddPublicIpPoolCapacityRequest struct {
// The OCID (https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm) of the public IP pool.
PublicIpPoolId *string `mandatory:"true" contributesTo:"path" name:"publicIpPoolId"`
// Byoip Range prefix and a cidr from it
AddPublicIpPoolCapacityDetails `contributesTo:"body"`
// Unique identifier for the request.
// If you need to contact Oracle about a particular request, please provide the request ID.
OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"`
// A token that uniquely identifies a request so it can be retried in case of a timeout or
// server error without risk of executing that same action again. Retry tokens expire after 24
// hours, but can be invalidated before then due to conflicting operations (for example, if a resource
// has been deleted and purged from the system, then a retry of the original creation request
// may be rejected).
OpcRetryToken *string `mandatory:"false" contributesTo:"header" name:"opc-retry-token"`
// Metadata about the request. This information will not be transmitted to the service, but
// represents information that the SDK will consume to drive retry behavior.
RequestMetadata common.RequestMetadata
}
func (request AddPublicIpPoolCapacityRequest) String() string {
return common.PointerString(request)
}
// HTTPRequest implements the OCIRequest interface
func (request AddPublicIpPoolCapacityRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {
return common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)
}
// BinaryRequestBody implements the OCIRequest interface
func (request AddPublicIpPoolCapacityRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {
return nil, false
}
// RetryPolicy implements the OCIRetryableRequest interface. This retrieves the specified retry policy.
func (request AddPublicIpPoolCapacityRequest) RetryPolicy() *common.RetryPolicy {
return request.RequestMetadata.RetryPolicy
}
// AddPublicIpPoolCapacityResponse wrapper for the AddPublicIpPoolCapacity operation
type AddPublicIpPoolCapacityResponse struct {
// The underlying http response
RawResponse *http.Response
// The PublicIpPool instance
PublicIpPool `presentIn:"body"`
// For optimistic concurrency control. See `if-match`.
Etag *string `presentIn:"header" name:"etag"`
// Unique Oracle-assigned identifier for the request. If you need to contact
// Oracle about a particular request, please provide the request ID.
OpcRequestId *string `presentIn:"header" name:"opc-request-id"`
}
func (response AddPublicIpPoolCapacityResponse) String() string {
return common.PointerString(response)
}
// HTTPResponse implements the OCIResponse interface
func (response AddPublicIpPoolCapacityResponse) HTTPResponse() *http.Response {
return response.RawResponse
}

View file

@ -0,0 +1,172 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
// Core Services API
//
// Use the Core Services API to manage resources such as virtual cloud networks (VCNs),
// compute instances, and block storage volumes. For more information, see the console
// documentation for the Networking (https://docs.cloud.oracle.com/iaas/Content/Network/Concepts/overview.htm),
// Compute (https://docs.cloud.oracle.com/iaas/Content/Compute/Concepts/computeoverview.htm), and
// Block Volume (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/overview.htm) services.
//
package core
import (
"github.com/oracle/oci-go-sdk/v54/common"
)
// AddSecurityRuleDetails A rule for allowing inbound (INGRESS) or outbound (EGRESS) IP packets.
type AddSecurityRuleDetails struct {
// Direction of the security rule. Set to `EGRESS` for rules to allow outbound IP packets,
// or `INGRESS` for rules to allow inbound IP packets.
Direction AddSecurityRuleDetailsDirectionEnum `mandatory:"true" json:"direction"`
// The transport protocol. Specify either `all` or an IPv4 protocol number as
// defined in
// Protocol Numbers (http://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml).
// Options are supported only for ICMP ("1"), TCP ("6"), UDP ("17"), and ICMPv6 ("58").
Protocol *string `mandatory:"true" json:"protocol"`
// An optional description of your choice for the rule. Avoid entering confidential information.
Description *string `mandatory:"false" json:"description"`
// Conceptually, this is the range of IP addresses that a packet originating from the instance
// can go to.
// Allowed values:
// * An IP address range in CIDR notation. For example: `192.168.1.0/24` or `2001:0db8:0123:45::/56`
// IPv6 addressing is supported for all commercial and government regions. See
// IPv6 Addresses (https://docs.cloud.oracle.com/iaas/Content/Network/Concepts/ipv6.htm).
// * The `cidrBlock` value for a Service, if you're
// setting up a security rule for traffic destined for a particular `Service` through
// a service gateway. For example: `oci-phx-objectstorage`.
// * The OCID (https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm) of a NetworkSecurityGroup in the same
// VCN. The value can be the NSG that the rule belongs to if the rule's intent is to control
// traffic between VNICs in the same NSG.
Destination *string `mandatory:"false" json:"destination"`
// Type of destination for the rule. Required if `direction` = `EGRESS`.
// Allowed values:
// * `CIDR_BLOCK`: If the rule's `destination` is an IP address range in CIDR notation.
// * `SERVICE_CIDR_BLOCK`: If the rule's `destination` is the `cidrBlock` value for a
// Service (the rule is for traffic destined for a
// particular `Service` through a service gateway).
// * `NETWORK_SECURITY_GROUP`: If the rule's `destination` is the OCID (https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm) of a
// NetworkSecurityGroup.
DestinationType AddSecurityRuleDetailsDestinationTypeEnum `mandatory:"false" json:"destinationType,omitempty"`
IcmpOptions *IcmpOptions `mandatory:"false" json:"icmpOptions"`
// A stateless rule allows traffic in one direction. Remember to add a corresponding
// stateless rule in the other direction if you need to support bidirectional traffic. For
// example, if egress traffic allows TCP destination port 80, there should be an ingress
// rule to allow TCP source port 80. Defaults to false, which means the rule is stateful
// and a corresponding rule is not necessary for bidirectional traffic.
IsStateless *bool `mandatory:"false" json:"isStateless"`
// Conceptually, this is the range of IP addresses that a packet coming into the instance
// can come from.
// Allowed values:
// * An IP address range in CIDR notation. For example: `192.168.1.0/24` or `2001:0db8:0123:45::/56`
// IPv6 addressing is supported for all commercial and government regions. See
// IPv6 Addresses (https://docs.cloud.oracle.com/iaas/Content/Network/Concepts/ipv6.htm).
// * The `cidrBlock` value for a Service, if you're
// setting up a security rule for traffic coming from a particular `Service` through
// a service gateway. For example: `oci-phx-objectstorage`.
// * The OCID (https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm) of a NetworkSecurityGroup in the same
// VCN. The value can be the NSG that the rule belongs to if the rule's intent is to control
// traffic between VNICs in the same NSG.
Source *string `mandatory:"false" json:"source"`
// Type of source for the rule. Required if `direction` = `INGRESS`.
// * `CIDR_BLOCK`: If the rule's `source` is an IP address range in CIDR notation.
// * `SERVICE_CIDR_BLOCK`: If the rule's `source` is the `cidrBlock` value for a
// Service (the rule is for traffic coming from a
// particular `Service` through a service gateway).
// * `NETWORK_SECURITY_GROUP`: If the rule's `source` is the OCID (https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm) of a
// NetworkSecurityGroup.
SourceType AddSecurityRuleDetailsSourceTypeEnum `mandatory:"false" json:"sourceType,omitempty"`
TcpOptions *TcpOptions `mandatory:"false" json:"tcpOptions"`
UdpOptions *UdpOptions `mandatory:"false" json:"udpOptions"`
}
func (m AddSecurityRuleDetails) String() string {
return common.PointerString(m)
}
// AddSecurityRuleDetailsDestinationTypeEnum Enum with underlying type: string
type AddSecurityRuleDetailsDestinationTypeEnum string
// Set of constants representing the allowable values for AddSecurityRuleDetailsDestinationTypeEnum
const (
AddSecurityRuleDetailsDestinationTypeCidrBlock AddSecurityRuleDetailsDestinationTypeEnum = "CIDR_BLOCK"
AddSecurityRuleDetailsDestinationTypeServiceCidrBlock AddSecurityRuleDetailsDestinationTypeEnum = "SERVICE_CIDR_BLOCK"
AddSecurityRuleDetailsDestinationTypeNetworkSecurityGroup AddSecurityRuleDetailsDestinationTypeEnum = "NETWORK_SECURITY_GROUP"
)
var mappingAddSecurityRuleDetailsDestinationType = map[string]AddSecurityRuleDetailsDestinationTypeEnum{
"CIDR_BLOCK": AddSecurityRuleDetailsDestinationTypeCidrBlock,
"SERVICE_CIDR_BLOCK": AddSecurityRuleDetailsDestinationTypeServiceCidrBlock,
"NETWORK_SECURITY_GROUP": AddSecurityRuleDetailsDestinationTypeNetworkSecurityGroup,
}
// GetAddSecurityRuleDetailsDestinationTypeEnumValues Enumerates the set of values for AddSecurityRuleDetailsDestinationTypeEnum
func GetAddSecurityRuleDetailsDestinationTypeEnumValues() []AddSecurityRuleDetailsDestinationTypeEnum {
values := make([]AddSecurityRuleDetailsDestinationTypeEnum, 0)
for _, v := range mappingAddSecurityRuleDetailsDestinationType {
values = append(values, v)
}
return values
}
// AddSecurityRuleDetailsDirectionEnum Enum with underlying type: string
type AddSecurityRuleDetailsDirectionEnum string
// Set of constants representing the allowable values for AddSecurityRuleDetailsDirectionEnum
const (
AddSecurityRuleDetailsDirectionEgress AddSecurityRuleDetailsDirectionEnum = "EGRESS"
AddSecurityRuleDetailsDirectionIngress AddSecurityRuleDetailsDirectionEnum = "INGRESS"
)
var mappingAddSecurityRuleDetailsDirection = map[string]AddSecurityRuleDetailsDirectionEnum{
"EGRESS": AddSecurityRuleDetailsDirectionEgress,
"INGRESS": AddSecurityRuleDetailsDirectionIngress,
}
// GetAddSecurityRuleDetailsDirectionEnumValues Enumerates the set of values for AddSecurityRuleDetailsDirectionEnum
func GetAddSecurityRuleDetailsDirectionEnumValues() []AddSecurityRuleDetailsDirectionEnum {
values := make([]AddSecurityRuleDetailsDirectionEnum, 0)
for _, v := range mappingAddSecurityRuleDetailsDirection {
values = append(values, v)
}
return values
}
// AddSecurityRuleDetailsSourceTypeEnum Enum with underlying type: string
type AddSecurityRuleDetailsSourceTypeEnum string
// Set of constants representing the allowable values for AddSecurityRuleDetailsSourceTypeEnum
const (
AddSecurityRuleDetailsSourceTypeCidrBlock AddSecurityRuleDetailsSourceTypeEnum = "CIDR_BLOCK"
AddSecurityRuleDetailsSourceTypeServiceCidrBlock AddSecurityRuleDetailsSourceTypeEnum = "SERVICE_CIDR_BLOCK"
AddSecurityRuleDetailsSourceTypeNetworkSecurityGroup AddSecurityRuleDetailsSourceTypeEnum = "NETWORK_SECURITY_GROUP"
)
var mappingAddSecurityRuleDetailsSourceType = map[string]AddSecurityRuleDetailsSourceTypeEnum{
"CIDR_BLOCK": AddSecurityRuleDetailsSourceTypeCidrBlock,
"SERVICE_CIDR_BLOCK": AddSecurityRuleDetailsSourceTypeServiceCidrBlock,
"NETWORK_SECURITY_GROUP": AddSecurityRuleDetailsSourceTypeNetworkSecurityGroup,
}
// GetAddSecurityRuleDetailsSourceTypeEnumValues Enumerates the set of values for AddSecurityRuleDetailsSourceTypeEnum
func GetAddSecurityRuleDetailsSourceTypeEnumValues() []AddSecurityRuleDetailsSourceTypeEnum {
values := make([]AddSecurityRuleDetailsSourceTypeEnum, 0)
for _, v := range mappingAddSecurityRuleDetailsSourceType {
values = append(values, v)
}
return values
}

View file

@ -0,0 +1,29 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
// Core Services API
//
// Use the Core Services API to manage resources such as virtual cloud networks (VCNs),
// compute instances, and block storage volumes. For more information, see the console
// documentation for the Networking (https://docs.cloud.oracle.com/iaas/Content/Network/Concepts/overview.htm),
// Compute (https://docs.cloud.oracle.com/iaas/Content/Compute/Concepts/computeoverview.htm), and
// Block Volume (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/overview.htm) services.
//
package core
import (
"github.com/oracle/oci-go-sdk/v54/common"
)
// AddVcnCidrDetails Details for adding a CIDR block to a VCN.
type AddVcnCidrDetails struct {
// The CIDR block to add.
CidrBlock *string `mandatory:"true" json:"cidrBlock"`
}
func (m AddVcnCidrDetails) String() string {
return common.PointerString(m)
}

View file

@ -0,0 +1,90 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
package core
import (
"github.com/oracle/oci-go-sdk/v54/common"
"net/http"
)
// AddVcnCidrRequest wrapper for the AddVcnCidr operation
//
// See also
//
// Click https://docs.cloud.oracle.com/en-us/iaas/tools/go-sdk-examples/latest/core/AddVcnCidr.go.html to see an example of how to use AddVcnCidrRequest.
type AddVcnCidrRequest struct {
// The OCID (https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm) of the VCN.
VcnId *string `mandatory:"true" contributesTo:"path" name:"vcnId"`
// Details object for deleting a VCN CIDR.
AddVcnCidrDetails `contributesTo:"body"`
// Unique identifier for the request.
// If you need to contact Oracle about a particular request, please provide the request ID.
OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"`
// A token that uniquely identifies a request so it can be retried in case of a timeout or
// server error without risk of executing that same action again. Retry tokens expire after 24
// hours, but can be invalidated before then due to conflicting operations (for example, if a resource
// has been deleted and purged from the system, then a retry of the original creation request
// may be rejected).
OpcRetryToken *string `mandatory:"false" contributesTo:"header" name:"opc-retry-token"`
// For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match`
// parameter to the value of the etag from a previous GET or POST response for that resource. The resource
// will be updated or deleted only if the etag you provide matches the resource's current etag value.
IfMatch *string `mandatory:"false" contributesTo:"header" name:"if-match"`
// Metadata about the request. This information will not be transmitted to the service, but
// represents information that the SDK will consume to drive retry behavior.
RequestMetadata common.RequestMetadata
}
func (request AddVcnCidrRequest) String() string {
return common.PointerString(request)
}
// HTTPRequest implements the OCIRequest interface
func (request AddVcnCidrRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {
return common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)
}
// BinaryRequestBody implements the OCIRequest interface
func (request AddVcnCidrRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {
return nil, false
}
// RetryPolicy implements the OCIRetryableRequest interface. This retrieves the specified retry policy.
func (request AddVcnCidrRequest) RetryPolicy() *common.RetryPolicy {
return request.RequestMetadata.RetryPolicy
}
// AddVcnCidrResponse wrapper for the AddVcnCidr operation
type AddVcnCidrResponse struct {
// The underlying http response
RawResponse *http.Response
// Unique Oracle-assigned identifier for the request. If you need to contact
// Oracle about a particular request, please provide the request ID.
OpcRequestId *string `presentIn:"header" name:"opc-request-id"`
// The OCID (https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm) of the work request. Use GetWorkRequest (https://docs.cloud.oracle.com/api/#/en/workrequests/20160918/WorkRequest/GetWorkRequest)
// with this ID to track the status of the request.
OpcWorkRequestId *string `presentIn:"header" name:"opc-work-request-id"`
}
func (response AddVcnCidrResponse) String() string {
return common.PointerString(response)
}
// HTTPResponse implements the OCIResponse interface
func (response AddVcnCidrResponse) HTTPResponse() *http.Response {
return response.RawResponse
}

View file

@ -0,0 +1,29 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
// Core Services API
//
// Use the Core Services API to manage resources such as virtual cloud networks (VCNs),
// compute instances, and block storage volumes. For more information, see the console
// documentation for the Networking (https://docs.cloud.oracle.com/iaas/Content/Network/Concepts/overview.htm),
// Compute (https://docs.cloud.oracle.com/iaas/Content/Compute/Concepts/computeoverview.htm), and
// Block Volume (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/overview.htm) services.
//
package core
import (
"github.com/oracle/oci-go-sdk/v54/common"
)
// AddedNetworkSecurityGroupSecurityRules The representation of AddedNetworkSecurityGroupSecurityRules
type AddedNetworkSecurityGroupSecurityRules struct {
// The NSG security rules that were added.
SecurityRules []SecurityRule `mandatory:"false" json:"securityRules"`
}
func (m AddedNetworkSecurityGroupSecurityRules) String() string {
return common.PointerString(m)
}

View file

@ -0,0 +1,71 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
package core
import (
"github.com/oracle/oci-go-sdk/v54/common"
"net/http"
)
// AdvertiseByoipRangeRequest wrapper for the AdvertiseByoipRange operation
//
// See also
//
// Click https://docs.cloud.oracle.com/en-us/iaas/tools/go-sdk-examples/latest/core/AdvertiseByoipRange.go.html to see an example of how to use AdvertiseByoipRangeRequest.
type AdvertiseByoipRangeRequest struct {
// The OCID (https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm) of the `ByoipRange` resource containing the BYOIP CIDR block.
ByoipRangeId *string `mandatory:"true" contributesTo:"path" name:"byoipRangeId"`
// Unique identifier for the request.
// If you need to contact Oracle about a particular request, please provide the request ID.
OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"`
// Metadata about the request. This information will not be transmitted to the service, but
// represents information that the SDK will consume to drive retry behavior.
RequestMetadata common.RequestMetadata
}
func (request AdvertiseByoipRangeRequest) String() string {
return common.PointerString(request)
}
// HTTPRequest implements the OCIRequest interface
func (request AdvertiseByoipRangeRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {
return common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)
}
// BinaryRequestBody implements the OCIRequest interface
func (request AdvertiseByoipRangeRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {
return nil, false
}
// RetryPolicy implements the OCIRetryableRequest interface. This retrieves the specified retry policy.
func (request AdvertiseByoipRangeRequest) RetryPolicy() *common.RetryPolicy {
return request.RequestMetadata.RetryPolicy
}
// AdvertiseByoipRangeResponse wrapper for the AdvertiseByoipRange operation
type AdvertiseByoipRangeResponse struct {
// The underlying http response
RawResponse *http.Response
// Unique Oracle-assigned identifier for the request. If you need to contact
// Oracle about a particular request, please provide the request ID.
OpcRequestId *string `presentIn:"header" name:"opc-request-id"`
}
func (response AdvertiseByoipRangeResponse) String() string {
return common.PointerString(response)
}
// HTTPResponse implements the OCIResponse interface
func (response AdvertiseByoipRangeResponse) HTTPResponse() *http.Response {
return response.RawResponse
}

View file

@ -0,0 +1,33 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
// Core Services API
//
// Use the Core Services API to manage resources such as virtual cloud networks (VCNs),
// compute instances, and block storage volumes. For more information, see the console
// documentation for the Networking (https://docs.cloud.oracle.com/iaas/Content/Network/Concepts/overview.htm),
// Compute (https://docs.cloud.oracle.com/iaas/Content/Compute/Concepts/computeoverview.htm), and
// Block Volume (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/overview.htm) services.
//
package core
import (
"github.com/oracle/oci-go-sdk/v54/common"
)
// AllowedIkeIpSecParameters Allowed IKE IPSec Parameters
type AllowedIkeIpSecParameters struct {
AllowedPhaseOneParameters *AllowedPhaseOneParameters `mandatory:"true" json:"allowedPhaseOneParameters"`
AllowedPhaseTwoParameters *AllowedPhaseTwoParameters `mandatory:"true" json:"allowedPhaseTwoParameters"`
DefaultPhaseOneParameters *DefaultPhaseOneParameters `mandatory:"true" json:"defaultPhaseOneParameters"`
DefaultPhaseTwoParameters *DefaultPhaseTwoParameters `mandatory:"true" json:"defaultPhaseTwoParameters"`
}
func (m AllowedIkeIpSecParameters) String() string {
return common.PointerString(m)
}

View file

@ -0,0 +1,35 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
// Core Services API
//
// Use the Core Services API to manage resources such as virtual cloud networks (VCNs),
// compute instances, and block storage volumes. For more information, see the console
// documentation for the Networking (https://docs.cloud.oracle.com/iaas/Content/Network/Concepts/overview.htm),
// Compute (https://docs.cloud.oracle.com/iaas/Content/Compute/Concepts/computeoverview.htm), and
// Block Volume (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/overview.htm) services.
//
package core
import (
"github.com/oracle/oci-go-sdk/v54/common"
)
// AllowedPhaseOneParameters Phase One Parameters
type AllowedPhaseOneParameters struct {
// Phase One Encryption Algorithms
EncryptionAlgorithms []string `mandatory:"false" json:"encryptionAlgorithms"`
// Phase One Authentication Algorithms
AuthenticationAlgorithms []string `mandatory:"false" json:"authenticationAlgorithms"`
// DH Groups
DhGroups []string `mandatory:"false" json:"dhGroups"`
}
func (m AllowedPhaseOneParameters) String() string {
return common.PointerString(m)
}

View file

@ -0,0 +1,35 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
// Core Services API
//
// Use the Core Services API to manage resources such as virtual cloud networks (VCNs),
// compute instances, and block storage volumes. For more information, see the console
// documentation for the Networking (https://docs.cloud.oracle.com/iaas/Content/Network/Concepts/overview.htm),
// Compute (https://docs.cloud.oracle.com/iaas/Content/Compute/Concepts/computeoverview.htm), and
// Block Volume (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/overview.htm) services.
//
package core
import (
"github.com/oracle/oci-go-sdk/v54/common"
)
// AllowedPhaseTwoParameters Phase Two Parameters
type AllowedPhaseTwoParameters struct {
// Phase Two Encryption Algorithms
EncryptionAlgorithms []string `mandatory:"false" json:"encryptionAlgorithms"`
// Phase Two Authentication Algorithms
AuthenticationAlgorithms []string `mandatory:"false" json:"authenticationAlgorithms"`
// PFS DH Groups
PfsDhGroups []string `mandatory:"false" json:"pfsDhGroups"`
}
func (m AllowedPhaseTwoParameters) String() string {
return common.PointerString(m)
}

View file

@ -0,0 +1,96 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
// Core Services API
//
// Use the Core Services API to manage resources such as virtual cloud networks (VCNs),
// compute instances, and block storage volumes. For more information, see the console
// documentation for the Networking (https://docs.cloud.oracle.com/iaas/Content/Network/Concepts/overview.htm),
// Compute (https://docs.cloud.oracle.com/iaas/Content/Compute/Concepts/computeoverview.htm), and
// Block Volume (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/overview.htm) services.
//
package core
import (
"encoding/json"
"github.com/oracle/oci-go-sdk/v54/common"
)
// AmdMilanBmLaunchInstancePlatformConfig The platform configuration used when launching a bare metal instance with an E4 shape
// (the AMD Milan platform).
type AmdMilanBmLaunchInstancePlatformConfig struct {
// Whether Secure Boot is enabled on the instance.
IsSecureBootEnabled *bool `mandatory:"false" json:"isSecureBootEnabled"`
// Whether the Trusted Platform Module (TPM) is enabled on the instance.
IsTrustedPlatformModuleEnabled *bool `mandatory:"false" json:"isTrustedPlatformModuleEnabled"`
// Whether the Measured Boot feature is enabled on the instance.
IsMeasuredBootEnabled *bool `mandatory:"false" json:"isMeasuredBootEnabled"`
// The number of NUMA nodes per socket (NPS).
NumaNodesPerSocket AmdMilanBmLaunchInstancePlatformConfigNumaNodesPerSocketEnum `mandatory:"false" json:"numaNodesPerSocket,omitempty"`
}
//GetIsSecureBootEnabled returns IsSecureBootEnabled
func (m AmdMilanBmLaunchInstancePlatformConfig) GetIsSecureBootEnabled() *bool {
return m.IsSecureBootEnabled
}
//GetIsTrustedPlatformModuleEnabled returns IsTrustedPlatformModuleEnabled
func (m AmdMilanBmLaunchInstancePlatformConfig) GetIsTrustedPlatformModuleEnabled() *bool {
return m.IsTrustedPlatformModuleEnabled
}
//GetIsMeasuredBootEnabled returns IsMeasuredBootEnabled
func (m AmdMilanBmLaunchInstancePlatformConfig) GetIsMeasuredBootEnabled() *bool {
return m.IsMeasuredBootEnabled
}
func (m AmdMilanBmLaunchInstancePlatformConfig) String() string {
return common.PointerString(m)
}
// MarshalJSON marshals to json representation
func (m AmdMilanBmLaunchInstancePlatformConfig) MarshalJSON() (buff []byte, e error) {
type MarshalTypeAmdMilanBmLaunchInstancePlatformConfig AmdMilanBmLaunchInstancePlatformConfig
s := struct {
DiscriminatorParam string `json:"type"`
MarshalTypeAmdMilanBmLaunchInstancePlatformConfig
}{
"AMD_MILAN_BM",
(MarshalTypeAmdMilanBmLaunchInstancePlatformConfig)(m),
}
return json.Marshal(&s)
}
// AmdMilanBmLaunchInstancePlatformConfigNumaNodesPerSocketEnum Enum with underlying type: string
type AmdMilanBmLaunchInstancePlatformConfigNumaNodesPerSocketEnum string
// Set of constants representing the allowable values for AmdMilanBmLaunchInstancePlatformConfigNumaNodesPerSocketEnum
const (
AmdMilanBmLaunchInstancePlatformConfigNumaNodesPerSocketNps0 AmdMilanBmLaunchInstancePlatformConfigNumaNodesPerSocketEnum = "NPS0"
AmdMilanBmLaunchInstancePlatformConfigNumaNodesPerSocketNps1 AmdMilanBmLaunchInstancePlatformConfigNumaNodesPerSocketEnum = "NPS1"
AmdMilanBmLaunchInstancePlatformConfigNumaNodesPerSocketNps2 AmdMilanBmLaunchInstancePlatformConfigNumaNodesPerSocketEnum = "NPS2"
AmdMilanBmLaunchInstancePlatformConfigNumaNodesPerSocketNps4 AmdMilanBmLaunchInstancePlatformConfigNumaNodesPerSocketEnum = "NPS4"
)
var mappingAmdMilanBmLaunchInstancePlatformConfigNumaNodesPerSocket = map[string]AmdMilanBmLaunchInstancePlatformConfigNumaNodesPerSocketEnum{
"NPS0": AmdMilanBmLaunchInstancePlatformConfigNumaNodesPerSocketNps0,
"NPS1": AmdMilanBmLaunchInstancePlatformConfigNumaNodesPerSocketNps1,
"NPS2": AmdMilanBmLaunchInstancePlatformConfigNumaNodesPerSocketNps2,
"NPS4": AmdMilanBmLaunchInstancePlatformConfigNumaNodesPerSocketNps4,
}
// GetAmdMilanBmLaunchInstancePlatformConfigNumaNodesPerSocketEnumValues Enumerates the set of values for AmdMilanBmLaunchInstancePlatformConfigNumaNodesPerSocketEnum
func GetAmdMilanBmLaunchInstancePlatformConfigNumaNodesPerSocketEnumValues() []AmdMilanBmLaunchInstancePlatformConfigNumaNodesPerSocketEnum {
values := make([]AmdMilanBmLaunchInstancePlatformConfigNumaNodesPerSocketEnum, 0)
for _, v := range mappingAmdMilanBmLaunchInstancePlatformConfigNumaNodesPerSocket {
values = append(values, v)
}
return values
}

View file

@ -0,0 +1,96 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
// Core Services API
//
// Use the Core Services API to manage resources such as virtual cloud networks (VCNs),
// compute instances, and block storage volumes. For more information, see the console
// documentation for the Networking (https://docs.cloud.oracle.com/iaas/Content/Network/Concepts/overview.htm),
// Compute (https://docs.cloud.oracle.com/iaas/Content/Compute/Concepts/computeoverview.htm), and
// Block Volume (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/overview.htm) services.
//
package core
import (
"encoding/json"
"github.com/oracle/oci-go-sdk/v54/common"
)
// AmdMilanBmPlatformConfig The platform configuration of a bare metal instance that uses an E4 shape
// (the AMD Milan platform).
type AmdMilanBmPlatformConfig struct {
// Whether Secure Boot is enabled on the instance.
IsSecureBootEnabled *bool `mandatory:"false" json:"isSecureBootEnabled"`
// Whether the Trusted Platform Module (TPM) is enabled on the instance.
IsTrustedPlatformModuleEnabled *bool `mandatory:"false" json:"isTrustedPlatformModuleEnabled"`
// Whether the Measured Boot feature is enabled on the instance.
IsMeasuredBootEnabled *bool `mandatory:"false" json:"isMeasuredBootEnabled"`
// The number of NUMA nodes per socket (NPS).
NumaNodesPerSocket AmdMilanBmPlatformConfigNumaNodesPerSocketEnum `mandatory:"false" json:"numaNodesPerSocket,omitempty"`
}
//GetIsSecureBootEnabled returns IsSecureBootEnabled
func (m AmdMilanBmPlatformConfig) GetIsSecureBootEnabled() *bool {
return m.IsSecureBootEnabled
}
//GetIsTrustedPlatformModuleEnabled returns IsTrustedPlatformModuleEnabled
func (m AmdMilanBmPlatformConfig) GetIsTrustedPlatformModuleEnabled() *bool {
return m.IsTrustedPlatformModuleEnabled
}
//GetIsMeasuredBootEnabled returns IsMeasuredBootEnabled
func (m AmdMilanBmPlatformConfig) GetIsMeasuredBootEnabled() *bool {
return m.IsMeasuredBootEnabled
}
func (m AmdMilanBmPlatformConfig) String() string {
return common.PointerString(m)
}
// MarshalJSON marshals to json representation
func (m AmdMilanBmPlatformConfig) MarshalJSON() (buff []byte, e error) {
type MarshalTypeAmdMilanBmPlatformConfig AmdMilanBmPlatformConfig
s := struct {
DiscriminatorParam string `json:"type"`
MarshalTypeAmdMilanBmPlatformConfig
}{
"AMD_MILAN_BM",
(MarshalTypeAmdMilanBmPlatformConfig)(m),
}
return json.Marshal(&s)
}
// AmdMilanBmPlatformConfigNumaNodesPerSocketEnum Enum with underlying type: string
type AmdMilanBmPlatformConfigNumaNodesPerSocketEnum string
// Set of constants representing the allowable values for AmdMilanBmPlatformConfigNumaNodesPerSocketEnum
const (
AmdMilanBmPlatformConfigNumaNodesPerSocketNps0 AmdMilanBmPlatformConfigNumaNodesPerSocketEnum = "NPS0"
AmdMilanBmPlatformConfigNumaNodesPerSocketNps1 AmdMilanBmPlatformConfigNumaNodesPerSocketEnum = "NPS1"
AmdMilanBmPlatformConfigNumaNodesPerSocketNps2 AmdMilanBmPlatformConfigNumaNodesPerSocketEnum = "NPS2"
AmdMilanBmPlatformConfigNumaNodesPerSocketNps4 AmdMilanBmPlatformConfigNumaNodesPerSocketEnum = "NPS4"
)
var mappingAmdMilanBmPlatformConfigNumaNodesPerSocket = map[string]AmdMilanBmPlatformConfigNumaNodesPerSocketEnum{
"NPS0": AmdMilanBmPlatformConfigNumaNodesPerSocketNps0,
"NPS1": AmdMilanBmPlatformConfigNumaNodesPerSocketNps1,
"NPS2": AmdMilanBmPlatformConfigNumaNodesPerSocketNps2,
"NPS4": AmdMilanBmPlatformConfigNumaNodesPerSocketNps4,
}
// GetAmdMilanBmPlatformConfigNumaNodesPerSocketEnumValues Enumerates the set of values for AmdMilanBmPlatformConfigNumaNodesPerSocketEnum
func GetAmdMilanBmPlatformConfigNumaNodesPerSocketEnumValues() []AmdMilanBmPlatformConfigNumaNodesPerSocketEnum {
values := make([]AmdMilanBmPlatformConfigNumaNodesPerSocketEnum, 0)
for _, v := range mappingAmdMilanBmPlatformConfigNumaNodesPerSocket {
values = append(values, v)
}
return values
}

View file

@ -0,0 +1,65 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
// Core Services API
//
// Use the Core Services API to manage resources such as virtual cloud networks (VCNs),
// compute instances, and block storage volumes. For more information, see the console
// documentation for the Networking (https://docs.cloud.oracle.com/iaas/Content/Network/Concepts/overview.htm),
// Compute (https://docs.cloud.oracle.com/iaas/Content/Compute/Concepts/computeoverview.htm), and
// Block Volume (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/overview.htm) services.
//
package core
import (
"encoding/json"
"github.com/oracle/oci-go-sdk/v54/common"
)
// AmdRomeBmLaunchInstancePlatformConfig The platform configuration used when launching a bare metal instance with the AMD Rome platform.
type AmdRomeBmLaunchInstancePlatformConfig struct {
// Whether Secure Boot is enabled on the instance.
IsSecureBootEnabled *bool `mandatory:"false" json:"isSecureBootEnabled"`
// Whether the Trusted Platform Module (TPM) is enabled on the instance.
IsTrustedPlatformModuleEnabled *bool `mandatory:"false" json:"isTrustedPlatformModuleEnabled"`
// Whether the Measured Boot feature is enabled on the instance.
IsMeasuredBootEnabled *bool `mandatory:"false" json:"isMeasuredBootEnabled"`
}
//GetIsSecureBootEnabled returns IsSecureBootEnabled
func (m AmdRomeBmLaunchInstancePlatformConfig) GetIsSecureBootEnabled() *bool {
return m.IsSecureBootEnabled
}
//GetIsTrustedPlatformModuleEnabled returns IsTrustedPlatformModuleEnabled
func (m AmdRomeBmLaunchInstancePlatformConfig) GetIsTrustedPlatformModuleEnabled() *bool {
return m.IsTrustedPlatformModuleEnabled
}
//GetIsMeasuredBootEnabled returns IsMeasuredBootEnabled
func (m AmdRomeBmLaunchInstancePlatformConfig) GetIsMeasuredBootEnabled() *bool {
return m.IsMeasuredBootEnabled
}
func (m AmdRomeBmLaunchInstancePlatformConfig) String() string {
return common.PointerString(m)
}
// MarshalJSON marshals to json representation
func (m AmdRomeBmLaunchInstancePlatformConfig) MarshalJSON() (buff []byte, e error) {
type MarshalTypeAmdRomeBmLaunchInstancePlatformConfig AmdRomeBmLaunchInstancePlatformConfig
s := struct {
DiscriminatorParam string `json:"type"`
MarshalTypeAmdRomeBmLaunchInstancePlatformConfig
}{
"AMD_ROME_BM",
(MarshalTypeAmdRomeBmLaunchInstancePlatformConfig)(m),
}
return json.Marshal(&s)
}

View file

@ -0,0 +1,65 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
// Core Services API
//
// Use the Core Services API to manage resources such as virtual cloud networks (VCNs),
// compute instances, and block storage volumes. For more information, see the console
// documentation for the Networking (https://docs.cloud.oracle.com/iaas/Content/Network/Concepts/overview.htm),
// Compute (https://docs.cloud.oracle.com/iaas/Content/Compute/Concepts/computeoverview.htm), and
// Block Volume (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/overview.htm) services.
//
package core
import (
"encoding/json"
"github.com/oracle/oci-go-sdk/v54/common"
)
// AmdRomeBmPlatformConfig The platform configuration of a bare metal instance that uses the AMD Rome platform.
type AmdRomeBmPlatformConfig struct {
// Whether Secure Boot is enabled on the instance.
IsSecureBootEnabled *bool `mandatory:"false" json:"isSecureBootEnabled"`
// Whether the Trusted Platform Module (TPM) is enabled on the instance.
IsTrustedPlatformModuleEnabled *bool `mandatory:"false" json:"isTrustedPlatformModuleEnabled"`
// Whether the Measured Boot feature is enabled on the instance.
IsMeasuredBootEnabled *bool `mandatory:"false" json:"isMeasuredBootEnabled"`
}
//GetIsSecureBootEnabled returns IsSecureBootEnabled
func (m AmdRomeBmPlatformConfig) GetIsSecureBootEnabled() *bool {
return m.IsSecureBootEnabled
}
//GetIsTrustedPlatformModuleEnabled returns IsTrustedPlatformModuleEnabled
func (m AmdRomeBmPlatformConfig) GetIsTrustedPlatformModuleEnabled() *bool {
return m.IsTrustedPlatformModuleEnabled
}
//GetIsMeasuredBootEnabled returns IsMeasuredBootEnabled
func (m AmdRomeBmPlatformConfig) GetIsMeasuredBootEnabled() *bool {
return m.IsMeasuredBootEnabled
}
func (m AmdRomeBmPlatformConfig) String() string {
return common.PointerString(m)
}
// MarshalJSON marshals to json representation
func (m AmdRomeBmPlatformConfig) MarshalJSON() (buff []byte, e error) {
type MarshalTypeAmdRomeBmPlatformConfig AmdRomeBmPlatformConfig
s := struct {
DiscriminatorParam string `json:"type"`
MarshalTypeAmdRomeBmPlatformConfig
}{
"AMD_ROME_BM",
(MarshalTypeAmdRomeBmPlatformConfig)(m),
}
return json.Marshal(&s)
}

View file

@ -0,0 +1,65 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
// Core Services API
//
// Use the Core Services API to manage resources such as virtual cloud networks (VCNs),
// compute instances, and block storage volumes. For more information, see the console
// documentation for the Networking (https://docs.cloud.oracle.com/iaas/Content/Network/Concepts/overview.htm),
// Compute (https://docs.cloud.oracle.com/iaas/Content/Compute/Concepts/computeoverview.htm), and
// Block Volume (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/overview.htm) services.
//
package core
import (
"encoding/json"
"github.com/oracle/oci-go-sdk/v54/common"
)
// AmdVmLaunchInstancePlatformConfig The platform configuration used when launching a virtual machine instance with the AMD platform.
type AmdVmLaunchInstancePlatformConfig struct {
// Whether Secure Boot is enabled on the instance.
IsSecureBootEnabled *bool `mandatory:"false" json:"isSecureBootEnabled"`
// Whether the Trusted Platform Module (TPM) is enabled on the instance.
IsTrustedPlatformModuleEnabled *bool `mandatory:"false" json:"isTrustedPlatformModuleEnabled"`
// Whether the Measured Boot feature is enabled on the instance.
IsMeasuredBootEnabled *bool `mandatory:"false" json:"isMeasuredBootEnabled"`
}
//GetIsSecureBootEnabled returns IsSecureBootEnabled
func (m AmdVmLaunchInstancePlatformConfig) GetIsSecureBootEnabled() *bool {
return m.IsSecureBootEnabled
}
//GetIsTrustedPlatformModuleEnabled returns IsTrustedPlatformModuleEnabled
func (m AmdVmLaunchInstancePlatformConfig) GetIsTrustedPlatformModuleEnabled() *bool {
return m.IsTrustedPlatformModuleEnabled
}
//GetIsMeasuredBootEnabled returns IsMeasuredBootEnabled
func (m AmdVmLaunchInstancePlatformConfig) GetIsMeasuredBootEnabled() *bool {
return m.IsMeasuredBootEnabled
}
func (m AmdVmLaunchInstancePlatformConfig) String() string {
return common.PointerString(m)
}
// MarshalJSON marshals to json representation
func (m AmdVmLaunchInstancePlatformConfig) MarshalJSON() (buff []byte, e error) {
type MarshalTypeAmdVmLaunchInstancePlatformConfig AmdVmLaunchInstancePlatformConfig
s := struct {
DiscriminatorParam string `json:"type"`
MarshalTypeAmdVmLaunchInstancePlatformConfig
}{
"AMD_VM",
(MarshalTypeAmdVmLaunchInstancePlatformConfig)(m),
}
return json.Marshal(&s)
}

View file

@ -0,0 +1,65 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
// Core Services API
//
// Use the Core Services API to manage resources such as virtual cloud networks (VCNs),
// compute instances, and block storage volumes. For more information, see the console
// documentation for the Networking (https://docs.cloud.oracle.com/iaas/Content/Network/Concepts/overview.htm),
// Compute (https://docs.cloud.oracle.com/iaas/Content/Compute/Concepts/computeoverview.htm), and
// Block Volume (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/overview.htm) services.
//
package core
import (
"encoding/json"
"github.com/oracle/oci-go-sdk/v54/common"
)
// AmdVmPlatformConfig The platform configuration of a virtual machine instance that uses the AMD platform.
type AmdVmPlatformConfig struct {
// Whether Secure Boot is enabled on the instance.
IsSecureBootEnabled *bool `mandatory:"false" json:"isSecureBootEnabled"`
// Whether the Trusted Platform Module (TPM) is enabled on the instance.
IsTrustedPlatformModuleEnabled *bool `mandatory:"false" json:"isTrustedPlatformModuleEnabled"`
// Whether the Measured Boot feature is enabled on the instance.
IsMeasuredBootEnabled *bool `mandatory:"false" json:"isMeasuredBootEnabled"`
}
//GetIsSecureBootEnabled returns IsSecureBootEnabled
func (m AmdVmPlatformConfig) GetIsSecureBootEnabled() *bool {
return m.IsSecureBootEnabled
}
//GetIsTrustedPlatformModuleEnabled returns IsTrustedPlatformModuleEnabled
func (m AmdVmPlatformConfig) GetIsTrustedPlatformModuleEnabled() *bool {
return m.IsTrustedPlatformModuleEnabled
}
//GetIsMeasuredBootEnabled returns IsMeasuredBootEnabled
func (m AmdVmPlatformConfig) GetIsMeasuredBootEnabled() *bool {
return m.IsMeasuredBootEnabled
}
func (m AmdVmPlatformConfig) String() string {
return common.PointerString(m)
}
// MarshalJSON marshals to json representation
func (m AmdVmPlatformConfig) MarshalJSON() (buff []byte, e error) {
type MarshalTypeAmdVmPlatformConfig AmdVmPlatformConfig
s := struct {
DiscriminatorParam string `json:"type"`
MarshalTypeAmdVmPlatformConfig
}{
"AMD_VM",
(MarshalTypeAmdVmPlatformConfig)(m),
}
return json.Marshal(&s)
}

View file

@ -0,0 +1,52 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
// Core Services API
//
// Use the Core Services API to manage resources such as virtual cloud networks (VCNs),
// compute instances, and block storage volumes. For more information, see the console
// documentation for the Networking (https://docs.cloud.oracle.com/iaas/Content/Network/Concepts/overview.htm),
// Compute (https://docs.cloud.oracle.com/iaas/Content/Compute/Concepts/computeoverview.htm), and
// Block Volume (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/overview.htm) services.
//
package core
import (
"github.com/oracle/oci-go-sdk/v54/common"
)
// AppCatalogListing Listing details.
type AppCatalogListing struct {
// Listing's contact URL.
ContactUrl *string `mandatory:"false" json:"contactUrl"`
// Description of the listing.
Description *string `mandatory:"false" json:"description"`
// The OCID of the listing.
ListingId *string `mandatory:"false" json:"listingId"`
// A user-friendly name. Does not have to be unique, and it's changeable.
// Avoid entering confidential information.
DisplayName *string `mandatory:"false" json:"displayName"`
// Date and time the listing was published, in RFC3339 (https://tools.ietf.org/html/rfc3339) format.
// Example: `2018-03-20T12:32:53.532Z`
TimePublished *common.SDKTime `mandatory:"false" json:"timePublished"`
// Publisher's logo URL.
PublisherLogoUrl *string `mandatory:"false" json:"publisherLogoUrl"`
// Name of the publisher who published this listing.
PublisherName *string `mandatory:"false" json:"publisherName"`
// Summary of the listing.
Summary *string `mandatory:"false" json:"summary"`
}
func (m AppCatalogListing) String() string {
return common.PointerString(m)
}

View file

@ -0,0 +1,89 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
// Core Services API
//
// Use the Core Services API to manage resources such as virtual cloud networks (VCNs),
// compute instances, and block storage volumes. For more information, see the console
// documentation for the Networking (https://docs.cloud.oracle.com/iaas/Content/Network/Concepts/overview.htm),
// Compute (https://docs.cloud.oracle.com/iaas/Content/Compute/Concepts/computeoverview.htm), and
// Block Volume (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/overview.htm) services.
//
package core
import (
"github.com/oracle/oci-go-sdk/v54/common"
)
// AppCatalogListingResourceVersion Listing Resource Version
type AppCatalogListingResourceVersion struct {
// The OCID of the listing this resource version belongs to.
ListingId *string `mandatory:"false" json:"listingId"`
// Date and time the listing resource version was published, in RFC3339 (https://tools.ietf.org/html/rfc3339) format.
// Example: `2018-03-20T12:32:53.532Z`
TimePublished *common.SDKTime `mandatory:"false" json:"timePublished"`
// OCID of the listing resource.
ListingResourceId *string `mandatory:"false" json:"listingResourceId"`
// Resource Version.
ListingResourceVersion *string `mandatory:"false" json:"listingResourceVersion"`
// List of regions that this listing resource version is available.
// For information about Regions, see
// Regions (https://docs.cloud.oracle.comGeneral/Concepts/regions.htm).
// Example: `["us-ashburn-1", "us-phoenix-1"]`
AvailableRegions []string `mandatory:"false" json:"availableRegions"`
// Array of shapes compatible with this resource.
// You may enumerate all available shapes by calling listShapes.
// Example: `["VM.Standard1.1", "VM.Standard1.2"]`
CompatibleShapes []string `mandatory:"false" json:"compatibleShapes"`
// List of accessible ports for instances launched with this listing resource version.
AccessiblePorts []int `mandatory:"false" json:"accessiblePorts"`
// Allowed actions for the listing resource.
AllowedActions []AppCatalogListingResourceVersionAllowedActionsEnum `mandatory:"false" json:"allowedActions,omitempty"`
}
func (m AppCatalogListingResourceVersion) String() string {
return common.PointerString(m)
}
// AppCatalogListingResourceVersionAllowedActionsEnum Enum with underlying type: string
type AppCatalogListingResourceVersionAllowedActionsEnum string
// Set of constants representing the allowable values for AppCatalogListingResourceVersionAllowedActionsEnum
const (
AppCatalogListingResourceVersionAllowedActionsSnapshot AppCatalogListingResourceVersionAllowedActionsEnum = "SNAPSHOT"
AppCatalogListingResourceVersionAllowedActionsBootVolumeDetach AppCatalogListingResourceVersionAllowedActionsEnum = "BOOT_VOLUME_DETACH"
AppCatalogListingResourceVersionAllowedActionsPreserveBootVolume AppCatalogListingResourceVersionAllowedActionsEnum = "PRESERVE_BOOT_VOLUME"
AppCatalogListingResourceVersionAllowedActionsSerialConsoleAccess AppCatalogListingResourceVersionAllowedActionsEnum = "SERIAL_CONSOLE_ACCESS"
AppCatalogListingResourceVersionAllowedActionsBootRecovery AppCatalogListingResourceVersionAllowedActionsEnum = "BOOT_RECOVERY"
AppCatalogListingResourceVersionAllowedActionsBackupBootVolume AppCatalogListingResourceVersionAllowedActionsEnum = "BACKUP_BOOT_VOLUME"
AppCatalogListingResourceVersionAllowedActionsCaptureConsoleHistory AppCatalogListingResourceVersionAllowedActionsEnum = "CAPTURE_CONSOLE_HISTORY"
)
var mappingAppCatalogListingResourceVersionAllowedActions = map[string]AppCatalogListingResourceVersionAllowedActionsEnum{
"SNAPSHOT": AppCatalogListingResourceVersionAllowedActionsSnapshot,
"BOOT_VOLUME_DETACH": AppCatalogListingResourceVersionAllowedActionsBootVolumeDetach,
"PRESERVE_BOOT_VOLUME": AppCatalogListingResourceVersionAllowedActionsPreserveBootVolume,
"SERIAL_CONSOLE_ACCESS": AppCatalogListingResourceVersionAllowedActionsSerialConsoleAccess,
"BOOT_RECOVERY": AppCatalogListingResourceVersionAllowedActionsBootRecovery,
"BACKUP_BOOT_VOLUME": AppCatalogListingResourceVersionAllowedActionsBackupBootVolume,
"CAPTURE_CONSOLE_HISTORY": AppCatalogListingResourceVersionAllowedActionsCaptureConsoleHistory,
}
// GetAppCatalogListingResourceVersionAllowedActionsEnumValues Enumerates the set of values for AppCatalogListingResourceVersionAllowedActionsEnum
func GetAppCatalogListingResourceVersionAllowedActionsEnumValues() []AppCatalogListingResourceVersionAllowedActionsEnum {
values := make([]AppCatalogListingResourceVersionAllowedActionsEnum, 0)
for _, v := range mappingAppCatalogListingResourceVersionAllowedActions {
values = append(values, v)
}
return values
}

View file

@ -0,0 +1,45 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
// Core Services API
//
// Use the Core Services API to manage resources such as virtual cloud networks (VCNs),
// compute instances, and block storage volumes. For more information, see the console
// documentation for the Networking (https://docs.cloud.oracle.com/iaas/Content/Network/Concepts/overview.htm),
// Compute (https://docs.cloud.oracle.com/iaas/Content/Compute/Concepts/computeoverview.htm), and
// Block Volume (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/overview.htm) services.
//
package core
import (
"github.com/oracle/oci-go-sdk/v54/common"
)
// AppCatalogListingResourceVersionAgreements Agreements for a listing resource version.
type AppCatalogListingResourceVersionAgreements struct {
// The OCID of the listing associated with these agreements.
ListingId *string `mandatory:"false" json:"listingId"`
// Listing resource version associated with these agreements.
ListingResourceVersion *string `mandatory:"false" json:"listingResourceVersion"`
// Oracle TOU link
OracleTermsOfUseLink *string `mandatory:"false" json:"oracleTermsOfUseLink"`
// EULA link
EulaLink *string `mandatory:"false" json:"eulaLink"`
// Date and time the agreements were retrieved, in RFC3339 (https://tools.ietf.org/html/rfc3339) format.
// Example: `2018-03-20T12:32:53.532Z`
TimeRetrieved *common.SDKTime `mandatory:"false" json:"timeRetrieved"`
// A generated signature for this agreement retrieval operation which should be used in the create subscription call.
Signature *string `mandatory:"false" json:"signature"`
}
func (m AppCatalogListingResourceVersionAgreements) String() string {
return common.PointerString(m)
}

View file

@ -0,0 +1,39 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
// Core Services API
//
// Use the Core Services API to manage resources such as virtual cloud networks (VCNs),
// compute instances, and block storage volumes. For more information, see the console
// documentation for the Networking (https://docs.cloud.oracle.com/iaas/Content/Network/Concepts/overview.htm),
// Compute (https://docs.cloud.oracle.com/iaas/Content/Compute/Concepts/computeoverview.htm), and
// Block Volume (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/overview.htm) services.
//
package core
import (
"github.com/oracle/oci-go-sdk/v54/common"
)
// AppCatalogListingResourceVersionSummary Listing Resource Version summary
type AppCatalogListingResourceVersionSummary struct {
// The OCID of the listing this resource version belongs to.
ListingId *string `mandatory:"false" json:"listingId"`
// Date and time the listing resource version was published, in RFC3339 (https://tools.ietf.org/html/rfc3339) format.
// Example: `2018-03-20T12:32:53.532Z`
TimePublished *common.SDKTime `mandatory:"false" json:"timePublished"`
// OCID of the listing resource.
ListingResourceId *string `mandatory:"false" json:"listingResourceId"`
// Resource Version.
ListingResourceVersion *string `mandatory:"false" json:"listingResourceVersion"`
}
func (m AppCatalogListingResourceVersionSummary) String() string {
return common.PointerString(m)
}

View file

@ -0,0 +1,39 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
// Core Services API
//
// Use the Core Services API to manage resources such as virtual cloud networks (VCNs),
// compute instances, and block storage volumes. For more information, see the console
// documentation for the Networking (https://docs.cloud.oracle.com/iaas/Content/Network/Concepts/overview.htm),
// Compute (https://docs.cloud.oracle.com/iaas/Content/Compute/Concepts/computeoverview.htm), and
// Block Volume (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/overview.htm) services.
//
package core
import (
"github.com/oracle/oci-go-sdk/v54/common"
)
// AppCatalogListingSummary A summary of a listing.
type AppCatalogListingSummary struct {
// the region free ocid of the listing resource.
ListingId *string `mandatory:"false" json:"listingId"`
// A user-friendly name. Does not have to be unique, and it's changeable.
// Avoid entering confidential information.
DisplayName *string `mandatory:"false" json:"displayName"`
// The short summary for the listing.
Summary *string `mandatory:"false" json:"summary"`
// The name of the publisher who published this listing.
PublisherName *string `mandatory:"false" json:"publisherName"`
}
func (m AppCatalogListingSummary) String() string {
return common.PointerString(m)
}

View file

@ -0,0 +1,52 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
// Core Services API
//
// Use the Core Services API to manage resources such as virtual cloud networks (VCNs),
// compute instances, and block storage volumes. For more information, see the console
// documentation for the Networking (https://docs.cloud.oracle.com/iaas/Content/Network/Concepts/overview.htm),
// Compute (https://docs.cloud.oracle.com/iaas/Content/Compute/Concepts/computeoverview.htm), and
// Block Volume (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/overview.htm) services.
//
package core
import (
"github.com/oracle/oci-go-sdk/v54/common"
)
// AppCatalogSubscription a subscription for a listing resource version.
type AppCatalogSubscription struct {
// Name of the publisher who published this listing.
PublisherName *string `mandatory:"false" json:"publisherName"`
// The ocid of the listing resource.
ListingId *string `mandatory:"false" json:"listingId"`
// Listing resource version.
ListingResourceVersion *string `mandatory:"false" json:"listingResourceVersion"`
// Listing resource id.
ListingResourceId *string `mandatory:"false" json:"listingResourceId"`
// A user-friendly name. Does not have to be unique, and it's changeable.
// Avoid entering confidential information.
DisplayName *string `mandatory:"false" json:"displayName"`
// The short summary to the listing.
Summary *string `mandatory:"false" json:"summary"`
// The compartmentID of the subscription.
CompartmentId *string `mandatory:"false" json:"compartmentId"`
// Date and time at which the subscription was created, in RFC3339 (https://tools.ietf.org/html/rfc3339) format.
// Example: `2018-03-20T12:32:53.532Z`
TimeCreated *common.SDKTime `mandatory:"false" json:"timeCreated"`
}
func (m AppCatalogSubscription) String() string {
return common.PointerString(m)
}

View file

@ -0,0 +1,52 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
// Core Services API
//
// Use the Core Services API to manage resources such as virtual cloud networks (VCNs),
// compute instances, and block storage volumes. For more information, see the console
// documentation for the Networking (https://docs.cloud.oracle.com/iaas/Content/Network/Concepts/overview.htm),
// Compute (https://docs.cloud.oracle.com/iaas/Content/Compute/Concepts/computeoverview.htm), and
// Block Volume (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/overview.htm) services.
//
package core
import (
"github.com/oracle/oci-go-sdk/v54/common"
)
// AppCatalogSubscriptionSummary a subscription summary for a listing resource version.
type AppCatalogSubscriptionSummary struct {
// Name of the publisher who published this listing.
PublisherName *string `mandatory:"false" json:"publisherName"`
// The ocid of the listing resource.
ListingId *string `mandatory:"false" json:"listingId"`
// Listing resource version.
ListingResourceVersion *string `mandatory:"false" json:"listingResourceVersion"`
// Listing resource id.
ListingResourceId *string `mandatory:"false" json:"listingResourceId"`
// A user-friendly name. Does not have to be unique, and it's changeable.
// Avoid entering confidential information.
DisplayName *string `mandatory:"false" json:"displayName"`
// The short summary to the listing.
Summary *string `mandatory:"false" json:"summary"`
// The compartmentID of the subscription.
CompartmentId *string `mandatory:"false" json:"compartmentId"`
// Date and time at which the subscription was created, in RFC3339 (https://tools.ietf.org/html/rfc3339) format.
// Example: `2018-03-20T12:32:53.532Z`
TimeCreated *common.SDKTime `mandatory:"false" json:"timeCreated"`
}
func (m AppCatalogSubscriptionSummary) String() string {
return common.PointerString(m)
}

View file

@ -0,0 +1,40 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
// Core Services API
//
// Use the Core Services API to manage resources such as virtual cloud networks (VCNs),
// compute instances, and block storage volumes. For more information, see the console
// documentation for the Networking (https://docs.cloud.oracle.com/iaas/Content/Network/Concepts/overview.htm),
// Compute (https://docs.cloud.oracle.com/iaas/Content/Compute/Concepts/computeoverview.htm), and
// Block Volume (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/overview.htm) services.
//
package core
import (
"github.com/oracle/oci-go-sdk/v54/common"
)
// AttachBootVolumeDetails The representation of AttachBootVolumeDetails
type AttachBootVolumeDetails struct {
// The OCID of the boot volume.
BootVolumeId *string `mandatory:"true" json:"bootVolumeId"`
// The OCID of the instance.
InstanceId *string `mandatory:"true" json:"instanceId"`
// A user-friendly name. Does not have to be unique, and it's changeable.
// Avoid entering confidential information.
DisplayName *string `mandatory:"false" json:"displayName"`
// Refer the top-level definition of encryptionInTransitType.
// The default value is NONE.
EncryptionInTransitType EncryptionInTransitTypeEnum `mandatory:"false" json:"encryptionInTransitType,omitempty"`
}
func (m AttachBootVolumeDetails) String() string {
return common.PointerString(m)
}

View file

@ -0,0 +1,84 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
package core
import (
"github.com/oracle/oci-go-sdk/v54/common"
"net/http"
)
// AttachBootVolumeRequest wrapper for the AttachBootVolume operation
//
// See also
//
// Click https://docs.cloud.oracle.com/en-us/iaas/tools/go-sdk-examples/latest/core/AttachBootVolume.go.html to see an example of how to use AttachBootVolumeRequest.
type AttachBootVolumeRequest struct {
// Attach boot volume request
AttachBootVolumeDetails `contributesTo:"body"`
// A token that uniquely identifies a request so it can be retried in case of a timeout or
// server error without risk of executing that same action again. Retry tokens expire after 24
// hours, but can be invalidated before then due to conflicting operations (for example, if a resource
// has been deleted and purged from the system, then a retry of the original creation request
// may be rejected).
OpcRetryToken *string `mandatory:"false" contributesTo:"header" name:"opc-retry-token"`
// Unique Oracle-assigned identifier for the request.
// If you need to contact Oracle about a particular request, please provide the request ID.
OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"`
// Metadata about the request. This information will not be transmitted to the service, but
// represents information that the SDK will consume to drive retry behavior.
RequestMetadata common.RequestMetadata
}
func (request AttachBootVolumeRequest) String() string {
return common.PointerString(request)
}
// HTTPRequest implements the OCIRequest interface
func (request AttachBootVolumeRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {
return common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)
}
// BinaryRequestBody implements the OCIRequest interface
func (request AttachBootVolumeRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {
return nil, false
}
// RetryPolicy implements the OCIRetryableRequest interface. This retrieves the specified retry policy.
func (request AttachBootVolumeRequest) RetryPolicy() *common.RetryPolicy {
return request.RequestMetadata.RetryPolicy
}
// AttachBootVolumeResponse wrapper for the AttachBootVolume operation
type AttachBootVolumeResponse struct {
// The underlying http response
RawResponse *http.Response
// The BootVolumeAttachment instance
BootVolumeAttachment `presentIn:"body"`
// For optimistic concurrency control. See `if-match`.
Etag *string `presentIn:"header" name:"etag"`
// Unique Oracle-assigned identifier for the request. If you need to contact
// Oracle about a particular request, please provide the request ID.
OpcRequestId *string `presentIn:"header" name:"opc-request-id"`
}
func (response AttachBootVolumeResponse) String() string {
return common.PointerString(response)
}
// HTTPResponse implements the OCIResponse interface
func (response AttachBootVolumeResponse) HTTPResponse() *http.Response {
return response.RawResponse
}

View file

@ -0,0 +1,93 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
// Core Services API
//
// Use the Core Services API to manage resources such as virtual cloud networks (VCNs),
// compute instances, and block storage volumes. For more information, see the console
// documentation for the Networking (https://docs.cloud.oracle.com/iaas/Content/Network/Concepts/overview.htm),
// Compute (https://docs.cloud.oracle.com/iaas/Content/Compute/Concepts/computeoverview.htm), and
// Block Volume (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/overview.htm) services.
//
package core
import (
"encoding/json"
"github.com/oracle/oci-go-sdk/v54/common"
)
// AttachEmulatedVolumeDetails The representation of AttachEmulatedVolumeDetails
type AttachEmulatedVolumeDetails struct {
// The OCID of the instance.
InstanceId *string `mandatory:"true" json:"instanceId"`
// The OCID of the volume.
VolumeId *string `mandatory:"true" json:"volumeId"`
// The device name. To retrieve a list of devices for a given instance, see ListInstanceDevices.
Device *string `mandatory:"false" json:"device"`
// A user-friendly name. Does not have to be unique, and it's changeable.
// Avoid entering confidential information.
DisplayName *string `mandatory:"false" json:"displayName"`
// Whether the attachment was created in read-only mode.
IsReadOnly *bool `mandatory:"false" json:"isReadOnly"`
// Whether the attachment should be created in shareable mode. If an attachment
// is created in shareable mode, then other instances can attach the same volume, provided
// that they also create their attachments in shareable mode. Only certain volume types can
// be attached in shareable mode. Defaults to false if not specified.
IsShareable *bool `mandatory:"false" json:"isShareable"`
}
//GetDevice returns Device
func (m AttachEmulatedVolumeDetails) GetDevice() *string {
return m.Device
}
//GetDisplayName returns DisplayName
func (m AttachEmulatedVolumeDetails) GetDisplayName() *string {
return m.DisplayName
}
//GetInstanceId returns InstanceId
func (m AttachEmulatedVolumeDetails) GetInstanceId() *string {
return m.InstanceId
}
//GetIsReadOnly returns IsReadOnly
func (m AttachEmulatedVolumeDetails) GetIsReadOnly() *bool {
return m.IsReadOnly
}
//GetIsShareable returns IsShareable
func (m AttachEmulatedVolumeDetails) GetIsShareable() *bool {
return m.IsShareable
}
//GetVolumeId returns VolumeId
func (m AttachEmulatedVolumeDetails) GetVolumeId() *string {
return m.VolumeId
}
func (m AttachEmulatedVolumeDetails) String() string {
return common.PointerString(m)
}
// MarshalJSON marshals to json representation
func (m AttachEmulatedVolumeDetails) MarshalJSON() (buff []byte, e error) {
type MarshalTypeAttachEmulatedVolumeDetails AttachEmulatedVolumeDetails
s := struct {
DiscriminatorParam string `json:"type"`
MarshalTypeAttachEmulatedVolumeDetails
}{
"emulated",
(MarshalTypeAttachEmulatedVolumeDetails)(m),
}
return json.Marshal(&s)
}

View file

@ -0,0 +1,100 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
// Core Services API
//
// Use the Core Services API to manage resources such as virtual cloud networks (VCNs),
// compute instances, and block storage volumes. For more information, see the console
// documentation for the Networking (https://docs.cloud.oracle.com/iaas/Content/Network/Concepts/overview.htm),
// Compute (https://docs.cloud.oracle.com/iaas/Content/Compute/Concepts/computeoverview.htm), and
// Block Volume (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/overview.htm) services.
//
package core
import (
"encoding/json"
"github.com/oracle/oci-go-sdk/v54/common"
)
// AttachIScsiVolumeDetails The representation of AttachIScsiVolumeDetails
type AttachIScsiVolumeDetails struct {
// The OCID of the instance.
InstanceId *string `mandatory:"true" json:"instanceId"`
// The OCID of the volume.
VolumeId *string `mandatory:"true" json:"volumeId"`
// The device name. To retrieve a list of devices for a given instance, see ListInstanceDevices.
Device *string `mandatory:"false" json:"device"`
// A user-friendly name. Does not have to be unique, and it's changeable.
// Avoid entering confidential information.
DisplayName *string `mandatory:"false" json:"displayName"`
// Whether the attachment was created in read-only mode.
IsReadOnly *bool `mandatory:"false" json:"isReadOnly"`
// Whether the attachment should be created in shareable mode. If an attachment
// is created in shareable mode, then other instances can attach the same volume, provided
// that they also create their attachments in shareable mode. Only certain volume types can
// be attached in shareable mode. Defaults to false if not specified.
IsShareable *bool `mandatory:"false" json:"isShareable"`
// Whether to use CHAP authentication for the volume attachment. Defaults to false.
UseChap *bool `mandatory:"false" json:"useChap"`
// Refer the top-level definition of encryptionInTransitType.
// The default value is NONE.
EncryptionInTransitType EncryptionInTransitTypeEnum `mandatory:"false" json:"encryptionInTransitType,omitempty"`
}
//GetDevice returns Device
func (m AttachIScsiVolumeDetails) GetDevice() *string {
return m.Device
}
//GetDisplayName returns DisplayName
func (m AttachIScsiVolumeDetails) GetDisplayName() *string {
return m.DisplayName
}
//GetInstanceId returns InstanceId
func (m AttachIScsiVolumeDetails) GetInstanceId() *string {
return m.InstanceId
}
//GetIsReadOnly returns IsReadOnly
func (m AttachIScsiVolumeDetails) GetIsReadOnly() *bool {
return m.IsReadOnly
}
//GetIsShareable returns IsShareable
func (m AttachIScsiVolumeDetails) GetIsShareable() *bool {
return m.IsShareable
}
//GetVolumeId returns VolumeId
func (m AttachIScsiVolumeDetails) GetVolumeId() *string {
return m.VolumeId
}
func (m AttachIScsiVolumeDetails) String() string {
return common.PointerString(m)
}
// MarshalJSON marshals to json representation
func (m AttachIScsiVolumeDetails) MarshalJSON() (buff []byte, e error) {
type MarshalTypeAttachIScsiVolumeDetails AttachIScsiVolumeDetails
s := struct {
DiscriminatorParam string `json:"type"`
MarshalTypeAttachIScsiVolumeDetails
}{
"iscsi",
(MarshalTypeAttachIScsiVolumeDetails)(m),
}
return json.Marshal(&s)
}

View file

@ -0,0 +1,29 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
// Core Services API
//
// Use the Core Services API to manage resources such as virtual cloud networks (VCNs),
// compute instances, and block storage volumes. For more information, see the console
// documentation for the Networking (https://docs.cloud.oracle.com/iaas/Content/Network/Concepts/overview.htm),
// Compute (https://docs.cloud.oracle.com/iaas/Content/Compute/Concepts/computeoverview.htm), and
// Block Volume (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/overview.htm) services.
//
package core
import (
"github.com/oracle/oci-go-sdk/v54/common"
)
// AttachInstancePoolInstanceDetails An instance that is to be attached to an instance pool.
type AttachInstancePoolInstanceDetails struct {
// The OCID (https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm) of the instance.
InstanceId *string `mandatory:"true" json:"instanceId"`
}
func (m AttachInstancePoolInstanceDetails) String() string {
return common.PointerString(m)
}

View file

@ -0,0 +1,94 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
package core
import (
"github.com/oracle/oci-go-sdk/v54/common"
"net/http"
)
// AttachInstancePoolInstanceRequest wrapper for the AttachInstancePoolInstance operation
//
// See also
//
// Click https://docs.cloud.oracle.com/en-us/iaas/tools/go-sdk-examples/latest/core/AttachInstancePoolInstance.go.html to see an example of how to use AttachInstancePoolInstanceRequest.
type AttachInstancePoolInstanceRequest struct {
// The OCID (https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm) of the instance pool.
InstancePoolId *string `mandatory:"true" contributesTo:"path" name:"instancePoolId"`
// Attach an instance to a pool
AttachInstancePoolInstanceDetails `contributesTo:"body"`
// A token that uniquely identifies a request so it can be retried in case of a timeout or
// server error without risk of executing that same action again. Retry tokens expire after 24
// hours, but can be invalidated before then due to conflicting operations (for example, if a resource
// has been deleted and purged from the system, then a retry of the original creation request
// may be rejected).
OpcRetryToken *string `mandatory:"false" contributesTo:"header" name:"opc-retry-token"`
// Unique Oracle-assigned identifier for the request.
// If you need to contact Oracle about a particular request, please provide the request ID.
OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"`
// Metadata about the request. This information will not be transmitted to the service, but
// represents information that the SDK will consume to drive retry behavior.
RequestMetadata common.RequestMetadata
}
func (request AttachInstancePoolInstanceRequest) String() string {
return common.PointerString(request)
}
// HTTPRequest implements the OCIRequest interface
func (request AttachInstancePoolInstanceRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {
return common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)
}
// BinaryRequestBody implements the OCIRequest interface
func (request AttachInstancePoolInstanceRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {
return nil, false
}
// RetryPolicy implements the OCIRetryableRequest interface. This retrieves the specified retry policy.
func (request AttachInstancePoolInstanceRequest) RetryPolicy() *common.RetryPolicy {
return request.RequestMetadata.RetryPolicy
}
// AttachInstancePoolInstanceResponse wrapper for the AttachInstancePoolInstance operation
type AttachInstancePoolInstanceResponse struct {
// The underlying http response
RawResponse *http.Response
// The InstancePoolInstance instance
InstancePoolInstance `presentIn:"body"`
// Unique Oracle-assigned identifier for the request. If you need to contact
// Oracle about a particular request, please provide the request ID.
OpcRequestId *string `presentIn:"header" name:"opc-request-id"`
// For optimistic concurrency control. See `if-match`.
Etag *string `presentIn:"header" name:"etag"`
// The OCID (https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm) of the work request. Use GetWorkRequest (https://docs.cloud.oracle.com/api/#/en/workrequests/20160918/WorkRequest/GetWorkRequest)
// with this ID to track the status of the request.
OpcWorkRequestId *string `presentIn:"header" name:"opc-work-request-id"`
// Location of the resource.
Location *string `presentIn:"header" name:"location"`
}
func (response AttachInstancePoolInstanceResponse) String() string {
return common.PointerString(response)
}
// HTTPResponse implements the OCIResponse interface
func (response AttachInstancePoolInstanceResponse) HTTPResponse() *http.Response {
return response.RawResponse
}

View file

@ -0,0 +1,40 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
// Core Services API
//
// Use the Core Services API to manage resources such as virtual cloud networks (VCNs),
// compute instances, and block storage volumes. For more information, see the console
// documentation for the Networking (https://docs.cloud.oracle.com/iaas/Content/Network/Concepts/overview.htm),
// Compute (https://docs.cloud.oracle.com/iaas/Content/Compute/Concepts/computeoverview.htm), and
// Block Volume (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/overview.htm) services.
//
package core
import (
"github.com/oracle/oci-go-sdk/v54/common"
)
// AttachLoadBalancerDetails Represents a load balancer that is to be attached to an instance pool.
type AttachLoadBalancerDetails struct {
// The OCID (https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm) of the load balancer to attach to the instance pool.
LoadBalancerId *string `mandatory:"true" json:"loadBalancerId"`
// The name of the backend set on the load balancer to add instances to.
BackendSetName *string `mandatory:"true" json:"backendSetName"`
// The port value to use when creating the backend set.
Port *int `mandatory:"true" json:"port"`
// Indicates which VNIC on each instance in the pool should be used to associate with the load balancer.
// Possible values are "PrimaryVnic" or the displayName of one of the secondary VNICs on the instance configuration
// that is associated with the instance pool.
VnicSelection *string `mandatory:"true" json:"vnicSelection"`
}
func (m AttachLoadBalancerDetails) String() string {
return common.PointerString(m)
}

View file

@ -0,0 +1,92 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
package core
import (
"github.com/oracle/oci-go-sdk/v54/common"
"net/http"
)
// AttachLoadBalancerRequest wrapper for the AttachLoadBalancer operation
//
// See also
//
// Click https://docs.cloud.oracle.com/en-us/iaas/tools/go-sdk-examples/latest/core/AttachLoadBalancer.go.html to see an example of how to use AttachLoadBalancerRequest.
type AttachLoadBalancerRequest struct {
// The OCID (https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm) of the instance pool.
InstancePoolId *string `mandatory:"true" contributesTo:"path" name:"instancePoolId"`
// Load balancer being attached
AttachLoadBalancerDetails `contributesTo:"body"`
// A token that uniquely identifies a request so it can be retried in case of a timeout or
// server error without risk of executing that same action again. Retry tokens expire after 24
// hours, but can be invalidated before then due to conflicting operations (for example, if a resource
// has been deleted and purged from the system, then a retry of the original creation request
// may be rejected).
OpcRetryToken *string `mandatory:"false" contributesTo:"header" name:"opc-retry-token"`
// For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match`
// parameter to the value of the etag from a previous GET or POST response for that resource. The resource
// will be updated or deleted only if the etag you provide matches the resource's current etag value.
IfMatch *string `mandatory:"false" contributesTo:"header" name:"if-match"`
// Unique Oracle-assigned identifier for the request.
// If you need to contact Oracle about a particular request, please provide the request ID.
OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"`
// Metadata about the request. This information will not be transmitted to the service, but
// represents information that the SDK will consume to drive retry behavior.
RequestMetadata common.RequestMetadata
}
func (request AttachLoadBalancerRequest) String() string {
return common.PointerString(request)
}
// HTTPRequest implements the OCIRequest interface
func (request AttachLoadBalancerRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {
return common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)
}
// BinaryRequestBody implements the OCIRequest interface
func (request AttachLoadBalancerRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {
return nil, false
}
// RetryPolicy implements the OCIRetryableRequest interface. This retrieves the specified retry policy.
func (request AttachLoadBalancerRequest) RetryPolicy() *common.RetryPolicy {
return request.RequestMetadata.RetryPolicy
}
// AttachLoadBalancerResponse wrapper for the AttachLoadBalancer operation
type AttachLoadBalancerResponse struct {
// The underlying http response
RawResponse *http.Response
// The InstancePool instance
InstancePool `presentIn:"body"`
// For optimistic concurrency control. See `if-match`.
Etag *string `presentIn:"header" name:"etag"`
// Unique Oracle-assigned identifier for the request. If you need to contact
// Oracle about a particular request, please provide the request ID.
OpcRequestId *string `presentIn:"header" name:"opc-request-id"`
}
func (response AttachLoadBalancerResponse) String() string {
return common.PointerString(response)
}
// HTTPResponse implements the OCIResponse interface
func (response AttachLoadBalancerResponse) HTTPResponse() *http.Response {
return response.RawResponse
}

View file

@ -0,0 +1,96 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
// Core Services API
//
// Use the Core Services API to manage resources such as virtual cloud networks (VCNs),
// compute instances, and block storage volumes. For more information, see the console
// documentation for the Networking (https://docs.cloud.oracle.com/iaas/Content/Network/Concepts/overview.htm),
// Compute (https://docs.cloud.oracle.com/iaas/Content/Compute/Concepts/computeoverview.htm), and
// Block Volume (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/overview.htm) services.
//
package core
import (
"encoding/json"
"github.com/oracle/oci-go-sdk/v54/common"
)
// AttachParavirtualizedVolumeDetails The representation of AttachParavirtualizedVolumeDetails
type AttachParavirtualizedVolumeDetails struct {
// The OCID of the instance.
InstanceId *string `mandatory:"true" json:"instanceId"`
// The OCID of the volume.
VolumeId *string `mandatory:"true" json:"volumeId"`
// The device name. To retrieve a list of devices for a given instance, see ListInstanceDevices.
Device *string `mandatory:"false" json:"device"`
// A user-friendly name. Does not have to be unique, and it's changeable.
// Avoid entering confidential information.
DisplayName *string `mandatory:"false" json:"displayName"`
// Whether the attachment was created in read-only mode.
IsReadOnly *bool `mandatory:"false" json:"isReadOnly"`
// Whether the attachment should be created in shareable mode. If an attachment
// is created in shareable mode, then other instances can attach the same volume, provided
// that they also create their attachments in shareable mode. Only certain volume types can
// be attached in shareable mode. Defaults to false if not specified.
IsShareable *bool `mandatory:"false" json:"isShareable"`
// Whether to enable in-transit encryption for the data volume's paravirtualized attachment. The default value is false.
IsPvEncryptionInTransitEnabled *bool `mandatory:"false" json:"isPvEncryptionInTransitEnabled"`
}
//GetDevice returns Device
func (m AttachParavirtualizedVolumeDetails) GetDevice() *string {
return m.Device
}
//GetDisplayName returns DisplayName
func (m AttachParavirtualizedVolumeDetails) GetDisplayName() *string {
return m.DisplayName
}
//GetInstanceId returns InstanceId
func (m AttachParavirtualizedVolumeDetails) GetInstanceId() *string {
return m.InstanceId
}
//GetIsReadOnly returns IsReadOnly
func (m AttachParavirtualizedVolumeDetails) GetIsReadOnly() *bool {
return m.IsReadOnly
}
//GetIsShareable returns IsShareable
func (m AttachParavirtualizedVolumeDetails) GetIsShareable() *bool {
return m.IsShareable
}
//GetVolumeId returns VolumeId
func (m AttachParavirtualizedVolumeDetails) GetVolumeId() *string {
return m.VolumeId
}
func (m AttachParavirtualizedVolumeDetails) String() string {
return common.PointerString(m)
}
// MarshalJSON marshals to json representation
func (m AttachParavirtualizedVolumeDetails) MarshalJSON() (buff []byte, e error) {
type MarshalTypeAttachParavirtualizedVolumeDetails AttachParavirtualizedVolumeDetails
s := struct {
DiscriminatorParam string `json:"type"`
MarshalTypeAttachParavirtualizedVolumeDetails
}{
"paravirtualized",
(MarshalTypeAttachParavirtualizedVolumeDetails)(m),
}
return json.Marshal(&s)
}

View file

@ -0,0 +1,93 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
// Core Services API
//
// Use the Core Services API to manage resources such as virtual cloud networks (VCNs),
// compute instances, and block storage volumes. For more information, see the console
// documentation for the Networking (https://docs.cloud.oracle.com/iaas/Content/Network/Concepts/overview.htm),
// Compute (https://docs.cloud.oracle.com/iaas/Content/Compute/Concepts/computeoverview.htm), and
// Block Volume (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/overview.htm) services.
//
package core
import (
"encoding/json"
"github.com/oracle/oci-go-sdk/v54/common"
)
// AttachServiceDeterminedVolumeDetails The representation of AttachServiceDeterminedVolumeDetails
type AttachServiceDeterminedVolumeDetails struct {
// The OCID of the instance.
InstanceId *string `mandatory:"true" json:"instanceId"`
// The OCID of the volume.
VolumeId *string `mandatory:"true" json:"volumeId"`
// The device name. To retrieve a list of devices for a given instance, see ListInstanceDevices.
Device *string `mandatory:"false" json:"device"`
// A user-friendly name. Does not have to be unique, and it's changeable.
// Avoid entering confidential information.
DisplayName *string `mandatory:"false" json:"displayName"`
// Whether the attachment was created in read-only mode.
IsReadOnly *bool `mandatory:"false" json:"isReadOnly"`
// Whether the attachment should be created in shareable mode. If an attachment
// is created in shareable mode, then other instances can attach the same volume, provided
// that they also create their attachments in shareable mode. Only certain volume types can
// be attached in shareable mode. Defaults to false if not specified.
IsShareable *bool `mandatory:"false" json:"isShareable"`
}
//GetDevice returns Device
func (m AttachServiceDeterminedVolumeDetails) GetDevice() *string {
return m.Device
}
//GetDisplayName returns DisplayName
func (m AttachServiceDeterminedVolumeDetails) GetDisplayName() *string {
return m.DisplayName
}
//GetInstanceId returns InstanceId
func (m AttachServiceDeterminedVolumeDetails) GetInstanceId() *string {
return m.InstanceId
}
//GetIsReadOnly returns IsReadOnly
func (m AttachServiceDeterminedVolumeDetails) GetIsReadOnly() *bool {
return m.IsReadOnly
}
//GetIsShareable returns IsShareable
func (m AttachServiceDeterminedVolumeDetails) GetIsShareable() *bool {
return m.IsShareable
}
//GetVolumeId returns VolumeId
func (m AttachServiceDeterminedVolumeDetails) GetVolumeId() *string {
return m.VolumeId
}
func (m AttachServiceDeterminedVolumeDetails) String() string {
return common.PointerString(m)
}
// MarshalJSON marshals to json representation
func (m AttachServiceDeterminedVolumeDetails) MarshalJSON() (buff []byte, e error) {
type MarshalTypeAttachServiceDeterminedVolumeDetails AttachServiceDeterminedVolumeDetails
s := struct {
DiscriminatorParam string `json:"type"`
MarshalTypeAttachServiceDeterminedVolumeDetails
}{
"service_determined",
(MarshalTypeAttachServiceDeterminedVolumeDetails)(m),
}
return json.Marshal(&s)
}

View file

@ -0,0 +1,82 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
package core
import (
"github.com/oracle/oci-go-sdk/v54/common"
"net/http"
)
// AttachServiceIdRequest wrapper for the AttachServiceId operation
//
// See also
//
// Click https://docs.cloud.oracle.com/en-us/iaas/tools/go-sdk-examples/latest/core/AttachServiceId.go.html to see an example of how to use AttachServiceIdRequest.
type AttachServiceIdRequest struct {
// The service gateway's OCID (https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm).
ServiceGatewayId *string `mandatory:"true" contributesTo:"path" name:"serviceGatewayId"`
// ServiceId of Service to be attached to a service gateway.
AttachServiceDetails ServiceIdRequestDetails `contributesTo:"body"`
// For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match`
// parameter to the value of the etag from a previous GET or POST response for that resource. The resource
// will be updated or deleted only if the etag you provide matches the resource's current etag value.
IfMatch *string `mandatory:"false" contributesTo:"header" name:"if-match"`
// Unique Oracle-assigned identifier for the request.
// If you need to contact Oracle about a particular request, please provide the request ID.
OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"`
// Metadata about the request. This information will not be transmitted to the service, but
// represents information that the SDK will consume to drive retry behavior.
RequestMetadata common.RequestMetadata
}
func (request AttachServiceIdRequest) String() string {
return common.PointerString(request)
}
// HTTPRequest implements the OCIRequest interface
func (request AttachServiceIdRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {
return common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)
}
// BinaryRequestBody implements the OCIRequest interface
func (request AttachServiceIdRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {
return nil, false
}
// RetryPolicy implements the OCIRetryableRequest interface. This retrieves the specified retry policy.
func (request AttachServiceIdRequest) RetryPolicy() *common.RetryPolicy {
return request.RequestMetadata.RetryPolicy
}
// AttachServiceIdResponse wrapper for the AttachServiceId operation
type AttachServiceIdResponse struct {
// The underlying http response
RawResponse *http.Response
// The ServiceGateway instance
ServiceGateway `presentIn:"body"`
// Unique Oracle-assigned identifier for the request. If you need to contact
// Oracle about a particular request, please provide the request ID.
OpcRequestId *string `presentIn:"header" name:"opc-request-id"`
}
func (response AttachServiceIdResponse) String() string {
return common.PointerString(response)
}
// HTTPResponse implements the OCIResponse interface
func (response AttachServiceIdResponse) HTTPResponse() *http.Response {
return response.RawResponse
}

View file

@ -0,0 +1,41 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
// Core Services API
//
// Use the Core Services API to manage resources such as virtual cloud networks (VCNs),
// compute instances, and block storage volumes. For more information, see the console
// documentation for the Networking (https://docs.cloud.oracle.com/iaas/Content/Network/Concepts/overview.htm),
// Compute (https://docs.cloud.oracle.com/iaas/Content/Compute/Concepts/computeoverview.htm), and
// Block Volume (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/overview.htm) services.
//
package core
import (
"github.com/oracle/oci-go-sdk/v54/common"
)
// AttachVnicDetails The representation of AttachVnicDetails
type AttachVnicDetails struct {
CreateVnicDetails *CreateVnicDetails `mandatory:"true" json:"createVnicDetails"`
// The OCID of the instance.
InstanceId *string `mandatory:"true" json:"instanceId"`
// A user-friendly name. Does not have to be unique, and it's changeable.
// Avoid entering confidential information.
DisplayName *string `mandatory:"false" json:"displayName"`
// Which physical network interface card (NIC) the VNIC will use. Defaults to 0.
// Certain bare metal instance shapes have two active physical NICs (0 and 1). If
// you add a secondary VNIC to one of these instances, you can specify which NIC
// the VNIC will use. For more information, see
// Virtual Network Interface Cards (VNICs) (https://docs.cloud.oracle.com/iaas/Content/Network/Tasks/managingVNICs.htm).
NicIndex *int `mandatory:"false" json:"nicIndex"`
}
func (m AttachVnicDetails) String() string {
return common.PointerString(m)
}

View file

@ -0,0 +1,84 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
package core
import (
"github.com/oracle/oci-go-sdk/v54/common"
"net/http"
)
// AttachVnicRequest wrapper for the AttachVnic operation
//
// See also
//
// Click https://docs.cloud.oracle.com/en-us/iaas/tools/go-sdk-examples/latest/core/AttachVnic.go.html to see an example of how to use AttachVnicRequest.
type AttachVnicRequest struct {
// Attach VNIC details.
AttachVnicDetails `contributesTo:"body"`
// A token that uniquely identifies a request so it can be retried in case of a timeout or
// server error without risk of executing that same action again. Retry tokens expire after 24
// hours, but can be invalidated before then due to conflicting operations (for example, if a resource
// has been deleted and purged from the system, then a retry of the original creation request
// may be rejected).
OpcRetryToken *string `mandatory:"false" contributesTo:"header" name:"opc-retry-token"`
// Unique Oracle-assigned identifier for the request.
// If you need to contact Oracle about a particular request, please provide the request ID.
OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"`
// Metadata about the request. This information will not be transmitted to the service, but
// represents information that the SDK will consume to drive retry behavior.
RequestMetadata common.RequestMetadata
}
func (request AttachVnicRequest) String() string {
return common.PointerString(request)
}
// HTTPRequest implements the OCIRequest interface
func (request AttachVnicRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {
return common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)
}
// BinaryRequestBody implements the OCIRequest interface
func (request AttachVnicRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {
return nil, false
}
// RetryPolicy implements the OCIRetryableRequest interface. This retrieves the specified retry policy.
func (request AttachVnicRequest) RetryPolicy() *common.RetryPolicy {
return request.RequestMetadata.RetryPolicy
}
// AttachVnicResponse wrapper for the AttachVnic operation
type AttachVnicResponse struct {
// The underlying http response
RawResponse *http.Response
// The VnicAttachment instance
VnicAttachment `presentIn:"body"`
// For optimistic concurrency control. See `if-match`.
Etag *string `presentIn:"header" name:"etag"`
// Unique Oracle-assigned identifier for the request. If you need to contact
// Oracle about a particular request, please provide the request ID.
OpcRequestId *string `presentIn:"header" name:"opc-request-id"`
}
func (response AttachVnicResponse) String() string {
return common.PointerString(response)
}
// HTTPResponse implements the OCIResponse interface
func (response AttachVnicResponse) HTTPResponse() *http.Response {
return response.RawResponse
}

View file

@ -0,0 +1,142 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
// Core Services API
//
// Use the Core Services API to manage resources such as virtual cloud networks (VCNs),
// compute instances, and block storage volumes. For more information, see the console
// documentation for the Networking (https://docs.cloud.oracle.com/iaas/Content/Network/Concepts/overview.htm),
// Compute (https://docs.cloud.oracle.com/iaas/Content/Compute/Concepts/computeoverview.htm), and
// Block Volume (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/overview.htm) services.
//
package core
import (
"encoding/json"
"github.com/oracle/oci-go-sdk/v54/common"
)
// AttachVolumeDetails The representation of AttachVolumeDetails
type AttachVolumeDetails interface {
// The OCID of the instance.
GetInstanceId() *string
// The OCID of the volume.
GetVolumeId() *string
// The device name. To retrieve a list of devices for a given instance, see ListInstanceDevices.
GetDevice() *string
// A user-friendly name. Does not have to be unique, and it's changeable.
// Avoid entering confidential information.
GetDisplayName() *string
// Whether the attachment was created in read-only mode.
GetIsReadOnly() *bool
// Whether the attachment should be created in shareable mode. If an attachment
// is created in shareable mode, then other instances can attach the same volume, provided
// that they also create their attachments in shareable mode. Only certain volume types can
// be attached in shareable mode. Defaults to false if not specified.
GetIsShareable() *bool
}
type attachvolumedetails struct {
JsonData []byte
InstanceId *string `mandatory:"true" json:"instanceId"`
VolumeId *string `mandatory:"true" json:"volumeId"`
Device *string `mandatory:"false" json:"device"`
DisplayName *string `mandatory:"false" json:"displayName"`
IsReadOnly *bool `mandatory:"false" json:"isReadOnly"`
IsShareable *bool `mandatory:"false" json:"isShareable"`
Type string `json:"type"`
}
// UnmarshalJSON unmarshals json
func (m *attachvolumedetails) UnmarshalJSON(data []byte) error {
m.JsonData = data
type Unmarshalerattachvolumedetails attachvolumedetails
s := struct {
Model Unmarshalerattachvolumedetails
}{}
err := json.Unmarshal(data, &s.Model)
if err != nil {
return err
}
m.InstanceId = s.Model.InstanceId
m.VolumeId = s.Model.VolumeId
m.Device = s.Model.Device
m.DisplayName = s.Model.DisplayName
m.IsReadOnly = s.Model.IsReadOnly
m.IsShareable = s.Model.IsShareable
m.Type = s.Model.Type
return err
}
// UnmarshalPolymorphicJSON unmarshals polymorphic json
func (m *attachvolumedetails) UnmarshalPolymorphicJSON(data []byte) (interface{}, error) {
if data == nil || string(data) == "null" {
return nil, nil
}
var err error
switch m.Type {
case "service_determined":
mm := AttachServiceDeterminedVolumeDetails{}
err = json.Unmarshal(data, &mm)
return mm, err
case "emulated":
mm := AttachEmulatedVolumeDetails{}
err = json.Unmarshal(data, &mm)
return mm, err
case "iscsi":
mm := AttachIScsiVolumeDetails{}
err = json.Unmarshal(data, &mm)
return mm, err
case "paravirtualized":
mm := AttachParavirtualizedVolumeDetails{}
err = json.Unmarshal(data, &mm)
return mm, err
default:
return *m, nil
}
}
//GetInstanceId returns InstanceId
func (m attachvolumedetails) GetInstanceId() *string {
return m.InstanceId
}
//GetVolumeId returns VolumeId
func (m attachvolumedetails) GetVolumeId() *string {
return m.VolumeId
}
//GetDevice returns Device
func (m attachvolumedetails) GetDevice() *string {
return m.Device
}
//GetDisplayName returns DisplayName
func (m attachvolumedetails) GetDisplayName() *string {
return m.DisplayName
}
//GetIsReadOnly returns IsReadOnly
func (m attachvolumedetails) GetIsReadOnly() *bool {
return m.IsReadOnly
}
//GetIsShareable returns IsShareable
func (m attachvolumedetails) GetIsShareable() *bool {
return m.IsShareable
}
func (m attachvolumedetails) String() string {
return common.PointerString(m)
}

View file

@ -0,0 +1,84 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
package core
import (
"github.com/oracle/oci-go-sdk/v54/common"
"net/http"
)
// AttachVolumeRequest wrapper for the AttachVolume operation
//
// See also
//
// Click https://docs.cloud.oracle.com/en-us/iaas/tools/go-sdk-examples/latest/core/AttachVolume.go.html to see an example of how to use AttachVolumeRequest.
type AttachVolumeRequest struct {
// Attach volume request
AttachVolumeDetails `contributesTo:"body"`
// A token that uniquely identifies a request so it can be retried in case of a timeout or
// server error without risk of executing that same action again. Retry tokens expire after 24
// hours, but can be invalidated before then due to conflicting operations (for example, if a resource
// has been deleted and purged from the system, then a retry of the original creation request
// may be rejected).
OpcRetryToken *string `mandatory:"false" contributesTo:"header" name:"opc-retry-token"`
// Unique Oracle-assigned identifier for the request.
// If you need to contact Oracle about a particular request, please provide the request ID.
OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"`
// Metadata about the request. This information will not be transmitted to the service, but
// represents information that the SDK will consume to drive retry behavior.
RequestMetadata common.RequestMetadata
}
func (request AttachVolumeRequest) String() string {
return common.PointerString(request)
}
// HTTPRequest implements the OCIRequest interface
func (request AttachVolumeRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {
return common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)
}
// BinaryRequestBody implements the OCIRequest interface
func (request AttachVolumeRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {
return nil, false
}
// RetryPolicy implements the OCIRetryableRequest interface. This retrieves the specified retry policy.
func (request AttachVolumeRequest) RetryPolicy() *common.RetryPolicy {
return request.RequestMetadata.RetryPolicy
}
// AttachVolumeResponse wrapper for the AttachVolume operation
type AttachVolumeResponse struct {
// The underlying http response
RawResponse *http.Response
// The VolumeAttachment instance
VolumeAttachment `presentIn:"body"`
// For optimistic concurrency control. See `if-match`.
Etag *string `presentIn:"header" name:"etag"`
// Unique Oracle-assigned identifier for the request. If you need to contact
// Oracle about a particular request, please provide the request ID.
OpcRequestId *string `presentIn:"header" name:"opc-request-id"`
}
func (response AttachVolumeResponse) String() string {
return common.PointerString(response)
}
// HTTPResponse implements the OCIResponse interface
func (response AttachVolumeResponse) HTTPResponse() *http.Response {
return response.RawResponse
}

View file

@ -0,0 +1,129 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
// Core Services API
//
// Use the Core Services API to manage resources such as virtual cloud networks (VCNs),
// compute instances, and block storage volumes. For more information, see the console
// documentation for the Networking (https://docs.cloud.oracle.com/iaas/Content/Network/Concepts/overview.htm),
// Compute (https://docs.cloud.oracle.com/iaas/Content/Compute/Concepts/computeoverview.htm), and
// Block Volume (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/overview.htm) services.
//
package core
import (
"github.com/oracle/oci-go-sdk/v54/common"
)
// BgpSessionInfo Information for establishing a BGP session for the IPSec tunnel.
type BgpSessionInfo struct {
// The IP address for the Oracle end of the inside tunnel interface.
// If the tunnel's `routing` attribute is set to `BGP`
// (see IPSecConnectionTunnel), this IP address
// is required and used for the tunnel's BGP session.
// If `routing` is instead set to `STATIC`, this IP address is optional. You can set this IP
// address so you can troubleshoot or monitor the tunnel.
// The value must be a /30 or /31.
// Example: `10.0.0.4/31`
OracleInterfaceIp *string `mandatory:"false" json:"oracleInterfaceIp"`
// The IP address for the CPE end of the inside tunnel interface.
// If the tunnel's `routing` attribute is set to `BGP`
// (see IPSecConnectionTunnel), this IP address
// is required and used for the tunnel's BGP session.
// If `routing` is instead set to `STATIC`, this IP address is optional. You can set this IP
// address so you can troubleshoot or monitor the tunnel.
// The value must be a /30 or /31.
// Example: `10.0.0.5/31`
CustomerInterfaceIp *string `mandatory:"false" json:"customerInterfaceIp"`
// The IPv6 address for the Oracle end of the inside tunnel interface. This IP address is optional.
// If the tunnel's `routing` attribute is set to `BGP`
// (see IPSecConnectionTunnel), this IP address
// is used for the tunnel's BGP session.
// If `routing` is instead set to `STATIC`, you can set this IP
// address to troubleshoot or monitor the tunnel.
// Only subnet masks from /64 up to /127 are allowed.
// Example: `2001:db8::1/64`
OracleInterfaceIpv6 *string `mandatory:"false" json:"oracleInterfaceIpv6"`
// The IPv6 address for the CPE end of the inside tunnel interface. This IP address is optional.
// If the tunnel's `routing` attribute is set to `BGP`
// (see IPSecConnectionTunnel), this IP address
// is used for the tunnel's BGP session.
// If `routing` is instead set to `STATIC`, you can set this IP
// address to troubleshoot or monitor the tunnel.
// Only subnet masks from /64 up to /127 are allowed.
// Example: `2001:db8::1/64`
CustomerInterfaceIpv6 *string `mandatory:"false" json:"customerInterfaceIpv6"`
// The Oracle BGP ASN.
OracleBgpAsn *string `mandatory:"false" json:"oracleBgpAsn"`
// If the tunnel's `routing` attribute is set to `BGP`
// (see IPSecConnectionTunnel), this ASN
// is required and used for the tunnel's BGP session. This is the ASN of the network on the
// CPE end of the BGP session. Can be a 2-byte or 4-byte ASN. Uses "asplain" format.
// If the tunnel uses static routing, the `customerBgpAsn` must be null.
// Example: `12345` (2-byte) or `1587232876` (4-byte)
CustomerBgpAsn *string `mandatory:"false" json:"customerBgpAsn"`
// The state of the BGP session.
BgpState BgpSessionInfoBgpStateEnum `mandatory:"false" json:"bgpState,omitempty"`
// The state of the BGP IPv6 session.
BgpIpv6State BgpSessionInfoBgpIpv6StateEnum `mandatory:"false" json:"bgpIpv6State,omitempty"`
}
func (m BgpSessionInfo) String() string {
return common.PointerString(m)
}
// BgpSessionInfoBgpStateEnum Enum with underlying type: string
type BgpSessionInfoBgpStateEnum string
// Set of constants representing the allowable values for BgpSessionInfoBgpStateEnum
const (
BgpSessionInfoBgpStateUp BgpSessionInfoBgpStateEnum = "UP"
BgpSessionInfoBgpStateDown BgpSessionInfoBgpStateEnum = "DOWN"
)
var mappingBgpSessionInfoBgpState = map[string]BgpSessionInfoBgpStateEnum{
"UP": BgpSessionInfoBgpStateUp,
"DOWN": BgpSessionInfoBgpStateDown,
}
// GetBgpSessionInfoBgpStateEnumValues Enumerates the set of values for BgpSessionInfoBgpStateEnum
func GetBgpSessionInfoBgpStateEnumValues() []BgpSessionInfoBgpStateEnum {
values := make([]BgpSessionInfoBgpStateEnum, 0)
for _, v := range mappingBgpSessionInfoBgpState {
values = append(values, v)
}
return values
}
// BgpSessionInfoBgpIpv6StateEnum Enum with underlying type: string
type BgpSessionInfoBgpIpv6StateEnum string
// Set of constants representing the allowable values for BgpSessionInfoBgpIpv6StateEnum
const (
BgpSessionInfoBgpIpv6StateUp BgpSessionInfoBgpIpv6StateEnum = "UP"
BgpSessionInfoBgpIpv6StateDown BgpSessionInfoBgpIpv6StateEnum = "DOWN"
)
var mappingBgpSessionInfoBgpIpv6State = map[string]BgpSessionInfoBgpIpv6StateEnum{
"UP": BgpSessionInfoBgpIpv6StateUp,
"DOWN": BgpSessionInfoBgpIpv6StateDown,
}
// GetBgpSessionInfoBgpIpv6StateEnumValues Enumerates the set of values for BgpSessionInfoBgpIpv6StateEnum
func GetBgpSessionInfoBgpIpv6StateEnumValues() []BgpSessionInfoBgpIpv6StateEnum {
values := make([]BgpSessionInfoBgpIpv6StateEnum, 0)
for _, v := range mappingBgpSessionInfoBgpIpv6State {
values = append(values, v)
}
return values
}

View file

@ -0,0 +1,109 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
// Core Services API
//
// Use the Core Services API to manage resources such as virtual cloud networks (VCNs),
// compute instances, and block storage volumes. For more information, see the console
// documentation for the Networking (https://docs.cloud.oracle.com/iaas/Content/Network/Concepts/overview.htm),
// Compute (https://docs.cloud.oracle.com/iaas/Content/Compute/Concepts/computeoverview.htm), and
// Block Volume (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/overview.htm) services.
//
package core
import (
"github.com/oracle/oci-go-sdk/v54/common"
)
// BlockVolumeReplica An asynchronous replica of a block volume that can then be used to create
// a new block volume or recover a block volume. For more information, see Overview
// of Cross-Region Volume Replication (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/volumereplication.htm)
// To use any of the API operations, you must be authorized in an IAM policy.
// If you're not authorized, talk to an administrator. If you're an administrator
// who needs to write policies to give users access, see Getting Started with
// Policies (https://docs.cloud.oracle.com/iaas/Content/Identity/Concepts/policygetstarted.htm).
// **Warning:** Oracle recommends that you avoid using any confidential information when you
// supply string values using the API.
type BlockVolumeReplica struct {
// The availability domain of the block volume replica.
// Example: `Uocm:PHX-AD-1`
AvailabilityDomain *string `mandatory:"true" json:"availabilityDomain"`
// The OCID of the compartment that contains the block volume replica.
CompartmentId *string `mandatory:"true" json:"compartmentId"`
// A user-friendly name. Does not have to be unique, and it's changeable.
// Avoid entering confidential information.
DisplayName *string `mandatory:"true" json:"displayName"`
// The block volume replica's Oracle ID (OCID).
Id *string `mandatory:"true" json:"id"`
// The current state of a block volume replica.
LifecycleState BlockVolumeReplicaLifecycleStateEnum `mandatory:"true" json:"lifecycleState"`
// The size of the source block volume, in GBs.
SizeInGBs *int64 `mandatory:"true" json:"sizeInGBs"`
// The date and time the block volume replica was created. Format defined
// by RFC3339 (https://tools.ietf.org/html/rfc3339).
TimeCreated *common.SDKTime `mandatory:"true" json:"timeCreated"`
// The date and time the block volume replica was last synced from the source block volume.
// Format defined by RFC3339 (https://tools.ietf.org/html/rfc3339).
TimeLastSynced *common.SDKTime `mandatory:"true" json:"timeLastSynced"`
// The OCID of the source block volume.
BlockVolumeId *string `mandatory:"true" json:"blockVolumeId"`
// Defined tags for this resource. Each key is predefined and scoped to a
// namespace. For more information, see Resource Tags (https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm).
// Example: `{"Operations": {"CostCenter": "42"}}`
DefinedTags map[string]map[string]interface{} `mandatory:"false" json:"definedTags"`
// Free-form tags for this resource. Each tag is a simple key-value pair with no
// predefined name, type, or namespace. For more information, see Resource Tags (https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm).
// Example: `{"Department": "Finance"}`
FreeformTags map[string]string `mandatory:"false" json:"freeformTags"`
// The total size of the data transferred from the source block volume to the block volume replica, in GBs.
TotalDataTransferredInGBs *int64 `mandatory:"false" json:"totalDataTransferredInGBs"`
}
func (m BlockVolumeReplica) String() string {
return common.PointerString(m)
}
// BlockVolumeReplicaLifecycleStateEnum Enum with underlying type: string
type BlockVolumeReplicaLifecycleStateEnum string
// Set of constants representing the allowable values for BlockVolumeReplicaLifecycleStateEnum
const (
BlockVolumeReplicaLifecycleStateProvisioning BlockVolumeReplicaLifecycleStateEnum = "PROVISIONING"
BlockVolumeReplicaLifecycleStateAvailable BlockVolumeReplicaLifecycleStateEnum = "AVAILABLE"
BlockVolumeReplicaLifecycleStateActivating BlockVolumeReplicaLifecycleStateEnum = "ACTIVATING"
BlockVolumeReplicaLifecycleStateTerminating BlockVolumeReplicaLifecycleStateEnum = "TERMINATING"
BlockVolumeReplicaLifecycleStateTerminated BlockVolumeReplicaLifecycleStateEnum = "TERMINATED"
BlockVolumeReplicaLifecycleStateFaulty BlockVolumeReplicaLifecycleStateEnum = "FAULTY"
)
var mappingBlockVolumeReplicaLifecycleState = map[string]BlockVolumeReplicaLifecycleStateEnum{
"PROVISIONING": BlockVolumeReplicaLifecycleStateProvisioning,
"AVAILABLE": BlockVolumeReplicaLifecycleStateAvailable,
"ACTIVATING": BlockVolumeReplicaLifecycleStateActivating,
"TERMINATING": BlockVolumeReplicaLifecycleStateTerminating,
"TERMINATED": BlockVolumeReplicaLifecycleStateTerminated,
"FAULTY": BlockVolumeReplicaLifecycleStateFaulty,
}
// GetBlockVolumeReplicaLifecycleStateEnumValues Enumerates the set of values for BlockVolumeReplicaLifecycleStateEnum
func GetBlockVolumeReplicaLifecycleStateEnumValues() []BlockVolumeReplicaLifecycleStateEnum {
values := make([]BlockVolumeReplicaLifecycleStateEnum, 0)
for _, v := range mappingBlockVolumeReplicaLifecycleState {
values = append(values, v)
}
return values
}

View file

@ -0,0 +1,34 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
// Core Services API
//
// Use the Core Services API to manage resources such as virtual cloud networks (VCNs),
// compute instances, and block storage volumes. For more information, see the console
// documentation for the Networking (https://docs.cloud.oracle.com/iaas/Content/Network/Concepts/overview.htm),
// Compute (https://docs.cloud.oracle.com/iaas/Content/Compute/Concepts/computeoverview.htm), and
// Block Volume (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/overview.htm) services.
//
package core
import (
"github.com/oracle/oci-go-sdk/v54/common"
)
// BlockVolumeReplicaDetails Contains the details for the block volume replica
type BlockVolumeReplicaDetails struct {
// The availability domain of the block volume replica.
// Example: `Uocm:PHX-AD-1`
AvailabilityDomain *string `mandatory:"true" json:"availabilityDomain"`
// A user-friendly name. Does not have to be unique, and it's changeable.
// Avoid entering confidential information.
DisplayName *string `mandatory:"false" json:"displayName"`
}
func (m BlockVolumeReplicaDetails) String() string {
return common.PointerString(m)
}

View file

@ -0,0 +1,37 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
// Core Services API
//
// Use the Core Services API to manage resources such as virtual cloud networks (VCNs),
// compute instances, and block storage volumes. For more information, see the console
// documentation for the Networking (https://docs.cloud.oracle.com/iaas/Content/Network/Concepts/overview.htm),
// Compute (https://docs.cloud.oracle.com/iaas/Content/Compute/Concepts/computeoverview.htm), and
// Block Volume (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/overview.htm) services.
//
package core
import (
"github.com/oracle/oci-go-sdk/v54/common"
)
// BlockVolumeReplicaInfo Information about the block volume replica in the destination availability domain.
type BlockVolumeReplicaInfo struct {
// A user-friendly name. Does not have to be unique, and it's changeable.
// Avoid entering confidential information.
DisplayName *string `mandatory:"true" json:"displayName"`
// The block volume replica's Oracle ID (OCID).
BlockVolumeReplicaId *string `mandatory:"true" json:"blockVolumeReplicaId"`
// The availability domain of the block volume replica.
// Example: `Uocm:PHX-AD-1`
AvailabilityDomain *string `mandatory:"true" json:"availabilityDomain"`
}
func (m BlockVolumeReplicaInfo) String() string {
return common.PointerString(m)
}

View file

@ -0,0 +1,51 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
// Core Services API
//
// Use the Core Services API to manage resources such as virtual cloud networks (VCNs),
// compute instances, and block storage volumes. For more information, see the console
// documentation for the Networking (https://docs.cloud.oracle.com/iaas/Content/Network/Concepts/overview.htm),
// Compute (https://docs.cloud.oracle.com/iaas/Content/Compute/Concepts/computeoverview.htm), and
// Block Volume (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/overview.htm) services.
//
package core
import (
"encoding/json"
"github.com/oracle/oci-go-sdk/v54/common"
)
// BooleanImageCapabilitySchemaDescriptor Boolean type ImageCapabilitySchemaDescriptor
type BooleanImageCapabilitySchemaDescriptor struct {
// the default value
DefaultValue *bool `mandatory:"false" json:"defaultValue"`
Source ImageCapabilitySchemaDescriptorSourceEnum `mandatory:"true" json:"source"`
}
//GetSource returns Source
func (m BooleanImageCapabilitySchemaDescriptor) GetSource() ImageCapabilitySchemaDescriptorSourceEnum {
return m.Source
}
func (m BooleanImageCapabilitySchemaDescriptor) String() string {
return common.PointerString(m)
}
// MarshalJSON marshals to json representation
func (m BooleanImageCapabilitySchemaDescriptor) MarshalJSON() (buff []byte, e error) {
type MarshalTypeBooleanImageCapabilitySchemaDescriptor BooleanImageCapabilitySchemaDescriptor
s := struct {
DiscriminatorParam string `json:"descriptorType"`
MarshalTypeBooleanImageCapabilitySchemaDescriptor
}{
"boolean",
(MarshalTypeBooleanImageCapabilitySchemaDescriptor)(m),
}
return json.Marshal(&s)
}

View file

@ -0,0 +1,222 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
// Core Services API
//
// Use the Core Services API to manage resources such as virtual cloud networks (VCNs),
// compute instances, and block storage volumes. For more information, see the console
// documentation for the Networking (https://docs.cloud.oracle.com/iaas/Content/Network/Concepts/overview.htm),
// Compute (https://docs.cloud.oracle.com/iaas/Content/Compute/Concepts/computeoverview.htm), and
// Block Volume (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/overview.htm) services.
//
package core
import (
"encoding/json"
"github.com/oracle/oci-go-sdk/v54/common"
)
// BootVolume A detachable boot volume device that contains the image used to boot a Compute instance. For more information, see
// Overview of Boot Volumes (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/bootvolumes.htm).
// To use any of the API operations, you must be authorized in an IAM policy. If you're not authorized,
// talk to an administrator. If you're an administrator who needs to write policies to give users access, see
// Getting Started with Policies (https://docs.cloud.oracle.com/iaas/Content/Identity/Concepts/policygetstarted.htm).
// **Warning:** Oracle recommends that you avoid using any confidential information when you
// supply string values using the API.
type BootVolume struct {
// The availability domain of the boot volume.
// Example: `Uocm:PHX-AD-1`
AvailabilityDomain *string `mandatory:"true" json:"availabilityDomain"`
// The OCID of the compartment that contains the boot volume.
CompartmentId *string `mandatory:"true" json:"compartmentId"`
// The boot volume's Oracle ID (OCID).
Id *string `mandatory:"true" json:"id"`
// The current state of a boot volume.
LifecycleState BootVolumeLifecycleStateEnum `mandatory:"true" json:"lifecycleState"`
// The size of the volume in MBs. The value must be a multiple of 1024.
// This field is deprecated. Please use sizeInGBs.
SizeInMBs *int64 `mandatory:"true" json:"sizeInMBs"`
// The date and time the boot volume was created. Format defined
// by RFC3339 (https://tools.ietf.org/html/rfc3339).
TimeCreated *common.SDKTime `mandatory:"true" json:"timeCreated"`
// Defined tags for this resource. Each key is predefined and scoped to a
// namespace. For more information, see Resource Tags (https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm).
// Example: `{"Operations": {"CostCenter": "42"}}`
DefinedTags map[string]map[string]interface{} `mandatory:"false" json:"definedTags"`
// System tags for this resource. Each key is predefined and scoped to a namespace.
// Example: `{"foo-namespace": {"bar-key": "value"}}`
SystemTags map[string]map[string]interface{} `mandatory:"false" json:"systemTags"`
// A user-friendly name. Does not have to be unique, and it's changeable.
// Avoid entering confidential information.
DisplayName *string `mandatory:"false" json:"displayName"`
// Free-form tags for this resource. Each tag is a simple key-value pair with no
// predefined name, type, or namespace. For more information, see Resource Tags (https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm).
// Example: `{"Department": "Finance"}`
FreeformTags map[string]string `mandatory:"false" json:"freeformTags"`
// The image OCID used to create the boot volume.
ImageId *string `mandatory:"false" json:"imageId"`
// Specifies whether the boot volume's data has finished copying
// from the source boot volume or boot volume backup.
IsHydrated *bool `mandatory:"false" json:"isHydrated"`
// The number of volume performance units (VPUs) that will be applied to this boot volume per GB,
// representing the Block Volume service's elastic performance options.
// See Block Volume Elastic Performance (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/blockvolumeelasticperformance.htm) for more information.
// Allowed values:
// * `10`: Represents Balanced option.
// * `20`: Represents Higher Performance option.
VpusPerGB *int64 `mandatory:"false" json:"vpusPerGB"`
// The size of the boot volume in GBs.
SizeInGBs *int64 `mandatory:"false" json:"sizeInGBs"`
SourceDetails BootVolumeSourceDetails `mandatory:"false" json:"sourceDetails"`
// The OCID of the source volume group.
VolumeGroupId *string `mandatory:"false" json:"volumeGroupId"`
// The OCID of the Key Management master encryption key assigned to the boot volume.
KmsKeyId *string `mandatory:"false" json:"kmsKeyId"`
// Specifies whether the auto-tune performance is enabled for this boot volume.
IsAutoTuneEnabled *bool `mandatory:"false" json:"isAutoTuneEnabled"`
// The number of Volume Performance Units per GB that this boot volume is effectively tuned to when it's idle.
AutoTunedVpusPerGB *int64 `mandatory:"false" json:"autoTunedVpusPerGB"`
// The list of boot volume replicas of this boot volume
BootVolumeReplicas []BootVolumeReplicaInfo `mandatory:"false" json:"bootVolumeReplicas"`
}
func (m BootVolume) String() string {
return common.PointerString(m)
}
// UnmarshalJSON unmarshals from json
func (m *BootVolume) UnmarshalJSON(data []byte) (e error) {
model := struct {
DefinedTags map[string]map[string]interface{} `json:"definedTags"`
SystemTags map[string]map[string]interface{} `json:"systemTags"`
DisplayName *string `json:"displayName"`
FreeformTags map[string]string `json:"freeformTags"`
ImageId *string `json:"imageId"`
IsHydrated *bool `json:"isHydrated"`
VpusPerGB *int64 `json:"vpusPerGB"`
SizeInGBs *int64 `json:"sizeInGBs"`
SourceDetails bootvolumesourcedetails `json:"sourceDetails"`
VolumeGroupId *string `json:"volumeGroupId"`
KmsKeyId *string `json:"kmsKeyId"`
IsAutoTuneEnabled *bool `json:"isAutoTuneEnabled"`
AutoTunedVpusPerGB *int64 `json:"autoTunedVpusPerGB"`
BootVolumeReplicas []BootVolumeReplicaInfo `json:"bootVolumeReplicas"`
AvailabilityDomain *string `json:"availabilityDomain"`
CompartmentId *string `json:"compartmentId"`
Id *string `json:"id"`
LifecycleState BootVolumeLifecycleStateEnum `json:"lifecycleState"`
SizeInMBs *int64 `json:"sizeInMBs"`
TimeCreated *common.SDKTime `json:"timeCreated"`
}{}
e = json.Unmarshal(data, &model)
if e != nil {
return
}
var nn interface{}
m.DefinedTags = model.DefinedTags
m.SystemTags = model.SystemTags
m.DisplayName = model.DisplayName
m.FreeformTags = model.FreeformTags
m.ImageId = model.ImageId
m.IsHydrated = model.IsHydrated
m.VpusPerGB = model.VpusPerGB
m.SizeInGBs = model.SizeInGBs
nn, e = model.SourceDetails.UnmarshalPolymorphicJSON(model.SourceDetails.JsonData)
if e != nil {
return
}
if nn != nil {
m.SourceDetails = nn.(BootVolumeSourceDetails)
} else {
m.SourceDetails = nil
}
m.VolumeGroupId = model.VolumeGroupId
m.KmsKeyId = model.KmsKeyId
m.IsAutoTuneEnabled = model.IsAutoTuneEnabled
m.AutoTunedVpusPerGB = model.AutoTunedVpusPerGB
m.BootVolumeReplicas = make([]BootVolumeReplicaInfo, len(model.BootVolumeReplicas))
for i, n := range model.BootVolumeReplicas {
m.BootVolumeReplicas[i] = n
}
m.AvailabilityDomain = model.AvailabilityDomain
m.CompartmentId = model.CompartmentId
m.Id = model.Id
m.LifecycleState = model.LifecycleState
m.SizeInMBs = model.SizeInMBs
m.TimeCreated = model.TimeCreated
return
}
// BootVolumeLifecycleStateEnum Enum with underlying type: string
type BootVolumeLifecycleStateEnum string
// Set of constants representing the allowable values for BootVolumeLifecycleStateEnum
const (
BootVolumeLifecycleStateProvisioning BootVolumeLifecycleStateEnum = "PROVISIONING"
BootVolumeLifecycleStateRestoring BootVolumeLifecycleStateEnum = "RESTORING"
BootVolumeLifecycleStateAvailable BootVolumeLifecycleStateEnum = "AVAILABLE"
BootVolumeLifecycleStateTerminating BootVolumeLifecycleStateEnum = "TERMINATING"
BootVolumeLifecycleStateTerminated BootVolumeLifecycleStateEnum = "TERMINATED"
BootVolumeLifecycleStateFaulty BootVolumeLifecycleStateEnum = "FAULTY"
)
var mappingBootVolumeLifecycleState = map[string]BootVolumeLifecycleStateEnum{
"PROVISIONING": BootVolumeLifecycleStateProvisioning,
"RESTORING": BootVolumeLifecycleStateRestoring,
"AVAILABLE": BootVolumeLifecycleStateAvailable,
"TERMINATING": BootVolumeLifecycleStateTerminating,
"TERMINATED": BootVolumeLifecycleStateTerminated,
"FAULTY": BootVolumeLifecycleStateFaulty,
}
// GetBootVolumeLifecycleStateEnumValues Enumerates the set of values for BootVolumeLifecycleStateEnum
func GetBootVolumeLifecycleStateEnumValues() []BootVolumeLifecycleStateEnum {
values := make([]BootVolumeLifecycleStateEnum, 0)
for _, v := range mappingBootVolumeLifecycleState {
values = append(values, v)
}
return values
}

View file

@ -0,0 +1,89 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
// Core Services API
//
// Use the Core Services API to manage resources such as virtual cloud networks (VCNs),
// compute instances, and block storage volumes. For more information, see the console
// documentation for the Networking (https://docs.cloud.oracle.com/iaas/Content/Network/Concepts/overview.htm),
// Compute (https://docs.cloud.oracle.com/iaas/Content/Compute/Concepts/computeoverview.htm), and
// Block Volume (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/overview.htm) services.
//
package core
import (
"github.com/oracle/oci-go-sdk/v54/common"
)
// BootVolumeAttachment Represents an attachment between a boot volume and an instance.
// **Warning:** Oracle recommends that you avoid using any confidential information when you
// supply string values using the API.
type BootVolumeAttachment struct {
// The availability domain of an instance.
// Example: `Uocm:PHX-AD-1`
AvailabilityDomain *string `mandatory:"true" json:"availabilityDomain"`
// The OCID of the boot volume.
BootVolumeId *string `mandatory:"true" json:"bootVolumeId"`
// The OCID of the compartment.
CompartmentId *string `mandatory:"true" json:"compartmentId"`
// The OCID of the boot volume attachment.
Id *string `mandatory:"true" json:"id"`
// The OCID of the instance the boot volume is attached to.
InstanceId *string `mandatory:"true" json:"instanceId"`
// The current state of the boot volume attachment.
LifecycleState BootVolumeAttachmentLifecycleStateEnum `mandatory:"true" json:"lifecycleState"`
// The date and time the boot volume was created, in the format defined by RFC3339 (https://tools.ietf.org/html/rfc3339).
// Example: `2016-08-25T21:10:29.600Z`
TimeCreated *common.SDKTime `mandatory:"true" json:"timeCreated"`
// A user-friendly name. Does not have to be unique, and it's changeable.
// Avoid entering confidential information.
DisplayName *string `mandatory:"false" json:"displayName"`
// Whether in-transit encryption for the boot volume's paravirtualized attachment is enabled or not.
IsPvEncryptionInTransitEnabled *bool `mandatory:"false" json:"isPvEncryptionInTransitEnabled"`
// Refer the top-level definition of encryptionInTransitType.
// The default value is NONE.
EncryptionInTransitType EncryptionInTransitTypeEnum `mandatory:"false" json:"encryptionInTransitType,omitempty"`
}
func (m BootVolumeAttachment) String() string {
return common.PointerString(m)
}
// BootVolumeAttachmentLifecycleStateEnum Enum with underlying type: string
type BootVolumeAttachmentLifecycleStateEnum string
// Set of constants representing the allowable values for BootVolumeAttachmentLifecycleStateEnum
const (
BootVolumeAttachmentLifecycleStateAttaching BootVolumeAttachmentLifecycleStateEnum = "ATTACHING"
BootVolumeAttachmentLifecycleStateAttached BootVolumeAttachmentLifecycleStateEnum = "ATTACHED"
BootVolumeAttachmentLifecycleStateDetaching BootVolumeAttachmentLifecycleStateEnum = "DETACHING"
BootVolumeAttachmentLifecycleStateDetached BootVolumeAttachmentLifecycleStateEnum = "DETACHED"
)
var mappingBootVolumeAttachmentLifecycleState = map[string]BootVolumeAttachmentLifecycleStateEnum{
"ATTACHING": BootVolumeAttachmentLifecycleStateAttaching,
"ATTACHED": BootVolumeAttachmentLifecycleStateAttached,
"DETACHING": BootVolumeAttachmentLifecycleStateDetaching,
"DETACHED": BootVolumeAttachmentLifecycleStateDetached,
}
// GetBootVolumeAttachmentLifecycleStateEnumValues Enumerates the set of values for BootVolumeAttachmentLifecycleStateEnum
func GetBootVolumeAttachmentLifecycleStateEnumValues() []BootVolumeAttachmentLifecycleStateEnum {
values := make([]BootVolumeAttachmentLifecycleStateEnum, 0)
for _, v := range mappingBootVolumeAttachmentLifecycleState {
values = append(values, v)
}
return values
}

View file

@ -0,0 +1,180 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
// Core Services API
//
// Use the Core Services API to manage resources such as virtual cloud networks (VCNs),
// compute instances, and block storage volumes. For more information, see the console
// documentation for the Networking (https://docs.cloud.oracle.com/iaas/Content/Network/Concepts/overview.htm),
// Compute (https://docs.cloud.oracle.com/iaas/Content/Compute/Concepts/computeoverview.htm), and
// Block Volume (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/overview.htm) services.
//
package core
import (
"github.com/oracle/oci-go-sdk/v54/common"
)
// BootVolumeBackup A point-in-time copy of a boot volume that can then be used to create
// a new boot volume or recover a boot volume. For more information, see Overview
// of Boot Volume Backups (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/bootvolumebackups.htm)
// To use any of the API operations, you must be authorized in an IAM policy.
// If you're not authorized, talk to an administrator. If you're an administrator
// who needs to write policies to give users access, see Getting Started with
// Policies (https://docs.cloud.oracle.com/iaas/Content/Identity/Concepts/policygetstarted.htm).
// **Warning:** Oracle recommends that you avoid using any confidential information when you
// supply string values using the API.
type BootVolumeBackup struct {
// The OCID of the compartment that contains the boot volume backup.
CompartmentId *string `mandatory:"true" json:"compartmentId"`
// A user-friendly name. Does not have to be unique, and it's changeable.
// Avoid entering confidential information.
DisplayName *string `mandatory:"true" json:"displayName"`
// The OCID of the boot volume backup.
Id *string `mandatory:"true" json:"id"`
// The current state of a boot volume backup.
LifecycleState BootVolumeBackupLifecycleStateEnum `mandatory:"true" json:"lifecycleState"`
// The date and time the boot volume backup was created. This is the time the actual point-in-time image
// of the volume data was taken. Format defined by RFC3339 (https://tools.ietf.org/html/rfc3339).
TimeCreated *common.SDKTime `mandatory:"true" json:"timeCreated"`
// The OCID of the boot volume.
BootVolumeId *string `mandatory:"false" json:"bootVolumeId"`
// Defined tags for this resource. Each key is predefined and scoped to a
// namespace. For more information, see Resource Tags (https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm).
// Example: `{"Operations": {"CostCenter": "42"}}`
DefinedTags map[string]map[string]interface{} `mandatory:"false" json:"definedTags"`
// System tags for this resource. Each key is predefined and scoped to a namespace.
// Example: `{"foo-namespace": {"bar-key": "value"}}`
SystemTags map[string]map[string]interface{} `mandatory:"false" json:"systemTags"`
// The date and time the volume backup will expire and be automatically deleted.
// Format defined by RFC3339 (https://tools.ietf.org/html/rfc3339). This parameter will always be present for backups that
// were created automatically by a scheduled-backup policy. For manually created backups,
// it will be absent, signifying that there is no expiration time and the backup will
// last forever until manually deleted.
ExpirationTime *common.SDKTime `mandatory:"false" json:"expirationTime"`
// Free-form tags for this resource. Each tag is a simple key-value pair with no
// predefined name, type, or namespace. For more information, see Resource Tags (https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm).
// Example: `{"Department": "Finance"}`
FreeformTags map[string]string `mandatory:"false" json:"freeformTags"`
// The image OCID used to create the boot volume the backup is taken from.
ImageId *string `mandatory:"false" json:"imageId"`
// The OCID of the Key Management master encryption assigned to the boot volume backup.
// For more information about the Key Management service and encryption keys, see
// Overview of Key Management (https://docs.cloud.oracle.com/iaas/Content/KeyManagement/Concepts/keyoverview.htm) and
// Using Keys (https://docs.cloud.oracle.com/iaas/Content/KeyManagement/Tasks/usingkeys.htm).
KmsKeyId *string `mandatory:"false" json:"kmsKeyId"`
// The size of the boot volume, in GBs.
SizeInGBs *int64 `mandatory:"false" json:"sizeInGBs"`
// The OCID of the source boot volume backup.
SourceBootVolumeBackupId *string `mandatory:"false" json:"sourceBootVolumeBackupId"`
// Specifies whether the backup was created manually, or via scheduled backup policy.
SourceType BootVolumeBackupSourceTypeEnum `mandatory:"false" json:"sourceType,omitempty"`
// The date and time the request to create the boot volume backup was received. Format defined by RFC3339 (https://tools.ietf.org/html/rfc3339).
TimeRequestReceived *common.SDKTime `mandatory:"false" json:"timeRequestReceived"`
// The type of a volume backup.
Type BootVolumeBackupTypeEnum `mandatory:"false" json:"type,omitempty"`
// The size used by the backup, in GBs. It is typically smaller than sizeInGBs, depending on the space
// consumed on the boot volume and whether the backup is full or incremental.
UniqueSizeInGBs *int64 `mandatory:"false" json:"uniqueSizeInGBs"`
}
func (m BootVolumeBackup) String() string {
return common.PointerString(m)
}
// BootVolumeBackupLifecycleStateEnum Enum with underlying type: string
type BootVolumeBackupLifecycleStateEnum string
// Set of constants representing the allowable values for BootVolumeBackupLifecycleStateEnum
const (
BootVolumeBackupLifecycleStateCreating BootVolumeBackupLifecycleStateEnum = "CREATING"
BootVolumeBackupLifecycleStateAvailable BootVolumeBackupLifecycleStateEnum = "AVAILABLE"
BootVolumeBackupLifecycleStateTerminating BootVolumeBackupLifecycleStateEnum = "TERMINATING"
BootVolumeBackupLifecycleStateTerminated BootVolumeBackupLifecycleStateEnum = "TERMINATED"
BootVolumeBackupLifecycleStateFaulty BootVolumeBackupLifecycleStateEnum = "FAULTY"
BootVolumeBackupLifecycleStateRequestReceived BootVolumeBackupLifecycleStateEnum = "REQUEST_RECEIVED"
)
var mappingBootVolumeBackupLifecycleState = map[string]BootVolumeBackupLifecycleStateEnum{
"CREATING": BootVolumeBackupLifecycleStateCreating,
"AVAILABLE": BootVolumeBackupLifecycleStateAvailable,
"TERMINATING": BootVolumeBackupLifecycleStateTerminating,
"TERMINATED": BootVolumeBackupLifecycleStateTerminated,
"FAULTY": BootVolumeBackupLifecycleStateFaulty,
"REQUEST_RECEIVED": BootVolumeBackupLifecycleStateRequestReceived,
}
// GetBootVolumeBackupLifecycleStateEnumValues Enumerates the set of values for BootVolumeBackupLifecycleStateEnum
func GetBootVolumeBackupLifecycleStateEnumValues() []BootVolumeBackupLifecycleStateEnum {
values := make([]BootVolumeBackupLifecycleStateEnum, 0)
for _, v := range mappingBootVolumeBackupLifecycleState {
values = append(values, v)
}
return values
}
// BootVolumeBackupSourceTypeEnum Enum with underlying type: string
type BootVolumeBackupSourceTypeEnum string
// Set of constants representing the allowable values for BootVolumeBackupSourceTypeEnum
const (
BootVolumeBackupSourceTypeManual BootVolumeBackupSourceTypeEnum = "MANUAL"
BootVolumeBackupSourceTypeScheduled BootVolumeBackupSourceTypeEnum = "SCHEDULED"
)
var mappingBootVolumeBackupSourceType = map[string]BootVolumeBackupSourceTypeEnum{
"MANUAL": BootVolumeBackupSourceTypeManual,
"SCHEDULED": BootVolumeBackupSourceTypeScheduled,
}
// GetBootVolumeBackupSourceTypeEnumValues Enumerates the set of values for BootVolumeBackupSourceTypeEnum
func GetBootVolumeBackupSourceTypeEnumValues() []BootVolumeBackupSourceTypeEnum {
values := make([]BootVolumeBackupSourceTypeEnum, 0)
for _, v := range mappingBootVolumeBackupSourceType {
values = append(values, v)
}
return values
}
// BootVolumeBackupTypeEnum Enum with underlying type: string
type BootVolumeBackupTypeEnum string
// Set of constants representing the allowable values for BootVolumeBackupTypeEnum
const (
BootVolumeBackupTypeFull BootVolumeBackupTypeEnum = "FULL"
BootVolumeBackupTypeIncremental BootVolumeBackupTypeEnum = "INCREMENTAL"
)
var mappingBootVolumeBackupType = map[string]BootVolumeBackupTypeEnum{
"FULL": BootVolumeBackupTypeFull,
"INCREMENTAL": BootVolumeBackupTypeIncremental,
}
// GetBootVolumeBackupTypeEnumValues Enumerates the set of values for BootVolumeBackupTypeEnum
func GetBootVolumeBackupTypeEnumValues() []BootVolumeBackupTypeEnum {
values := make([]BootVolumeBackupTypeEnum, 0)
for _, v := range mappingBootVolumeBackupType {
values = append(values, v)
}
return values
}

View file

@ -0,0 +1,29 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
// Core Services API
//
// Use the Core Services API to manage resources such as virtual cloud networks (VCNs),
// compute instances, and block storage volumes. For more information, see the console
// documentation for the Networking (https://docs.cloud.oracle.com/iaas/Content/Network/Concepts/overview.htm),
// Compute (https://docs.cloud.oracle.com/iaas/Content/Compute/Concepts/computeoverview.htm), and
// Block Volume (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/overview.htm) services.
//
package core
import (
"github.com/oracle/oci-go-sdk/v54/common"
)
// BootVolumeKmsKey The Key Management master encryption key associated with this volume.
type BootVolumeKmsKey struct {
// The OCID of the Key Management key assigned to this volume. If the volume is not using Key Management, then the `kmsKeyId` will be a null string.
KmsKeyId *string `mandatory:"false" json:"kmsKeyId"`
}
func (m BootVolumeKmsKey) String() string {
return common.PointerString(m)
}

View file

@ -0,0 +1,112 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
// Core Services API
//
// Use the Core Services API to manage resources such as virtual cloud networks (VCNs),
// compute instances, and block storage volumes. For more information, see the console
// documentation for the Networking (https://docs.cloud.oracle.com/iaas/Content/Network/Concepts/overview.htm),
// Compute (https://docs.cloud.oracle.com/iaas/Content/Compute/Concepts/computeoverview.htm), and
// Block Volume (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/overview.htm) services.
//
package core
import (
"github.com/oracle/oci-go-sdk/v54/common"
)
// BootVolumeReplica An asynchronous replica of a boot volume that can then be used to create
// a new boot volume or recover a boot volume. For more information, see Overview
// of Cross-Region Volume Replication (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/volumereplication.htm)
// To use any of the API operations, you must be authorized in an IAM policy.
// If you're not authorized, talk to an administrator. If you're an administrator
// who needs to write policies to give users access, see Getting Started with
// Policies (https://docs.cloud.oracle.com/iaas/Content/Identity/Concepts/policygetstarted.htm).
// **Warning:** Oracle recommends that you avoid using any confidential information when you
// supply string values using the API.
type BootVolumeReplica struct {
// The availability domain of the boot volume replica.
// Example: `Uocm:PHX-AD-1`
AvailabilityDomain *string `mandatory:"true" json:"availabilityDomain"`
// The OCID of the compartment that contains the boot volume replica.
CompartmentId *string `mandatory:"true" json:"compartmentId"`
// A user-friendly name. Does not have to be unique, and it's changeable.
// Avoid entering confidential information.
DisplayName *string `mandatory:"true" json:"displayName"`
// The boot volume replica's Oracle ID (OCID).
Id *string `mandatory:"true" json:"id"`
// The current state of a boot volume replica.
LifecycleState BootVolumeReplicaLifecycleStateEnum `mandatory:"true" json:"lifecycleState"`
// The size of the source boot volume, in GBs.
SizeInGBs *int64 `mandatory:"true" json:"sizeInGBs"`
// The date and time the boot volume replica was created. Format defined
// by RFC3339 (https://tools.ietf.org/html/rfc3339).
TimeCreated *common.SDKTime `mandatory:"true" json:"timeCreated"`
// The date and time the boot volume replica was last synced from the source boot volume.
// Format defined by RFC3339 (https://tools.ietf.org/html/rfc3339).
TimeLastSynced *common.SDKTime `mandatory:"true" json:"timeLastSynced"`
// The OCID of the source boot volume.
BootVolumeId *string `mandatory:"true" json:"bootVolumeId"`
// Defined tags for this resource. Each key is predefined and scoped to a
// namespace. For more information, see Resource Tags (https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm).
// Example: `{"Operations": {"CostCenter": "42"}}`
DefinedTags map[string]map[string]interface{} `mandatory:"false" json:"definedTags"`
// Free-form tags for this resource. Each tag is a simple key-value pair with no
// predefined name, type, or namespace. For more information, see Resource Tags (https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm).
// Example: `{"Department": "Finance"}`
FreeformTags map[string]string `mandatory:"false" json:"freeformTags"`
// The image OCID used to create the boot volume the replica is replicated from.
ImageId *string `mandatory:"false" json:"imageId"`
// The total size of the data transferred from the source boot volume to the boot volume replica, in GBs.
TotalDataTransferredInGBs *int64 `mandatory:"false" json:"totalDataTransferredInGBs"`
}
func (m BootVolumeReplica) String() string {
return common.PointerString(m)
}
// BootVolumeReplicaLifecycleStateEnum Enum with underlying type: string
type BootVolumeReplicaLifecycleStateEnum string
// Set of constants representing the allowable values for BootVolumeReplicaLifecycleStateEnum
const (
BootVolumeReplicaLifecycleStateProvisioning BootVolumeReplicaLifecycleStateEnum = "PROVISIONING"
BootVolumeReplicaLifecycleStateAvailable BootVolumeReplicaLifecycleStateEnum = "AVAILABLE"
BootVolumeReplicaLifecycleStateActivating BootVolumeReplicaLifecycleStateEnum = "ACTIVATING"
BootVolumeReplicaLifecycleStateTerminating BootVolumeReplicaLifecycleStateEnum = "TERMINATING"
BootVolumeReplicaLifecycleStateTerminated BootVolumeReplicaLifecycleStateEnum = "TERMINATED"
BootVolumeReplicaLifecycleStateFaulty BootVolumeReplicaLifecycleStateEnum = "FAULTY"
)
var mappingBootVolumeReplicaLifecycleState = map[string]BootVolumeReplicaLifecycleStateEnum{
"PROVISIONING": BootVolumeReplicaLifecycleStateProvisioning,
"AVAILABLE": BootVolumeReplicaLifecycleStateAvailable,
"ACTIVATING": BootVolumeReplicaLifecycleStateActivating,
"TERMINATING": BootVolumeReplicaLifecycleStateTerminating,
"TERMINATED": BootVolumeReplicaLifecycleStateTerminated,
"FAULTY": BootVolumeReplicaLifecycleStateFaulty,
}
// GetBootVolumeReplicaLifecycleStateEnumValues Enumerates the set of values for BootVolumeReplicaLifecycleStateEnum
func GetBootVolumeReplicaLifecycleStateEnumValues() []BootVolumeReplicaLifecycleStateEnum {
values := make([]BootVolumeReplicaLifecycleStateEnum, 0)
for _, v := range mappingBootVolumeReplicaLifecycleState {
values = append(values, v)
}
return values
}

View file

@ -0,0 +1,34 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
// Core Services API
//
// Use the Core Services API to manage resources such as virtual cloud networks (VCNs),
// compute instances, and block storage volumes. For more information, see the console
// documentation for the Networking (https://docs.cloud.oracle.com/iaas/Content/Network/Concepts/overview.htm),
// Compute (https://docs.cloud.oracle.com/iaas/Content/Compute/Concepts/computeoverview.htm), and
// Block Volume (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/overview.htm) services.
//
package core
import (
"github.com/oracle/oci-go-sdk/v54/common"
)
// BootVolumeReplicaDetails Contains the details for the boot volume replica
type BootVolumeReplicaDetails struct {
// The availability domain of the boot volume replica.
// Example: `Uocm:PHX-AD-1`
AvailabilityDomain *string `mandatory:"true" json:"availabilityDomain"`
// A user-friendly name. Does not have to be unique, and it's changeable.
// Avoid entering confidential information.
DisplayName *string `mandatory:"false" json:"displayName"`
}
func (m BootVolumeReplicaDetails) String() string {
return common.PointerString(m)
}

View file

@ -0,0 +1,37 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
// Core Services API
//
// Use the Core Services API to manage resources such as virtual cloud networks (VCNs),
// compute instances, and block storage volumes. For more information, see the console
// documentation for the Networking (https://docs.cloud.oracle.com/iaas/Content/Network/Concepts/overview.htm),
// Compute (https://docs.cloud.oracle.com/iaas/Content/Compute/Concepts/computeoverview.htm), and
// Block Volume (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/overview.htm) services.
//
package core
import (
"github.com/oracle/oci-go-sdk/v54/common"
)
// BootVolumeReplicaInfo Information about the boot volume replica in the destination availability domain.
type BootVolumeReplicaInfo struct {
// A user-friendly name. Does not have to be unique, and it's changeable.
// Avoid entering confidential information.
DisplayName *string `mandatory:"true" json:"displayName"`
// The boot volume replica's Oracle ID (OCID).
BootVolumeReplicaId *string `mandatory:"true" json:"bootVolumeReplicaId"`
// The availability domain of the boot volume replica.
// Example: `Uocm:PHX-AD-1`
AvailabilityDomain *string `mandatory:"true" json:"availabilityDomain"`
}
func (m BootVolumeReplicaInfo) String() string {
return common.PointerString(m)
}

View file

@ -0,0 +1,74 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
// Core Services API
//
// Use the Core Services API to manage resources such as virtual cloud networks (VCNs),
// compute instances, and block storage volumes. For more information, see the console
// documentation for the Networking (https://docs.cloud.oracle.com/iaas/Content/Network/Concepts/overview.htm),
// Compute (https://docs.cloud.oracle.com/iaas/Content/Compute/Concepts/computeoverview.htm), and
// Block Volume (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/overview.htm) services.
//
package core
import (
"encoding/json"
"github.com/oracle/oci-go-sdk/v54/common"
)
// BootVolumeSourceDetails The representation of BootVolumeSourceDetails
type BootVolumeSourceDetails interface {
}
type bootvolumesourcedetails struct {
JsonData []byte
Type string `json:"type"`
}
// UnmarshalJSON unmarshals json
func (m *bootvolumesourcedetails) UnmarshalJSON(data []byte) error {
m.JsonData = data
type Unmarshalerbootvolumesourcedetails bootvolumesourcedetails
s := struct {
Model Unmarshalerbootvolumesourcedetails
}{}
err := json.Unmarshal(data, &s.Model)
if err != nil {
return err
}
m.Type = s.Model.Type
return err
}
// UnmarshalPolymorphicJSON unmarshals polymorphic json
func (m *bootvolumesourcedetails) UnmarshalPolymorphicJSON(data []byte) (interface{}, error) {
if data == nil || string(data) == "null" {
return nil, nil
}
var err error
switch m.Type {
case "bootVolumeBackup":
mm := BootVolumeSourceFromBootVolumeBackupDetails{}
err = json.Unmarshal(data, &mm)
return mm, err
case "bootVolume":
mm := BootVolumeSourceFromBootVolumeDetails{}
err = json.Unmarshal(data, &mm)
return mm, err
case "bootVolumeReplica":
mm := BootVolumeSourceFromBootVolumeReplicaDetails{}
err = json.Unmarshal(data, &mm)
return mm, err
default:
return *m, nil
}
}
func (m bootvolumesourcedetails) String() string {
return common.PointerString(m)
}

View file

@ -0,0 +1,44 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
// Core Services API
//
// Use the Core Services API to manage resources such as virtual cloud networks (VCNs),
// compute instances, and block storage volumes. For more information, see the console
// documentation for the Networking (https://docs.cloud.oracle.com/iaas/Content/Network/Concepts/overview.htm),
// Compute (https://docs.cloud.oracle.com/iaas/Content/Compute/Concepts/computeoverview.htm), and
// Block Volume (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/overview.htm) services.
//
package core
import (
"encoding/json"
"github.com/oracle/oci-go-sdk/v54/common"
)
// BootVolumeSourceFromBootVolumeBackupDetails Specifies the boot volume backup.
type BootVolumeSourceFromBootVolumeBackupDetails struct {
// The OCID of the boot volume backup.
Id *string `mandatory:"true" json:"id"`
}
func (m BootVolumeSourceFromBootVolumeBackupDetails) String() string {
return common.PointerString(m)
}
// MarshalJSON marshals to json representation
func (m BootVolumeSourceFromBootVolumeBackupDetails) MarshalJSON() (buff []byte, e error) {
type MarshalTypeBootVolumeSourceFromBootVolumeBackupDetails BootVolumeSourceFromBootVolumeBackupDetails
s := struct {
DiscriminatorParam string `json:"type"`
MarshalTypeBootVolumeSourceFromBootVolumeBackupDetails
}{
"bootVolumeBackup",
(MarshalTypeBootVolumeSourceFromBootVolumeBackupDetails)(m),
}
return json.Marshal(&s)
}

View file

@ -0,0 +1,44 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
// Core Services API
//
// Use the Core Services API to manage resources such as virtual cloud networks (VCNs),
// compute instances, and block storage volumes. For more information, see the console
// documentation for the Networking (https://docs.cloud.oracle.com/iaas/Content/Network/Concepts/overview.htm),
// Compute (https://docs.cloud.oracle.com/iaas/Content/Compute/Concepts/computeoverview.htm), and
// Block Volume (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/overview.htm) services.
//
package core
import (
"encoding/json"
"github.com/oracle/oci-go-sdk/v54/common"
)
// BootVolumeSourceFromBootVolumeDetails Specifies the source boot volume.
type BootVolumeSourceFromBootVolumeDetails struct {
// The OCID of the boot volume.
Id *string `mandatory:"true" json:"id"`
}
func (m BootVolumeSourceFromBootVolumeDetails) String() string {
return common.PointerString(m)
}
// MarshalJSON marshals to json representation
func (m BootVolumeSourceFromBootVolumeDetails) MarshalJSON() (buff []byte, e error) {
type MarshalTypeBootVolumeSourceFromBootVolumeDetails BootVolumeSourceFromBootVolumeDetails
s := struct {
DiscriminatorParam string `json:"type"`
MarshalTypeBootVolumeSourceFromBootVolumeDetails
}{
"bootVolume",
(MarshalTypeBootVolumeSourceFromBootVolumeDetails)(m),
}
return json.Marshal(&s)
}

View file

@ -0,0 +1,46 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
// Core Services API
//
// Use the Core Services API to manage resources such as virtual cloud networks (VCNs),
// compute instances, and block storage volumes. For more information, see the console
// documentation for the Networking (https://docs.cloud.oracle.com/iaas/Content/Network/Concepts/overview.htm),
// Compute (https://docs.cloud.oracle.com/iaas/Content/Compute/Concepts/computeoverview.htm), and
// Block Volume (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/overview.htm) services.
//
package core
import (
"encoding/json"
"github.com/oracle/oci-go-sdk/v54/common"
)
// BootVolumeSourceFromBootVolumeReplicaDetails Specifies the source boot volume replica which the boot volume will be created from.
// The boot volume replica shoulbe be in the same availability domain as the boot volume.
// Only one volume can be created from a replica at the same time.
type BootVolumeSourceFromBootVolumeReplicaDetails struct {
// The OCID of the boot volume replica.
Id *string `mandatory:"true" json:"id"`
}
func (m BootVolumeSourceFromBootVolumeReplicaDetails) String() string {
return common.PointerString(m)
}
// MarshalJSON marshals to json representation
func (m BootVolumeSourceFromBootVolumeReplicaDetails) MarshalJSON() (buff []byte, e error) {
type MarshalTypeBootVolumeSourceFromBootVolumeReplicaDetails BootVolumeSourceFromBootVolumeReplicaDetails
s := struct {
DiscriminatorParam string `json:"type"`
MarshalTypeBootVolumeSourceFromBootVolumeReplicaDetails
}{
"bootVolumeReplica",
(MarshalTypeBootVolumeSourceFromBootVolumeReplicaDetails)(m),
}
return json.Marshal(&s)
}

View file

@ -0,0 +1,29 @@
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
// Core Services API
//
// Use the Core Services API to manage resources such as virtual cloud networks (VCNs),
// compute instances, and block storage volumes. For more information, see the console
// documentation for the Networking (https://docs.cloud.oracle.com/iaas/Content/Network/Concepts/overview.htm),
// Compute (https://docs.cloud.oracle.com/iaas/Content/Compute/Concepts/computeoverview.htm), and
// Block Volume (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/overview.htm) services.
//
package core
import (
"github.com/oracle/oci-go-sdk/v54/common"
)
// BulkAddVirtualCircuitPublicPrefixesDetails The representation of BulkAddVirtualCircuitPublicPrefixesDetails
type BulkAddVirtualCircuitPublicPrefixesDetails struct {
// The public IP prefixes (CIDRs) to add to the public virtual circuit.
PublicPrefixes []CreateVirtualCircuitPublicPrefixDetails `mandatory:"true" json:"publicPrefixes"`
}
func (m BulkAddVirtualCircuitPublicPrefixesDetails) String() string {
return common.PointerString(m)
}

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