filename
stringlengths 4
198
| content
stringlengths 25
939k
| environment
sequence | variablearg
sequence | constarg
sequence | variableargjson
stringclasses 1
value | constargjson
stringlengths 2
3.9k
| lang
stringclasses 3
values | constargcount
float64 0
129
⌀ | variableargcount
float64 0
0
⌀ | sentence
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|
manage.py | #!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'open_library.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
| [] | [] | [] | [] | [] | python | 0 | 0 | |
parser_test.go | package gitprompt
import (
"bufio"
"bytes"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path"
"testing"
)
func TestParseValues(t *testing.T) {
tests := []struct {
name string
setup string
expected *GitStatus
}{
{
name: "not git repo",
expected: nil,
},
{
name: "dirty",
setup: `
git init
touch test
`,
expected: &GitStatus{
Untracked: 1,
},
},
{
name: "staged",
setup: `
git init
touch test
git add test
`,
expected: &GitStatus{
Staged: 1,
},
},
{
name: "modified",
setup: `
git init
echo "hello" >> test
git add test
git commit -m 'initial'
echo "world" >> test
`,
expected: &GitStatus{
Modified: 1,
},
},
{
name: "deleted",
setup: `
git init
echo "hello" >> test
git add test
git commit -m 'initial'
rm test
`,
expected: &GitStatus{
Modified: 1,
},
},
{
name: "conflicts",
setup: `
git init
git commit --allow-empty -m 'initial'
git checkout -b other
git checkout master
echo foo >> test
git add test
git commit -m 'first'
git checkout other
echo bar >> test
git add test
git commit -m 'first'
git rebase master || true
`,
expected: &GitStatus{
Conflicts: 1,
},
},
{
name: "ahead",
setup: `
git init
git remote add origin $REMOTE
git commit --allow-empty -m 'first'
git push -u origin HEAD
git commit --allow-empty -m 'second'
`,
expected: &GitStatus{
Ahead: 1,
},
},
{
name: "behind",
setup: `
git init
git remote add origin $REMOTE
git commit --allow-empty -m 'first'
git commit --allow-empty -m 'second'
git push -u origin HEAD
git reset --hard HEAD^
`,
expected: &GitStatus{
Behind: 1,
},
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
dir, cleanupDir := setupTestDir(t)
defer cleanupDir()
if test.setup != "" {
remote, cleanupRemote := setupRemote(t, dir)
defer cleanupRemote()
commands := "export REMOTE=" + remote + "\n" + test.setup
setupCommands(t, dir, commands)
}
actual, err := Parse()
if err != nil {
t.Errorf("Received unexpected error: %v", err)
return
}
if test.expected == nil {
if actual != nil {
t.Errorf("Expected nil return, got %v", actual)
}
return
}
assertInt(t, "Untracked", test.expected.Untracked, actual.Untracked)
assertInt(t, "Modified", test.expected.Modified, actual.Modified)
assertInt(t, "Staged", test.expected.Staged, actual.Staged)
assertInt(t, "Conflicts", test.expected.Conflicts, actual.Conflicts)
assertInt(t, "Ahead", test.expected.Ahead, actual.Ahead)
assertInt(t, "Behind", test.expected.Behind, actual.Behind)
})
}
}
func TestParseHead(t *testing.T) {
dir, done := setupTestDir(t)
defer done()
setupCommands(t, dir, `
git init
`)
s, _ := Parse()
assertString(t, "branch", "master", s.Branch)
setupCommands(t, dir, `
git commit --allow-empty -m 'initial'
`)
s, _ = Parse()
assertString(t, "branch", "master", s.Branch)
setupCommands(t, dir, `
git checkout -b other
`)
s, _ = Parse()
assertString(t, "branch", "other", s.Branch)
setupCommands(t, dir, `
git commit --allow-empty -m 'second'
git checkout HEAD^
`)
s, _ = Parse()
assertString(t, "branch", "", s.Branch)
if len(s.Sha) != 40 {
t.Errorf("Expected 40 char hash, got %v (%s)", len(s.Sha), s.Sha)
}
}
func TestExecGitErr(t *testing.T) {
path := os.Getenv("PATH")
os.Setenv("PATH", "")
defer os.Setenv("PATH", path)
_, err := Parse()
if err == nil {
t.Errorf("Expected error when git not found on $PATH")
}
}
func setupTestDir(t *testing.T) (string, func()) {
dir, err := ioutil.TempDir("", "gitprompt-test")
if err != nil {
t.Fatalf("Create temp dir: %v", err)
}
if err = os.Chdir(dir); err != nil {
t.Fatalf("Could not change dir: %v", err)
}
return dir, func() {
if err = os.RemoveAll(dir); err != nil {
fmt.Fprintf(os.Stderr, "Failed to clean up test dir: %v\n", err)
}
}
}
func setupRemote(t *testing.T, dir string) (string, func()) {
// Set up remote dir
remote, err := ioutil.TempDir("", "gitprompt-test-remote.git")
if err != nil {
t.Fatalf("create temp dir for remote: %v", err)
}
remoteCmd := exec.Command("git", "init", "--bare")
remoteCmd.Dir = remote
if err = remoteCmd.Run(); err != nil {
t.Fatalf("Set up remote: %v", err)
}
return remote, func() {
if err = os.RemoveAll(remote); err != nil {
fmt.Fprintf(os.Stderr, "Failed to clean up remote dir: %v\n", err)
}
}
}
func setupCommands(t *testing.T, dir, commands string) {
commands = "set -eo pipefail\n" + commands
script := path.Join(dir, "setup.sh")
if err := ioutil.WriteFile(script, []byte(commands), 0644); err != nil {
t.Fatal(err)
}
cmd := exec.Command("bash", "setup.sh")
var stderr bytes.Buffer
var stdout bytes.Buffer
cmd.Stderr = bufio.NewWriter(&stderr)
cmd.Stdout = bufio.NewWriter(&stdout)
cmd.Dir = dir
if err := cmd.Run(); err != nil {
t.Log("STDOUT:", stdout.String())
t.Log("STDERR:", stderr.String())
t.Fatalf("Setup command failed: %v", err)
}
if err := os.Remove(script); err != nil {
t.Fatal(err)
}
}
func assertString(t *testing.T, name, expected, actual string) {
t.Helper()
if expected == actual {
return
}
t.Errorf("%s does not match\n\tExpected: %q\n\tActual: %q", name, expected, actual)
}
func assertInt(t *testing.T, name string, expected, actual int) {
t.Helper()
if expected == actual {
return
}
t.Errorf("%s does not match\n\tExpected: %v\n\tActual: %v", name, expected, actual)
}
| [
"\"PATH\""
] | [] | [
"PATH"
] | [] | ["PATH"] | go | 1 | 0 | |
tests/e2e/volume_health_test.go | /*
Copyright 2020 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package e2e
import (
"context"
"fmt"
"os"
"time"
"github.com/onsi/ginkgo"
"github.com/onsi/gomega"
cnstypes "github.com/vmware/govmomi/cns/types"
v1 "k8s.io/api/core/v1"
storagev1 "k8s.io/api/storage/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
clientset "k8s.io/client-go/kubernetes"
"k8s.io/kubernetes/test/e2e/framework"
fnodes "k8s.io/kubernetes/test/e2e/framework/node"
fpv "k8s.io/kubernetes/test/e2e/framework/pv"
fss "k8s.io/kubernetes/test/e2e/framework/statefulset"
"sigs.k8s.io/vsphere-csi-driver/pkg/csi/service/logger"
k8s "sigs.k8s.io/vsphere-csi-driver/pkg/kubernetes"
)
var _ = ginkgo.Describe("Volume health check", func() {
f := framework.NewDefaultFramework("volume-healthcheck")
var (
client clientset.Interface
namespace string
scParameters map[string]string
storagePolicyName string
raid0StoragePolicyName string
volumeHealthAnnotation string = "volumehealth.storage.kubernetes.io/health"
datastoreURL string
hostIP string
pvc *v1.PersistentVolumeClaim
pvclaim *v1.PersistentVolumeClaim
isVsanhealthServiceStopped bool
)
ginkgo.BeforeEach(func() {
bootstrap()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
client = f.ClientSet
namespace = getNamespaceToRunTests(f)
scParameters = make(map[string]string)
storagePolicyName = GetAndExpectStringEnvVar(envStoragePolicyNameForSharedDatastores)
nodeList, err := fnodes.GetReadySchedulableNodes(f.ClientSet)
datastoreURL = GetAndExpectStringEnvVar(envSharedDatastoreURL)
framework.ExpectNoError(err, "Unable to find ready and schedulable Node")
if guestCluster {
svcClient, svNamespace := getSvcClientAndNamespace()
setResourceQuota(svcClient, svNamespace, rqLimit)
}
if !(len(nodeList.Items) > 0) {
framework.Failf("Unable to find ready and schedulable Node")
}
isVsanhealthServiceStopped = false
waitForAllHostsToBeUp(ctx, &e2eVSphere)
})
ginkgo.AfterEach(func() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
vcAddress := e2eVSphere.Config.Global.VCenterHostname + ":" + sshdPort
if supervisorCluster {
deleteResourceQuota(client, namespace)
}
if pvc != nil {
ginkgo.By("checking host status")
err := waitForHostToBeUp(hostIP)
time.Sleep(pollTimeoutShort)
if err != nil {
time.Sleep(pollTimeoutShort)
}
err = fpv.DeletePersistentVolumeClaim(client, pvc.Name, namespace)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
}
if pvclaim != nil {
ginkgo.By("checking host status")
err := waitForHostToBeUp(hostIP)
time.Sleep(pollTimeoutShort)
if err != nil {
time.Sleep(pollTimeoutShort)
}
err = fpv.DeletePersistentVolumeClaim(client, pvclaim.Name, namespace)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
}
if isVsanhealthServiceStopped {
ginkgo.By(fmt.Sprintln("Starting vsan-health on the vCenter host"))
err := invokeVCenterServiceControl("start", vsanhealthServiceName, vcAddress)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
ginkgo.By(fmt.Sprintf("Sleeping for %v seconds to allow vsan-health to come up again", vsanHealthServiceWaitTime))
time.Sleep(time.Duration(vsanHealthServiceWaitTime) * time.Second)
}
if guestCluster {
svcClient, svNamespace := getSvcClientAndNamespace()
setResourceQuota(svcClient, svNamespace, defaultrqLimit)
}
waitForAllHostsToBeUp(ctx, &e2eVSphere)
})
/*
Test to verify health annotation status is accessible on the pvc .
(Combined test for TC1 and TC2)
Steps
1. Create a Storage Class
2. Create a PVC using above SC
3. Wait for PVC to be in Bound phase
4. Verify health annotation is added on the PVC is accessible
5. Wait for the CNS health api to be called again (No changes made to PV/PVC, expecting it to be accessible)
6. Delete PVC
7. Verify PV entry is deleted from CNS
8. Delete the SC
*/
ginkgo.It("[csi-supervisor] [csi-guest] Verify health annotation added on the pvc is accessible", func() {
var storageclass *storagev1.StorageClass
var pvclaim *v1.PersistentVolumeClaim
var err error
var pvclaims []*v1.PersistentVolumeClaim
ctx, cancel := context.WithCancel(context.Background())
log := logger.GetLogger(ctx)
defer cancel()
ginkgo.By("Invoking Test for validating health status")
// decide which test setup is available to run
if supervisorCluster {
ginkgo.By("CNS_TEST: Running for WCP setup")
profileID := e2eVSphere.GetSpbmPolicyID(storagePolicyName)
scParameters[scParamStoragePolicyID] = profileID
// create resource quota
createResourceQuota(client, namespace, rqLimit, storagePolicyName)
storageclass, pvclaim, err = createPVCAndStorageClass(client, namespace, nil, scParameters, diskSize, nil, "", false, "", storagePolicyName)
} else if guestCluster {
ginkgo.By("CNS_TEST: Running for GC setup")
scParameters[svStorageClassName] = storagePolicyName
storageclass, pvclaim, err = createPVCAndStorageClass(client, namespace, nil, scParameters, diskSize, nil, "", false, "")
}
gomega.Expect(err).NotTo(gomega.HaveOccurred())
defer func() {
err := client.StorageV1().StorageClasses().Delete(ctx, storageclass.Name, *metav1.NewDeleteOptions(0))
gomega.Expect(err).NotTo(gomega.HaveOccurred())
}()
ginkgo.By("Expect claim to provision volume successfully")
err = fpv.WaitForPersistentVolumeClaimPhase(v1.ClaimBound, client, pvclaim.Namespace, pvclaim.Name, framework.Poll, framework.ClaimProvisionTimeout)
gomega.Expect(err).NotTo(gomega.HaveOccurred(), "Failed to provision volume")
pvclaims = append(pvclaims, pvclaim)
persistentvolumes, err := fpv.WaitForPVClaimBoundPhase(client, pvclaims, framework.ClaimProvisionTimeout)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
volHandle := persistentvolumes[0].Spec.CSI.VolumeHandle
svPVCName := volHandle
if guestCluster {
// svcPVCName refers to PVC Name in the supervisor cluster
svcPVCName := volHandle
volHandle = getVolumeIDFromSupervisorCluster(svcPVCName)
}
gomega.Expect(volHandle).NotTo(gomega.BeEmpty())
defer func() {
err := fpv.DeletePersistentVolumeClaim(client, pvclaim.Name, namespace)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
pvclaim = nil
err = e2eVSphere.waitForCNSVolumeToBeDeleted(volHandle)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
}()
for counter := 0; counter < 2; counter++ {
ginkgo.By(fmt.Sprintf("Sleeping for %v minutes to allow volume health check to be triggered", healthStatusWaitTime))
time.Sleep(healthStatusWaitTime)
ginkgo.By("Expect health status of the pvc to be accessible")
pvc, err := client.CoreV1().PersistentVolumeClaims(pvclaim.Namespace).Get(ctx, pvclaim.Name, metav1.GetOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
gomega.Expect(pvc.Annotations[volumeHealthAnnotation]).Should(gomega.BeEquivalentTo(healthStatusAccessible))
if guestCluster {
//verifying svc pvc health status
ginkgo.By("Expect health annotation is added on the SV pvc")
svPVC := getPVCFromSupervisorCluster(svPVCName)
gomega.Expect(svPVC.Annotations[volumeHealthAnnotation]).Should(gomega.BeEquivalentTo(healthStatusAccessible))
}
}
ginkgo.By(fmt.Sprintf("Invoking QueryCNSVolumeWithResult with VolumeID: %s", volHandle))
queryResult, err := e2eVSphere.queryCNSVolumeWithResult(volHandle)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
gomega.Expect(len(queryResult.Volumes) > 0)
ginkgo.By("Verifying the volume health status returned by CNS(green/yellow/red")
for _, vol := range queryResult.Volumes {
log.Infof("Volume health status: %s", vol.HealthStatus)
gomega.Expect(vol.HealthStatus).Should(gomega.BeEquivalentTo(healthGreen))
}
})
/*
Test to verify health annotation status is not added on the pvc which is on pending state .
Steps
1. Create a Storage Class with non shared datastore
2. Create a PVC using above SC
3. PVC will be created and it will be in pending state
4. Verify health annotation is not added on the PVC
5. Delete PVC
7. Delete the SC
*/
ginkgo.It("[csi-supervisor] [csi-guest] Verify health annotation is not added on the pvc which is on pending state", func() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
nonShareadstoragePolicyName := GetAndExpectStringEnvVar(envStoragePolicyNameForNonSharedDatastores)
var storageclass *storagev1.StorageClass
var pvclaim *v1.PersistentVolumeClaim
var err error
ginkgo.By("Invoking Test for validating health annotation is not added to PVC on Pending state")
// decide which test setup is available to run
if supervisorCluster {
ginkgo.By("CNS_TEST: Running for WCP setup")
profileID := e2eVSphere.GetSpbmPolicyID(nonShareadstoragePolicyName)
scParameters[scParamStoragePolicyID] = profileID
// create resource quota
createResourceQuota(client, namespace, rqLimit, nonShareadstoragePolicyName)
storageclass, pvclaim, err = createPVCAndStorageClass(client, namespace, nil, scParameters, diskSize, nil, "", false, "", nonShareadstoragePolicyName)
} else if guestCluster {
ginkgo.By("CNS_TEST: Running for GC setup")
scParameters[svStorageClassName] = nonShareadstoragePolicyName
storageclass, pvclaim, err = createPVCAndStorageClass(client, namespace, nil, scParameters, diskSize, nil, "", false, "")
}
gomega.Expect(err).NotTo(gomega.HaveOccurred())
defer func() {
err := client.StorageV1().StorageClasses().Delete(ctx, storageclass.Name, *metav1.NewDeleteOptions(0))
gomega.Expect(err).NotTo(gomega.HaveOccurred())
}()
ginkgo.By(fmt.Sprintf("Sleeping for %v minutes to allow volume health check to be triggered", healthStatusWaitTime))
time.Sleep(healthStatusWaitTime)
ginkgo.By("Verify health status annotation is not added to the pvc in pending state")
pvc, err := client.CoreV1().PersistentVolumeClaims(pvclaim.Namespace).Get(ctx, pvclaim.Name, metav1.GetOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
for describe := range pvc.Annotations {
gomega.Expect(pvc.Annotations[describe]).ShouldNot(gomega.BeEquivalentTo(volumeHealthAnnotation))
}
defer func() {
err := fpv.DeletePersistentVolumeClaim(client, pvclaim.Name, namespace)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
pvclaim = nil
}()
})
/*
Validate the health status is updated from "unknown" status to accessible .
Steps
1. Create a Storage Class
2. Create a PVC using above SC
3. Wait for PVC to be in Bound phase
4. Bring vSAN-health down
5. Verify no health annotation is added on the PVC
6. Bring vSAN-health up
7. Verify health annotation which is added on the PVC is accessible
8. Delete PVC
9. Verify PV entry is deleted from CNS
10. Delete the SC
*/
ginkgo.It("[csi-supervisor] [csi-guest] Verify health annotation is updated from unknown status to accessible", func() {
var storageclass *storagev1.StorageClass
var pvclaim *v1.PersistentVolumeClaim
var err error
var pvclaims []*v1.PersistentVolumeClaim
ctx, cancel := context.WithCancel(context.Background())
log := logger.GetLogger(ctx)
defer cancel()
ginkgo.By("Invoking Test for validating health status")
// decide which test setup is available to run
if supervisorCluster {
ginkgo.By("CNS_TEST: Running for WCP setup")
profileID := e2eVSphere.GetSpbmPolicyID(storagePolicyName)
scParameters[scParamStoragePolicyID] = profileID
// create resource quota
createResourceQuota(client, namespace, rqLimit, storagePolicyName)
storageclass, pvclaim, err = createPVCAndStorageClass(client, namespace, nil, scParameters, diskSize, nil, "", false, "", storagePolicyName)
} else if guestCluster {
ginkgo.By("CNS_TEST: Running for GC setup")
scParameters[svStorageClassName] = storagePolicyName
storageclass, pvclaim, err = createPVCAndStorageClass(client, namespace, nil, scParameters, diskSize, nil, "", false, "")
}
gomega.Expect(err).NotTo(gomega.HaveOccurred())
defer func() {
err := client.StorageV1().StorageClasses().Delete(ctx, storageclass.Name, *metav1.NewDeleteOptions(0))
gomega.Expect(err).NotTo(gomega.HaveOccurred())
}()
ginkgo.By("Expect claim to provision volume successfully")
err = fpv.WaitForPersistentVolumeClaimPhase(v1.ClaimBound, client, pvclaim.Namespace, pvclaim.Name, framework.Poll, framework.ClaimProvisionShortTimeout)
gomega.Expect(err).NotTo(gomega.HaveOccurred(), "Failed to provision volume")
pvclaims = append(pvclaims, pvclaim)
persistentvolumes, err := fpv.WaitForPVClaimBoundPhase(client, pvclaims, framework.ClaimProvisionTimeout)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
volHandle := persistentvolumes[0].Spec.CSI.VolumeHandle
svPVCName := volHandle
if guestCluster {
// svcPVCName refers to PVC Name in the supervisor cluster
svcPVCName := volHandle
volHandle = getVolumeIDFromSupervisorCluster(svcPVCName)
}
gomega.Expect(volHandle).NotTo(gomega.BeEmpty())
ginkgo.By(fmt.Sprintln("Stopping vsan-health on the vCenter host"))
vcAddress := e2eVSphere.Config.Global.VCenterHostname + ":" + sshdPort
err = invokeVCenterServiceControl(stopOperation, vsanhealthServiceName, vcAddress)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
ginkgo.By(fmt.Sprintf("Sleeping for %v seconds to allow vsan-health to completely shutdown", vsanHealthServiceWaitTime))
time.Sleep(time.Duration(vsanHealthServiceWaitTime) * time.Second)
ginkgo.By(fmt.Sprintf("Sleeping for %v minutes to allow volume health check to be triggered", healthStatusWaitTime))
time.Sleep(healthStatusWaitTime)
ginkgo.By("Expect health annotation is not added on the pvc")
pvc, err := client.CoreV1().PersistentVolumeClaims(pvclaim.Namespace).Get(ctx, pvclaim.Name, metav1.GetOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
for describe := range pvc.Annotations {
gomega.Expect(pvc.Annotations[describe]).ShouldNot(gomega.BeEquivalentTo(volumeHealthAnnotation))
}
if guestCluster {
ginkgo.By("Expect health annotation is not added on the SV pvc")
svPVC := getPVCFromSupervisorCluster(svPVCName)
for describe := range svPVC.Annotations {
gomega.Expect(svPVC.Annotations[describe]).ShouldNot(gomega.BeEquivalentTo(volumeHealthAnnotation))
}
}
ginkgo.By(fmt.Sprintln("Starting vsan-health on the vCenter host"))
err = invokeVCenterServiceControl(startOperation, vsanhealthServiceName, vcAddress)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
ginkgo.By(fmt.Sprintf("Sleeping for %v seconds to allow vsan-health to come up again", vsanHealthServiceWaitTime))
time.Sleep(time.Duration(vsanHealthServiceWaitTime) * time.Second)
ginkgo.By(fmt.Sprintf("Sleeping for %v minutes to allow volume health check to be triggered", healthStatusWaitTime))
time.Sleep(healthStatusWaitTime)
ginkgo.By("Expect health annotation is added on the pvc and its accessible")
pvc, err = client.CoreV1().PersistentVolumeClaims(pvclaim.Namespace).Get(ctx, pvclaim.Name, metav1.GetOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
gomega.Expect(pvc.Annotations[volumeHealthAnnotation]).Should(gomega.BeEquivalentTo(healthStatusAccessible))
if guestCluster {
//verifying svc pvc health status
ginkgo.By("Expect health annotation is added on the SV pvc")
svPVC := getPVCFromSupervisorCluster(svPVCName)
gomega.Expect(svPVC.Annotations[volumeHealthAnnotation]).Should(gomega.BeEquivalentTo(healthStatusAccessible))
}
defer func() {
err := fpv.DeletePersistentVolumeClaim(client, pvclaim.Name, namespace)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
pvclaim = nil
err = e2eVSphere.waitForCNSVolumeToBeDeleted(volHandle)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
}()
ginkgo.By(fmt.Sprintf("Invoking QueryCNSVolumeWithResult with VolumeID: %s", volHandle))
queryResult, err := e2eVSphere.queryCNSVolumeWithResult(volHandle)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
gomega.Expect(len(queryResult.Volumes) > 0)
ginkgo.By("Verifying the volume health status returned by CNS(green/yellow/red")
for _, vol := range queryResult.Volumes {
log.Infof("Volume health status: %s", vol.HealthStatus)
gomega.Expect(vol.HealthStatus).Should(gomega.BeEquivalentTo(healthGreen))
}
ginkgo.By("Verifying disk size specified in PVC is honored")
if queryResult.Volumes[0].BackingObjectDetails.(*cnstypes.CnsBlockBackingDetails).CapacityInMb != diskSizeInMb {
err = fmt.Errorf("Wrong disk size provisioned ")
}
gomega.Expect(err).NotTo(gomega.HaveOccurred())
})
/*
Validate the health status is not updated to "unknown" status from accessible
Steps
1. Create a Storage Class
2. Create a PVC using above SC
3. Wait for PVC to be in Bound phase
4. Verify health annotation which is added on the PVC is accessible
5. Bring VSAN down
6. Verify the health annotation of the PVC remains accessible
7. Bring VSAN up
8. Verify health annotation which is added on the PVC is accessible
9. Delete PVC
10. Verify PV entry is deleted from CNS
11. Delete the SC
*/
ginkgo.It("[csi-supervisor] [csi-guest] Verify health annotation is not updated to unknown status from accessible", func() {
var storageclass *storagev1.StorageClass
var pvclaim *v1.PersistentVolumeClaim
var err error
var pvclaims []*v1.PersistentVolumeClaim
ctx, cancel := context.WithCancel(context.Background())
log := logger.GetLogger(ctx)
defer cancel()
ginkgo.By("Invoking Test for validating health status")
// decide which test setup is available to run
if supervisorCluster {
ginkgo.By("CNS_TEST: Running for WCP setup")
profileID := e2eVSphere.GetSpbmPolicyID(storagePolicyName)
scParameters[scParamStoragePolicyID] = profileID
// create resource quota
createResourceQuota(client, namespace, rqLimit, storagePolicyName)
storageclass, pvclaim, err = createPVCAndStorageClass(client, namespace, nil, scParameters, diskSize, nil, "", false, "", storagePolicyName)
} else if guestCluster {
ginkgo.By("CNS_TEST: Running for GC setup")
scParameters[svStorageClassName] = storagePolicyName
storageclass, pvclaim, err = createPVCAndStorageClass(client, namespace, nil, scParameters, diskSize, nil, "", false, "")
}
gomega.Expect(err).NotTo(gomega.HaveOccurred())
defer func() {
err := client.StorageV1().StorageClasses().Delete(ctx, storageclass.Name, *metav1.NewDeleteOptions(0))
gomega.Expect(err).NotTo(gomega.HaveOccurred())
}()
ginkgo.By("Expect claim to provision volume successfully")
err = fpv.WaitForPersistentVolumeClaimPhase(v1.ClaimBound, client, pvclaim.Namespace, pvclaim.Name, framework.Poll, framework.ClaimProvisionTimeout)
gomega.Expect(err).NotTo(gomega.HaveOccurred(), "Failed to provision volume")
pvclaims = append(pvclaims, pvclaim)
persistentvolumes, err := fpv.WaitForPVClaimBoundPhase(client, pvclaims, framework.ClaimProvisionTimeout)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
volHandle := persistentvolumes[0].Spec.CSI.VolumeHandle
svPVCName := volHandle
if guestCluster {
// svcPVCName refers to PVC Name in the supervisor cluster
svcPVCName := volHandle
volHandle = getVolumeIDFromSupervisorCluster(svcPVCName)
}
gomega.Expect(volHandle).NotTo(gomega.BeEmpty())
ginkgo.By(fmt.Sprintf("Sleeping for %v minutes to allow volume health check to be triggered", healthStatusWaitTime))
time.Sleep(healthStatusWaitTime)
ginkgo.By("Expect health annotation is added on the pvc and its accessible")
pvc, err := client.CoreV1().PersistentVolumeClaims(pvclaim.Namespace).Get(ctx, pvclaim.Name, metav1.GetOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
gomega.Expect(pvc.Annotations[volumeHealthAnnotation]).Should(gomega.BeEquivalentTo(healthStatusAccessible))
if guestCluster {
//verifying svc pvc health status
ginkgo.By("Expect health annotation is added on the SV pvc")
svPVC := getPVCFromSupervisorCluster(svPVCName)
gomega.Expect(svPVC.Annotations[volumeHealthAnnotation]).Should(gomega.BeEquivalentTo(healthStatusAccessible))
}
ginkgo.By("Verifying the volume health status returned by CNS(green/yellow/red")
queryResult, err := e2eVSphere.queryCNSVolumeWithResult(volHandle)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
for _, vol := range queryResult.Volumes {
log.Infof("Volume health status: %s", vol.HealthStatus)
gomega.Expect(vol.HealthStatus).Should(gomega.BeEquivalentTo(healthGreen))
}
ginkgo.By(fmt.Sprintln("Stopping vsan-health on the vCenter host"))
vcAddress := e2eVSphere.Config.Global.VCenterHostname + ":" + sshdPort
err = invokeVCenterServiceControl(stopOperation, vsanhealthServiceName, vcAddress)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
ginkgo.By(fmt.Sprintf("Sleeping for %v seconds to allow vsan-health to completely shutdown", vsanHealthServiceWaitTime))
time.Sleep(time.Duration(vsanHealthServiceWaitTime) * time.Second)
ginkgo.By(fmt.Sprintf("Sleeping for %v minutes to allow volume health check to be triggered", healthStatusWaitTime))
time.Sleep(healthStatusWaitTime)
ginkgo.By("Expect health annotation is added on the pvc and its accessible after the vsan health is down")
pvc, err = client.CoreV1().PersistentVolumeClaims(pvclaim.Namespace).Get(ctx, pvclaim.Name, metav1.GetOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
gomega.Expect(pvc.Annotations[volumeHealthAnnotation]).Should(gomega.BeEquivalentTo(healthStatusAccessible))
if guestCluster {
//verifying svc pvc health status
ginkgo.By("Expect health annotation is added on the SV pvc")
svPVC := getPVCFromSupervisorCluster(svPVCName)
gomega.Expect(svPVC.Annotations[volumeHealthAnnotation]).Should(gomega.BeEquivalentTo(healthStatusAccessible))
}
ginkgo.By(fmt.Sprintln("Starting vsan-health on the vCenter host"))
err = invokeVCenterServiceControl(startOperation, vsanhealthServiceName, vcAddress)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
ginkgo.By(fmt.Sprintf("Sleeping for %v seconds to allow vsan-health to come up again", vsanHealthServiceWaitTime))
time.Sleep(time.Duration(vsanHealthServiceWaitTime) * time.Second)
ginkgo.By(fmt.Sprintf("Sleeping for %v minutes to allow volume health check to be triggered", healthStatusWaitTime))
time.Sleep(healthStatusWaitTime)
ginkgo.By("Expect health annotation is added on the pvc and its accessible")
pvc, err = client.CoreV1().PersistentVolumeClaims(pvclaim.Namespace).Get(ctx, pvclaim.Name, metav1.GetOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
gomega.Expect(pvc.Annotations[volumeHealthAnnotation]).Should(gomega.BeEquivalentTo(healthStatusAccessible))
defer func() {
err := fpv.DeletePersistentVolumeClaim(client, pvclaim.Name, namespace)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
pvclaim = nil
err = e2eVSphere.waitForCNSVolumeToBeDeleted(volHandle)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
}()
gomega.Expect(len(queryResult.Volumes) > 0)
ginkgo.By("Verifying the volume health status returned by CNS(green/yellow/red")
for _, vol := range queryResult.Volumes {
log.Infof("Volume health status: %s", vol.HealthStatus)
gomega.Expect(vol.HealthStatus).Should(gomega.BeEquivalentTo(healthGreen))
}
})
/*
Validate the health status is not updated when SPS is down .
Steps
1. Create a Storage Class
2. Create a PVC using above SC
3. Wait for PVC to be in Bound phase
4. Bring SPS down
5. Verify no annotation is added on the PVC
6. Bring SPS up
7. Verify annotation is added on the PVC is accessible
8. Delete PVC
9. Verify PV entry is deleted from CNS
10. Delete the SC
*/
ginkgo.It("[csi-supervisor] [csi-guest] Verify health annotation is not updated when SPS is down", func() {
var storageclass *storagev1.StorageClass
var pvclaim *v1.PersistentVolumeClaim
var err error
var pvclaims []*v1.PersistentVolumeClaim
ctx, cancel := context.WithCancel(context.Background())
log := logger.GetLogger(ctx)
defer cancel()
ginkgo.By("Invoking Test for validating health status")
// decide which test setup is available to run
if supervisorCluster {
ginkgo.By("CNS_TEST: Running for WCP setup")
profileID := e2eVSphere.GetSpbmPolicyID(storagePolicyName)
scParameters[scParamStoragePolicyID] = profileID
// create resource quota
createResourceQuota(client, namespace, rqLimit, storagePolicyName)
storageclass, pvclaim, err = createPVCAndStorageClass(client, namespace, nil, scParameters, diskSize, nil, "", false, "", storagePolicyName)
} else if guestCluster {
ginkgo.By("CNS_TEST: Running for GC setup")
scParameters[svStorageClassName] = storagePolicyName
storageclass, pvclaim, err = createPVCAndStorageClass(client, namespace, nil, scParameters, diskSize, nil, "", false, "")
}
gomega.Expect(err).NotTo(gomega.HaveOccurred())
defer func() {
err := client.StorageV1().StorageClasses().Delete(ctx, storageclass.Name, *metav1.NewDeleteOptions(0))
gomega.Expect(err).NotTo(gomega.HaveOccurred())
}()
ginkgo.By("Expect claim to provision volume successfully")
err = fpv.WaitForPersistentVolumeClaimPhase(v1.ClaimBound, client, pvclaim.Namespace, pvclaim.Name, framework.Poll, framework.ClaimProvisionTimeout)
gomega.Expect(err).NotTo(gomega.HaveOccurred(), "Failed to provision volume")
pvclaims = append(pvclaims, pvclaim)
persistentvolumes, err := fpv.WaitForPVClaimBoundPhase(client, pvclaims, framework.ClaimProvisionTimeout)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
volHandle := persistentvolumes[0].Spec.CSI.VolumeHandle
svPVCName := volHandle
if guestCluster {
// svcPVCName refers to PVC Name in the supervisor cluster
svcPVCName := volHandle
volHandle = getVolumeIDFromSupervisorCluster(svcPVCName)
}
gomega.Expect(volHandle).NotTo(gomega.BeEmpty())
ginkgo.By(fmt.Sprintln("Stopping sps on the vCenter host"))
vcAddress := e2eVSphere.Config.Global.VCenterHostname + ":" + sshdPort
err = invokeVCenterServiceControl(stopOperation, spsServiceName, vcAddress)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
ginkgo.By(fmt.Sprintf("Sleeping for %v seconds to allow sps to completely shutdown", vsanHealthServiceWaitTime))
time.Sleep(time.Duration(vsanHealthServiceWaitTime) * time.Second)
ginkgo.By(fmt.Sprintf("Sleeping for %v minutes to allow volume health check to be triggered", healthStatusWaitTime))
time.Sleep(healthStatusWaitTime)
ginkgo.By("Expect health annotation is not added on the pvc")
pvc, err := client.CoreV1().PersistentVolumeClaims(pvclaim.Namespace).Get(ctx, pvclaim.Name, metav1.GetOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
for describe := range pvc.Annotations {
gomega.Expect(pvc.Annotations[describe]).ShouldNot(gomega.BeEquivalentTo(volumeHealthAnnotation))
}
if guestCluster {
ginkgo.By("Expect health annotation is not added on the SV pvc")
svPVC := getPVCFromSupervisorCluster(svPVCName)
for describe := range svPVC.Annotations {
gomega.Expect(svPVC.Annotations[describe]).ShouldNot(gomega.BeEquivalentTo(volumeHealthAnnotation))
}
}
ginkgo.By(fmt.Sprintln("Starting sps on the vCenter host"))
err = invokeVCenterServiceControl(startOperation, spsServiceName, vcAddress)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
ginkgo.By(fmt.Sprintf("Sleeping for %v seconds to allow sps to come up again", vsanHealthServiceWaitTime))
time.Sleep(time.Duration(vsanHealthServiceWaitTime) * time.Second)
ginkgo.By(fmt.Sprintf("Sleeping for %v minutes to allow volume health check to be triggered", healthStatusWaitTime))
time.Sleep(healthStatusWaitTime)
ginkgo.By("Expect health annotation is added on the pvc and its accessible")
pvc, err = client.CoreV1().PersistentVolumeClaims(pvclaim.Namespace).Get(ctx, pvclaim.Name, metav1.GetOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
gomega.Expect(pvc.Annotations[volumeHealthAnnotation]).Should(gomega.BeEquivalentTo(healthStatusAccessible))
if guestCluster {
//verifying svc pvc health status
ginkgo.By("Expect health annotation is added on the SV pvc")
svPVC := getPVCFromSupervisorCluster(svPVCName)
gomega.Expect(svPVC.Annotations[volumeHealthAnnotation]).Should(gomega.BeEquivalentTo(healthStatusAccessible))
}
defer func() {
err := fpv.DeletePersistentVolumeClaim(client, pvclaim.Name, namespace)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
pvclaim = nil
err = e2eVSphere.waitForCNSVolumeToBeDeleted(volHandle)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
}()
ginkgo.By(fmt.Sprintf("Invoking QueryCNSVolumeWithResult with VolumeID: %s", volHandle))
queryResult, err := e2eVSphere.queryCNSVolumeWithResult(volHandle)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
gomega.Expect(len(queryResult.Volumes) > 0)
ginkgo.By("Verifying the volume health status returned by CNS(green/yellow/red")
for _, vol := range queryResult.Volumes {
log.Infof("Volume health status: %s", vol.HealthStatus)
gomega.Expect(vol.HealthStatus).Should(gomega.BeEquivalentTo(healthGreen))
}
})
/*
Verify changing the annotated values on the PVC to random value
Steps
1. Create a Storage Class
2. Create a PVC using above SC
3. Wait for PVC to be in Bound phase
4. Verify annotation added on the PVC in accessible
5. Kubectl edit on the annotation of the PVC and change the annotation to inaccessible state
6. Wait for the default time interval
7. Verify health annotation is added on the PVC is accessible
8. Delete PVC
9. Verify PV entry is deleted from CNS
10. Delete the SC
*/
ginkgo.It("[csi-supervisor] Verify changing the annotated values on the PVC to random value", func() {
var storageclass *storagev1.StorageClass
var pvclaim *v1.PersistentVolumeClaim
var err error
var pvclaims []*v1.PersistentVolumeClaim
ctx, cancel := context.WithCancel(context.Background())
log := logger.GetLogger(ctx)
defer cancel()
ginkgo.By("Invoking Test for validating health status")
// decide which test setup is available to run
if supervisorCluster {
ginkgo.By("CNS_TEST: Running for WCP setup")
profileID := e2eVSphere.GetSpbmPolicyID(storagePolicyName)
scParameters[scParamStoragePolicyID] = profileID
// create resource quota
createResourceQuota(client, namespace, rqLimit, storagePolicyName)
storageclass, pvclaim, err = createPVCAndStorageClass(client, namespace, nil, scParameters, diskSize, nil, "", false, "", storagePolicyName)
} else if guestCluster {
ginkgo.By("CNS_TEST: Running for GC setup")
scParameters[svStorageClassName] = storagePolicyName
storageclass, pvclaim, err = createPVCAndStorageClass(client, namespace, nil, scParameters, diskSize, nil, "", false, "")
}
gomega.Expect(err).NotTo(gomega.HaveOccurred())
defer func() {
err := client.StorageV1().StorageClasses().Delete(ctx, storageclass.Name, *metav1.NewDeleteOptions(0))
gomega.Expect(err).NotTo(gomega.HaveOccurred())
}()
ginkgo.By("Expect claim to provision volume successfully")
err = fpv.WaitForPersistentVolumeClaimPhase(v1.ClaimBound, client, pvclaim.Namespace, pvclaim.Name, framework.Poll, framework.ClaimProvisionTimeout)
gomega.Expect(err).NotTo(gomega.HaveOccurred(), "Failed to provision volume")
pvclaims = append(pvclaims, pvclaim)
persistentvolumes, err := fpv.WaitForPVClaimBoundPhase(client, pvclaims, framework.ClaimProvisionTimeout)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
volHandle := persistentvolumes[0].Spec.CSI.VolumeHandle
if guestCluster {
// svcPVCName refers to PVC Name in the supervisor cluster
svcPVCName := volHandle
volHandle = getVolumeIDFromSupervisorCluster(svcPVCName)
}
gomega.Expect(volHandle).NotTo(gomega.BeEmpty())
ginkgo.By(fmt.Sprintf("Sleeping for %v minutes to allow volume health check to be triggered", healthStatusWaitTime))
time.Sleep(healthStatusWaitTime)
ginkgo.By("Expect health status of the pvc to be accessible")
pvc, err := client.CoreV1().PersistentVolumeClaims(pvclaim.Namespace).Get(ctx, pvclaim.Name, metav1.GetOptions{})
gomega.Expect(pvc.Annotations[volumeHealthAnnotation]).Should(gomega.BeEquivalentTo(healthStatusAccessible))
gomega.Expect(err).NotTo(gomega.HaveOccurred())
ginkgo.By("Changing health status of the pvc to be inaccessible")
setAnnotation := make(map[string]string)
setAnnotation[volumeHealthAnnotation] = healthStatusInAccessible
pvc.Annotations = setAnnotation
_, err = client.CoreV1().PersistentVolumeClaims(pvc.Namespace).Update(ctx, pvc, metav1.UpdateOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
pvc, err = client.CoreV1().PersistentVolumeClaims(pvclaim.Namespace).Get(ctx, pvclaim.Name, metav1.GetOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
gomega.Expect(pvc.Annotations[volumeHealthAnnotation]).Should(gomega.BeEquivalentTo(healthStatusInAccessible))
ginkgo.By(fmt.Sprintf("Sleeping for %v minutes to allow volume health check to be triggered", healthStatusWaitTime))
time.Sleep(healthStatusWaitTime)
pvc, err = client.CoreV1().PersistentVolumeClaims(pvclaim.Namespace).Get(ctx, pvc.Name, metav1.GetOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
gomega.Expect(pvc.Annotations[volumeHealthAnnotation]).Should(gomega.BeEquivalentTo(healthStatusAccessible))
ginkgo.By("Changing health status of the pvc to be random value")
setAnnotation[volumeHealthAnnotation] = "vmware"
pvc.Annotations = setAnnotation
_, err = client.CoreV1().PersistentVolumeClaims(pvc.Namespace).Update(ctx, pvc, metav1.UpdateOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
pvc, err = client.CoreV1().PersistentVolumeClaims(pvclaim.Namespace).Get(ctx, pvclaim.Name, metav1.GetOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
gomega.Expect(pvc.Annotations[volumeHealthAnnotation]).Should(gomega.BeEquivalentTo("vmware"))
ginkgo.By(fmt.Sprintf("Sleeping for %v minutes to allow volume health check to be triggered", healthStatusWaitTime))
time.Sleep(healthStatusWaitTime)
ginkgo.By("Verify if health status of the pvc is changed to accessible")
pvc, err = client.CoreV1().PersistentVolumeClaims(pvclaim.Namespace).Get(ctx, pvc.Name, metav1.GetOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
gomega.Expect(pvc.Annotations[volumeHealthAnnotation]).Should(gomega.BeEquivalentTo(healthStatusAccessible))
defer func() {
err := fpv.DeletePersistentVolumeClaim(client, pvclaim.Name, namespace)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
pvclaim = nil
err = e2eVSphere.waitForCNSVolumeToBeDeleted(volHandle)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
}()
ginkgo.By(fmt.Sprintf("Invoking QueryCNSVolumeWithResult with VolumeID: %s", volHandle))
queryResult, err := e2eVSphere.queryCNSVolumeWithResult(volHandle)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
gomega.Expect(len(queryResult.Volumes) > 0)
ginkgo.By("Verifying the volume health status returned by CNS(green/yellow/red")
for _, vol := range queryResult.Volumes {
log.Infof("Volume health status: %s", vol.HealthStatus)
gomega.Expect(vol.HealthStatus).Should(gomega.BeEquivalentTo(healthGreen))
}
})
/*
Verify health annotation is added on the volume created by statefulset
steps
1. Create a storage class.
2. Create nginx service.
3. Create nginx statefulset
4. Wait until all Pods are ready and PVCs are bounded with PV.
5. Verify health annotation added on the PVC is accessible
6. Delete the pod(make the replicas to 0)
7. Delete PVC from the tests namespace
8. Delete the storage class.
*/
ginkgo.It("[csi-supervisor] Verify Volume health on Statefulset", func() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
ginkgo.By("Creating StorageClass for Statefulset")
// decide which test setup is available to run
if supervisorCluster {
ginkgo.By("CNS_TEST: Running for WCP setup")
profileID := e2eVSphere.GetSpbmPolicyID(storagePolicyName)
scParameters[scParamStoragePolicyID] = profileID
// create resource quota
createResourceQuota(client, namespace, rqLimit, storageclassname)
}
scSpec := getVSphereStorageClassSpec(storageclassname, scParameters, nil, "", "", false)
sc, err := client.StorageV1().StorageClasses().Create(ctx, scSpec, metav1.CreateOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
defer func() {
err := client.StorageV1().StorageClasses().Delete(ctx, sc.Name, *metav1.NewDeleteOptions(0))
gomega.Expect(err).NotTo(gomega.HaveOccurred())
}()
ginkgo.By("Creating service")
service := CreateService(namespace, client)
defer func() {
deleteService(namespace, client, service)
}()
statefulset := GetStatefulSetFromManifest(namespace)
ginkgo.By("Creating statefulset")
CreateStatefulSet(namespace, statefulset, client)
replicas := *(statefulset.Spec.Replicas)
// Waiting for pods status to be Ready
fss.WaitForStatusReadyReplicas(client, statefulset, replicas)
gomega.Expect(fss.CheckMount(client, statefulset, mountPath)).NotTo(gomega.HaveOccurred())
ssPodsBeforeScaleDown := fss.GetPodList(client, statefulset)
gomega.Expect(ssPodsBeforeScaleDown.Items).NotTo(gomega.BeEmpty(), fmt.Sprintf("Unable to get list of Pods from the Statefulset: %v", statefulset.Name))
gomega.Expect(len(ssPodsBeforeScaleDown.Items) == int(replicas)).To(gomega.BeTrue(), "Number of Pods in the statefulset should match with number of replicas")
// Verify the health status is accessible on the volume created
ginkgo.By(fmt.Sprintf("Sleeping for %v minutes to allow volume health check to be triggered", healthStatusWaitTime))
time.Sleep(healthStatusWaitTime)
// Get the list of Volumes attached to Pods before scale dow
for _, sspod := range ssPodsBeforeScaleDown.Items {
// _, err := client.CoreV1().Pods(namespace).Get(ctx, sspod.Name, metav1.GetOptions{})
// gomega.Expect(err).NotTo(gomega.HaveOccurred())
for _, volumespec := range sspod.Spec.Volumes {
if volumespec.PersistentVolumeClaim != nil {
pv := getPvFromClaim(client, statefulset.Namespace, volumespec.PersistentVolumeClaim.ClaimName)
// Verify the attached volume match the one in CNS cache
err := verifyVolumeMetadataInCNS(&e2eVSphere, pv.Spec.CSI.VolumeHandle, volumespec.PersistentVolumeClaim.ClaimName, pv.ObjectMeta.Name, sspod.Name)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
ginkgo.By("Expect health status of the pvc to be accessible")
pvc, err := client.CoreV1().PersistentVolumeClaims(namespace).Get(ctx, volumespec.PersistentVolumeClaim.ClaimName, metav1.GetOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
gomega.Expect(pvc.Annotations[volumeHealthAnnotation]).Should(gomega.BeEquivalentTo(healthStatusAccessible))
}
}
}
defer func() {
ginkgo.By(fmt.Sprintf("Deleting all statefulsets in namespace: %v", namespace))
fss.DeleteAllStatefulSets(client, namespace)
}()
})
/*
Verify health annotaiton is not added on the PV
Steps
1. Create a Storage Class
2. Create a PVC using above SC
3. Wait for PVC to be in Bound phase
4. Verify health annotation is not added on the PV
5. Delete PVC
6. Verify PV entry is deleted from CNS
7. Delete the SC
*/
ginkgo.It("[csi-supervisor] Verify health annotaiton is not added on the PV ", func() {
var storageclass *storagev1.StorageClass
var pvclaim *v1.PersistentVolumeClaim
var err error
var pvclaims []*v1.PersistentVolumeClaim
ctx, cancel := context.WithCancel(context.Background())
log := logger.GetLogger(ctx)
defer cancel()
ginkgo.By("Invoking Test for validating health status")
// decide which test setup is available to run
if supervisorCluster {
ginkgo.By("CNS_TEST: Running for WCP setup")
profileID := e2eVSphere.GetSpbmPolicyID(storagePolicyName)
scParameters[scParamStoragePolicyID] = profileID
// create resource quota
createResourceQuota(client, namespace, rqLimit, storagePolicyName)
storageclass, pvclaim, err = createPVCAndStorageClass(client, namespace, nil, scParameters, diskSize, nil, "", false, "", storagePolicyName)
}
gomega.Expect(err).NotTo(gomega.HaveOccurred())
defer func() {
err := client.StorageV1().StorageClasses().Delete(ctx, storageclass.Name, *metav1.NewDeleteOptions(0))
gomega.Expect(err).NotTo(gomega.HaveOccurred())
}()
ginkgo.By("Expect volume to be provisioned successfully")
err = fpv.WaitForPersistentVolumeClaimPhase(v1.ClaimBound, client, pvclaim.Namespace, pvclaim.Name, framework.Poll, framework.ClaimProvisionTimeout)
gomega.Expect(err).NotTo(gomega.HaveOccurred(), "Failed to provision volume")
pvclaims = append(pvclaims, pvclaim)
persistentvolumes, err := fpv.WaitForPVClaimBoundPhase(client, pvclaims, framework.ClaimProvisionTimeout)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
volHandle := persistentvolumes[0].Spec.CSI.VolumeHandle
ginkgo.By("Verify health annotation is not added on PV")
ginkgo.By(fmt.Sprintf("Sleeping for %v minutes to allow volume health check to be triggered", healthStatusWaitTime))
time.Sleep(healthStatusWaitTime)
pv, err := client.CoreV1().PersistentVolumes().Get(ctx, persistentvolumes[0].Name, metav1.GetOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
for describe := range pv.Annotations {
gomega.Expect(describe).ShouldNot(gomega.BeEquivalentTo(volumeHealthAnnotation))
}
defer func() {
err := fpv.DeletePersistentVolumeClaim(client, pvclaim.Name, namespace)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
pvclaim = nil
err = e2eVSphere.waitForCNSVolumeToBeDeleted(volHandle)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
}()
ginkgo.By(fmt.Sprintf("Invoking QueryCNSVolumeWithResult with VolumeID: %s", volHandle))
queryResult, err := e2eVSphere.queryCNSVolumeWithResult(volHandle)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
gomega.Expect(len(queryResult.Volumes) > 0)
ginkgo.By("Verifying the volume health status returned by CNS(green/yellow/red")
for _, vol := range queryResult.Volumes {
log.Infof("Volume health status: %s", vol.HealthStatus)
gomega.Expect(vol.HealthStatus).Should(gomega.BeEquivalentTo(healthGreen))
}
})
/*
Verify removing the health annotation on the PVC
Steps
1. Create a Storage Class
2. Create a PVC using above SC
3. Wait for PVC to be in Bound phase
4. Verify annotation added on the PVC in accessible
5. Kubectl edit on the annotation of the PVC and remove the entire health annotation
6. Wait for the default time interval
7. Verify health annotation is added on the PVC is accessible
8. Delete PVC
9. Verify PV entry is deleted from CNS
10. Delete the SC
*/
ginkgo.It("[csi-supervisor] Verify removing the health annotation on the PVC", func() {
var storageclass *storagev1.StorageClass
var pvclaim *v1.PersistentVolumeClaim
var err error
var pvclaims []*v1.PersistentVolumeClaim
ctx, cancel := context.WithCancel(context.Background())
log := logger.GetLogger(ctx)
defer cancel()
ginkgo.By("Invoking Test for validating health status")
ginkgo.By("CNS_TEST: Running for WCP setup")
profileID := e2eVSphere.GetSpbmPolicyID(storagePolicyName)
scParameters[scParamStoragePolicyID] = profileID
// create resource quota
createResourceQuota(client, namespace, rqLimit, storagePolicyName)
storageclass, pvclaim, err = createPVCAndStorageClass(client, namespace, nil, scParameters, diskSize, nil, "", false, "", storagePolicyName)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
defer func() {
err := client.StorageV1().StorageClasses().Delete(ctx, storageclass.Name, *metav1.NewDeleteOptions(0))
gomega.Expect(err).NotTo(gomega.HaveOccurred())
}()
ginkgo.By("Expect volume to be provisioned successfully")
err = fpv.WaitForPersistentVolumeClaimPhase(v1.ClaimBound, client, pvclaim.Namespace, pvclaim.Name, framework.Poll, framework.ClaimProvisionTimeout)
gomega.Expect(err).NotTo(gomega.HaveOccurred(), "Failed to provision volume")
pvclaims = append(pvclaims, pvclaim)
persistentvolumes, err := fpv.WaitForPVClaimBoundPhase(client, pvclaims, framework.ClaimProvisionTimeout)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
volHandle := persistentvolumes[0].Spec.CSI.VolumeHandle
gomega.Expect(volHandle).NotTo(gomega.BeEmpty())
ginkgo.By(fmt.Sprintf("Sleeping for %v minutes to allow volume health check to be triggered", healthStatusWaitTime))
time.Sleep(healthStatusWaitTime)
ginkgo.By("Expect health status of the pvc to be accessible")
pvc, err := client.CoreV1().PersistentVolumeClaims(pvclaim.Namespace).Get(ctx, pvclaim.Name, metav1.GetOptions{})
gomega.Expect(pvc.Annotations[volumeHealthAnnotation]).Should(gomega.BeEquivalentTo(healthStatusAccessible))
gomega.Expect(err).NotTo(gomega.HaveOccurred())
ginkgo.By("Removing health status from the pvc")
setAnnotation := make(map[string]string)
checkVolumeHealthAnnotation := "test-key"
setAnnotation[checkVolumeHealthAnnotation] = " "
pvc.Annotations = setAnnotation
_, err = client.CoreV1().PersistentVolumeClaims(pvc.Namespace).Update(ctx, pvc, metav1.UpdateOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
pvc, err = client.CoreV1().PersistentVolumeClaims(pvclaim.Namespace).Get(ctx, pvclaim.Name, metav1.GetOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
for describe := range pvc.Annotations {
gomega.Expect(describe).ShouldNot(gomega.BeEquivalentTo(volumeHealthAnnotation))
}
ginkgo.By(fmt.Sprintf("Sleeping for %v minutes to allow volume health check to be triggered", healthStatusWaitTime))
time.Sleep(healthStatusWaitTime)
ginkgo.By("Expect health status of the pvc to be accessible")
pvc, err = client.CoreV1().PersistentVolumeClaims(pvclaim.Namespace).Get(ctx, pvc.Name, metav1.GetOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
gomega.Expect(pvc.Annotations[volumeHealthAnnotation]).Should(gomega.BeEquivalentTo(healthStatusAccessible))
defer func() {
err := fpv.DeletePersistentVolumeClaim(client, pvclaim.Name, namespace)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
pvclaim = nil
err = e2eVSphere.waitForCNSVolumeToBeDeleted(volHandle)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
}()
ginkgo.By(fmt.Sprintf("Invoking QueryCNSVolumeWithResult with VolumeID: %s", volHandle))
queryResult, err := e2eVSphere.queryCNSVolumeWithResult(volHandle)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
gomega.Expect(len(queryResult.Volumes) > 0)
ginkgo.By("Verifying the volume health status returned by CNS(green/yellow/red")
for _, vol := range queryResult.Volumes {
log.Infof("Volume health status: %s", vol.HealthStatus)
gomega.Expect(vol.HealthStatus).Should(gomega.BeEquivalentTo(healthGreen))
}
})
/*
Verify health annotation is added on the volume created by statefulset
1. Create a storage class.
2. Create nginx service.
3. Create nginx statefulset
4. Wait until all Pods are ready and PVCs are bounded with PV.
5. Verify health annotation added on the PVC is accessible
6. Delete the pod
7. Delete PVC from the tests namespace
8. Delete the storage class.
*/
ginkgo.It("[csi-guest] In Guest Cluster Verify Volume health on Statefulset", func() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
ginkgo.By("Creating StorageClass for Statefulset")
scParameters[svStorageClassName] = storagePolicyName
sc, err := createStorageClass(client, scParameters, nil, "", "", false, "nginx-sc")
gomega.Expect(err).NotTo(gomega.HaveOccurred())
defer func() {
err := client.StorageV1().StorageClasses().Delete(ctx, sc.Name, *metav1.NewDeleteOptions(0))
gomega.Expect(err).NotTo(gomega.HaveOccurred())
}()
ginkgo.By("Creating service")
service := CreateService(namespace, client)
defer func() {
deleteService(namespace, client, service)
}()
statefulset := GetStatefulSetFromManifest(namespace)
ginkgo.By("Create a statefulset with 3 replicas")
CreateStatefulSet(namespace, statefulset, client)
replicas := *(statefulset.Spec.Replicas)
// Waiting for pods status to be Ready
ginkgo.By("Wait for all Pods are Running state")
fss.WaitForStatusReadyReplicas(client, statefulset, replicas)
gomega.Expect(fss.CheckMount(client, statefulset, mountPath)).NotTo(gomega.HaveOccurred())
ssPodsBeforeScaleDown := fss.GetPodList(client, statefulset)
gomega.Expect(ssPodsBeforeScaleDown.Items).NotTo(gomega.BeEmpty(), fmt.Sprintf("Unable to get list of Pods from the Statefulset: %v", statefulset.Name))
gomega.Expect(len(ssPodsBeforeScaleDown.Items) == int(replicas)).To(gomega.BeTrue(), "Number of Pods in the statefulset should match with number of replicas")
ginkgo.By(fmt.Sprintf("Sleeping for %v minutes to allow volume health check to be triggered", healthStatusWaitTime))
time.Sleep(healthStatusWaitTime)
// Get the list of Volumes attached to Pods before scale down
for _, sspod := range ssPodsBeforeScaleDown.Items {
_, err := client.CoreV1().Pods(namespace).Get(ctx, sspod.Name, metav1.GetOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
for _, volumespec := range sspod.Spec.Volumes {
if volumespec.PersistentVolumeClaim != nil {
pv := getPvFromClaim(client, statefulset.Namespace, volumespec.PersistentVolumeClaim.ClaimName)
ginkgo.By("Verify CnsNodeVmAttachment CRD is created")
volumeID := pv.Spec.CSI.VolumeHandle
// svcPVCName refers to PVC Name in the supervisor cluster
svcPVCName := volumeID
volumeID = getVolumeIDFromSupervisorCluster(svcPVCName)
gomega.Expect(volumeID).NotTo(gomega.BeEmpty())
verifyCRDInSupervisor(ctx, f, sspod.Spec.NodeName+"-"+svcPVCName, crdCNSNodeVMAttachment, crdVersion, crdGroup, true)
ginkgo.By(fmt.Sprintf("Verify volume: %s is attached to the node: %s", pv.Spec.CSI.VolumeHandle, sspod.Spec.NodeName))
var vmUUID string
vmUUID, err = getVMUUIDFromNodeName(sspod.Spec.NodeName)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
isDiskAttached, err := e2eVSphere.isVolumeAttachedToVM(client, volumeID, vmUUID)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
gomega.Expect(isDiskAttached).To(gomega.BeTrue(), fmt.Sprintf("Volume is not attached to the node, %s", vmUUID))
// Verify the health status is accessible on the volume created
ginkgo.By("Expect health status of the pvc to be accessible")
pvc, err := client.CoreV1().PersistentVolumeClaims(namespace).Get(ctx, volumespec.PersistentVolumeClaim.ClaimName, metav1.GetOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
gomega.Expect(pvc.Annotations[volumeHealthAnnotation]).Should(gomega.BeEquivalentTo(healthStatusAccessible))
}
}
}
defer func() {
ginkgo.By(fmt.Sprintf("Deleting all statefulsets in namespace: %v", namespace))
fss.DeleteAllStatefulSets(client, namespace)
}()
})
/*
Verify Volume health when GC CSI is down
1. Create a Storage Class
2. Create a GC PVC using above SC
3. Wait for PVC to be in Bound phase
4. Verify annotation in the GC PVC is accessible
5. Bring GC CSI controller down
6. Verify SV PVC and GC PVC have same health annotation
7. Bring GC CSI controller up
8. Verify the existing annotation in the GC PVC is not affected(remains accessible)
9. Verify SV PVC and GC PVC have same health annotation
10. Delete GC PVC
11. Verify PV entry is deleted from CNS
12. Delete the SC
*/
ginkgo.It("[csi-guest] Verify Volume health when GC CSI is down", func() {
var sc *storagev1.StorageClass
var pvc *v1.PersistentVolumeClaim
var err error
var isControllerUP = true
ctx, cancel := context.WithCancel(context.Background())
log := logger.GetLogger(ctx)
defer cancel()
ginkgo.By("Creating Storage Class and PVC")
scParameters[svStorageClassName] = storagePolicyName
sc, pvc, err = createPVCAndStorageClass(client, namespace, nil, scParameters, "", nil, "", false, "")
gomega.Expect(err).NotTo(gomega.HaveOccurred())
defer func() {
err := client.StorageV1().StorageClasses().Delete(ctx, sc.Name, *metav1.NewDeleteOptions(0))
gomega.Expect(err).NotTo(gomega.HaveOccurred())
}()
ginkgo.By(fmt.Sprintf("Waiting for claim %s to be in bound phase", pvc.Name))
pvs, err := fpv.WaitForPVClaimBoundPhase(client, []*v1.PersistentVolumeClaim{pvc}, framework.ClaimProvisionTimeout)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
gomega.Expect(pvs).NotTo(gomega.BeEmpty())
pv := pvs[0]
volumeID := pv.Spec.CSI.VolumeHandle
//svPVCName refers to PVC Name in the supervisor cluster
svPVCName := volumeID
volumeID = getVolumeIDFromSupervisorCluster(svPVCName)
gomega.Expect(volumeID).NotTo(gomega.BeEmpty())
defer func() {
err := fpv.DeletePersistentVolumeClaim(client, pvc.Name, namespace)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
pvclaim = nil
err = e2eVSphere.waitForCNSVolumeToBeDeleted(pv.Spec.CSI.VolumeHandle)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
}()
ginkgo.By(fmt.Sprintf("Sleeping for %v minutes to allow volume health check to be triggered", healthStatusWaitTime))
time.Sleep(healthStatusWaitTime)
ginkgo.By("Expect health status of the pvc to be accessible")
pvclaim, err := client.CoreV1().PersistentVolumeClaims(pvc.Namespace).Get(ctx, pvc.Name, metav1.GetOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
gomega.Expect(pvclaim.Annotations[volumeHealthAnnotation]).Should(gomega.BeEquivalentTo(healthStatusAccessible))
var gcClient clientset.Interface
if k8senv := GetAndExpectStringEnvVar("KUBECONFIG"); k8senv != "" {
gcClient, err = k8s.CreateKubernetesClientFromConfig(k8senv)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
}
ginkgo.By("Get svcClient and svNamespace")
svClient, _ := getSvcClientAndNamespace()
ginkgo.By("Bring down csi-controller pod in GC")
bringDownTKGController(svClient)
bringDownCsiController(gcClient)
isControllerUP = false
defer func() {
if !isControllerUP {
bringUpTKGController(svClient)
bringUpCsiController(gcClient)
}
}()
ginkgo.By(fmt.Sprintf("Sleeping for %v minutes to allow volume health check to be triggered", healthStatusWaitTime))
time.Sleep(healthStatusWaitTime)
ginkgo.By("Expect health status of the pvc to be accessible")
pvclaim, err = client.CoreV1().PersistentVolumeClaims(pvc.Namespace).Get(ctx, pvc.Name, metav1.GetOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
gomega.Expect(pvclaim.Annotations[volumeHealthAnnotation]).Should(gomega.BeEquivalentTo(healthStatusAccessible))
ginkgo.By("Expect health annotation is added on the SV pvc")
svPVC := getPVCFromSupervisorCluster(svPVCName)
gomega.Expect(svPVC.Annotations[volumeHealthAnnotation]).Should(gomega.BeEquivalentTo(healthStatusAccessible))
ginkgo.By("Bring up csi-controller pod in GC")
bringUpTKGController(svClient)
bringUpCsiController(gcClient)
isControllerUP = true
ginkgo.By("Verify health status of GC PVC after GC csi is up")
ginkgo.By(fmt.Sprintf("Sleeping for %v minutes to allow volume health check to be triggered", healthStatusWaitTime))
time.Sleep(healthStatusWaitTime)
pvclaim, err = client.CoreV1().PersistentVolumeClaims(pvc.Namespace).Get(ctx, pvc.Name, metav1.GetOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
gomega.Expect(pvclaim.Annotations[volumeHealthAnnotation]).Should(gomega.BeEquivalentTo(healthStatusAccessible))
ginkgo.By("Expect health annotation is added on the SV pvc")
svPVC = getPVCFromSupervisorCluster(svPVCName)
gomega.Expect(svPVC.Annotations[volumeHealthAnnotation]).Should(gomega.BeEquivalentTo(healthStatusAccessible))
ginkgo.By(fmt.Sprintf("Invoking QueryCNSVolumeWithResult with VolumeID: %s", volumeID))
queryResult, err := e2eVSphere.queryCNSVolumeWithResult(volumeID)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
gomega.Expect(len(queryResult.Volumes) > 0)
ginkgo.By("Verifying the volume health status returned by CNS(green/yellow/red")
for _, vol := range queryResult.Volumes {
log.Infof("Volume health status: %s", vol.HealthStatus)
gomega.Expect(vol.HealthStatus).Should(gomega.BeEquivalentTo(healthGreen))
}
})
/*
Verify Volume health after password rotation
1. Create StorageClass and PVC
2. Wait for PVC to be Bound
3. verify health annotation on PVC
4. Modify the password rotation time in storage user file to 0.
5. verify health annotation on PVC
6. Delete PVC
7. Delete Storage class
*/
ginkgo.It("[csi-supervisor] [csi-guest] Verify Volume health after password rotation", func() {
var sc *storagev1.StorageClass
var pvc *v1.PersistentVolumeClaim
var err error
ctx, cancel := context.WithCancel(context.Background())
log := logger.GetLogger(ctx)
defer cancel()
if supervisorCluster {
ginkgo.By("CNS_TEST: Running for WCP setup")
profileID := e2eVSphere.GetSpbmPolicyID(storagePolicyName)
scParameters[scParamStoragePolicyID] = profileID
// create resource quota
createResourceQuota(client, namespace, rqLimit, storagePolicyName)
sc, pvc, err = createPVCAndStorageClass(client, namespace, nil, scParameters, diskSize, nil, "", false, "", storagePolicyName)
} else if guestCluster {
ginkgo.By("CNS_TEST: Running for GC setup")
scParameters[svStorageClassName] = storagePolicyName
sc, pvc, err = createPVCAndStorageClass(client, namespace, nil, scParameters, diskSize, nil, "", false, "")
}
gomega.Expect(err).NotTo(gomega.HaveOccurred())
defer func() {
err := client.StorageV1().StorageClasses().Delete(ctx, sc.Name, *metav1.NewDeleteOptions(0))
gomega.Expect(err).NotTo(gomega.HaveOccurred())
}()
ginkgo.By(fmt.Sprintf("Waiting for claim %s to be in bound phase", pvc.Name))
pvs, err := fpv.WaitForPVClaimBoundPhase(client, []*v1.PersistentVolumeClaim{pvc}, framework.ClaimProvisionTimeout)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
gomega.Expect(pvs).NotTo(gomega.BeEmpty())
pv := pvs[0]
volumeID := pv.Spec.CSI.VolumeHandle
svPVCName := volumeID
if guestCluster {
// svcPVCName refers to PVC Name in the supervisor cluster
svPVCName := volumeID
volumeID = getVolumeIDFromSupervisorCluster(svPVCName)
}
gomega.Expect(volumeID).NotTo(gomega.BeEmpty())
defer func() {
err := fpv.DeletePersistentVolumeClaim(client, pvc.Name, namespace)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
pvc = nil
err = e2eVSphere.waitForCNSVolumeToBeDeleted(pv.Spec.CSI.VolumeHandle)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
}()
ginkgo.By(fmt.Sprintf("Sleeping for %v minutes to allow volume health check to be triggered", healthStatusWaitTime))
time.Sleep(healthStatusWaitTime)
ginkgo.By("Expect health status of the pvc to be accessible")
pvclaim, err := client.CoreV1().PersistentVolumeClaims(pvc.Namespace).Get(ctx, pvc.Name, metav1.GetOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
gomega.Expect(pvclaim.Annotations[volumeHealthAnnotation]).Should(gomega.BeEquivalentTo(healthStatusAccessible))
if guestCluster {
//verifying svc pvc health status
ginkgo.By("Expect health annotation is added on the SV pvc")
svPVC := getPVCFromSupervisorCluster(svPVCName)
gomega.Expect(svPVC.Annotations[volumeHealthAnnotation]).Should(gomega.BeEquivalentTo(healthStatusAccessible))
}
ginkgo.By("Invoking password rotation")
vcAddress := e2eVSphere.Config.Global.VCenterHostname + ":" + sshdPort
err = replacePasswordRotationTime(passorwdFilePath, vcAddress)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
ginkgo.By("Verify health annotation on the PVC after password rotation")
ginkgo.By(fmt.Sprintf("Sleeping for %v minutes to allow volume health check to be triggered", healthStatusWaitTime))
time.Sleep(healthStatusWaitTime)
pvclaim, err = client.CoreV1().PersistentVolumeClaims(pvc.Namespace).Get(ctx, pvc.Name, metav1.GetOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
gomega.Expect(pvclaim.Annotations[volumeHealthAnnotation]).Should(gomega.BeEquivalentTo(healthStatusAccessible))
if guestCluster {
//verifying svc pvc health status
ginkgo.By("Expect health annotation is added on the SV pvc")
svPVC := getPVCFromSupervisorCluster(svPVCName)
gomega.Expect(svPVC.Annotations[volumeHealthAnnotation]).Should(gomega.BeEquivalentTo(healthStatusAccessible))
}
ginkgo.By(fmt.Sprintf("Invoking QueryCNSVolumeWithResult with VolumeID: %s", volumeID))
queryResult, err := e2eVSphere.queryCNSVolumeWithResult(volumeID)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
gomega.Expect(len(queryResult.Volumes) > 0)
ginkgo.By("Verifying the volume health status returned by CNS(green/yellow/red")
for _, vol := range queryResult.Volumes {
log.Infof("Volume health status: %s", vol.HealthStatus)
gomega.Expect(vol.HealthStatus).Should(gomega.BeEquivalentTo(healthGreen))
}
})
/*
Verify Volume health when SV CSI is down
Create a Storage Class
Create a PVC using above SC
Wait for PVC to be in Bound phase
Verify health annotation which is added on the PVC is accessible
Bring CSI controller down
Bring down link between all the hosts and datastore
Existing PVC annotation should remain same
Bring CSI controller up
Verify health annotation which is added on the PVC is inaccessible
Restore link between all the hosts and datastore
Verify health annotation which is added on the PVC is accessible
Delete PVC
Verify PV entry is deleted from CNS
Delete the SC
*/
ginkgo.It("[csi-supervisor] Verify Volume health when SVC CSI is down", func() {
var sc *storagev1.StorageClass
var err error
var isControllerUP = true
ctx, cancel := context.WithCancel(context.Background())
log := logger.GetLogger(ctx)
defer cancel()
raid0StoragePolicyName = os.Getenv("RAID_0_STORAGE_POLICY")
if raid0StoragePolicyName == "" {
ginkgo.Skip("Env RAID_0_STORAGE_POLICY is missing")
}
ginkgo.By("CNS_TEST: Running for WCP setup")
profileID := e2eVSphere.GetSpbmPolicyID(raid0StoragePolicyName)
scParameters[scParamStoragePolicyID] = profileID
// create resource quota
createResourceQuota(client, namespace, rqLimit, raid0StoragePolicyName)
sc, pvc, err = createPVCAndStorageClass(client, namespace, nil, scParameters, diskSize, nil, "", false, "", raid0StoragePolicyName)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
defer func() {
err := client.StorageV1().StorageClasses().Delete(ctx, sc.Name, *metav1.NewDeleteOptions(0))
gomega.Expect(err).NotTo(gomega.HaveOccurred())
}()
ginkgo.By(fmt.Sprintf("Waiting for claim %s to be in bound phase", pvc.Name))
pvs, err := fpv.WaitForPVClaimBoundPhase(client, []*v1.PersistentVolumeClaim{pvc}, framework.ClaimProvisionTimeout)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
gomega.Expect(pvs).NotTo(gomega.BeEmpty())
volHandle := pvs[0].Spec.CSI.VolumeHandle
gomega.Expect(volHandle).NotTo(gomega.BeEmpty())
pv := getPvFromClaim(client, namespace, pvc.Name)
framework.Logf("volume name %v", pv.Name)
ginkgo.By("poll for health status annotation")
err = pvcHealthAnnotationWatcher(ctx, client, pvc, healthStatusAccessible)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
ginkgo.By("Expect health status of the pvc to be accessible")
pvclaim, err := client.CoreV1().PersistentVolumeClaims(pvc.Namespace).Get(ctx, pvc.Name, metav1.GetOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
gomega.Expect(pvclaim.Annotations[volumeHealthAnnotation]).Should(gomega.BeEquivalentTo(healthStatusAccessible))
ginkgo.By("Get svcClient")
svClient, _ := getSvcClientAndNamespace()
ginkgo.By("Bring down csi-controller pod in SVC")
bringDownCsiController(svClient)
isControllerUP = false
defer func() {
if !isControllerUP {
bringUpCsiController(svClient)
}
}()
ginkgo.By("PSOD the host")
hostIP = psodHostWithPv(ctx, &e2eVSphere, pv.Name)
defer func() {
ginkgo.By("checking host status")
err := waitForHostToBeUp(hostIP)
time.Sleep(pollTimeoutShort)
if err != nil {
time.Sleep(hostRecoveryTime)
}
err = fpv.DeletePersistentVolumeClaim(client, pvc.Name, namespace)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
pvc = nil
err = e2eVSphere.waitForCNSVolumeToBeDeleted(volHandle)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
}()
ginkgo.By("poll for health status annotation")
err = pvcHealthAnnotationWatcher(ctx, client, pvc, healthStatusAccessible)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
ginkgo.By("Expect health status of the pvc to be accessible")
pvclaim, err = client.CoreV1().PersistentVolumeClaims(pvc.Namespace).Get(ctx, pvc.Name, metav1.GetOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
gomega.Expect(pvclaim.Annotations[volumeHealthAnnotation]).Should(gomega.BeEquivalentTo(healthStatusAccessible))
ginkgo.By("Bring up csi-controller pod in SVC")
bringUpCsiController(svClient)
isControllerUP = true
ginkgo.By("Verify health status of SVC PVC after csi is up(inaccessible)")
ginkgo.By("poll for health status annotation")
err = pvcHealthAnnotationWatcher(ctx, client, pvclaim, healthStatusInAccessible)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
pvclaim, err = client.CoreV1().PersistentVolumeClaims(pvc.Namespace).Get(ctx, pvc.Name, metav1.GetOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
gomega.Expect(pvclaim.Annotations[volumeHealthAnnotation]).Should(gomega.BeEquivalentTo(healthStatusInAccessible))
ginkgo.By("poll for health status annotation")
err = pvcHealthAnnotationWatcher(ctx, client, pvc, healthStatusAccessible)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
ginkgo.By("Verify health status of SVC PVC should be accessible")
pvclaim, err = client.CoreV1().PersistentVolumeClaims(pvc.Namespace).Get(ctx, pvc.Name, metav1.GetOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
gomega.Expect(pvclaim.Annotations[volumeHealthAnnotation]).Should(gomega.BeEquivalentTo(healthStatusAccessible))
ginkgo.By(fmt.Sprintf("Invoking QueryCNSVolumeWithResult with VolumeID: %s", volHandle))
queryResult, err := e2eVSphere.queryCNSVolumeWithResult(volHandle)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
gomega.Expect(len(queryResult.Volumes) > 0)
ginkgo.By("Verifying the volume health status returned by CNS(green/yellow/red")
for _, vol := range queryResult.Volumes {
log.Infof("Volume health status: %s", vol.HealthStatus)
gomega.Expect(vol.HealthStatus).Should(gomega.BeEquivalentTo(healthGreen))
}
})
/*
Verify health annotation added on the pvc is changed from accessible to inaccessible
Steps
1. Create a Storage Class
2. Create a PVC using above SC
3. Wait for PVC to be in Bound phase
4. Verify health annotation is added on the PVC is accessible
5. Bring down link between all the hosts and datastore. (Health status should return in-accessible status)
6. Verify health annotation on the PVC is updated to in-accessible
7. Restore link between all the hosts and datastore
8. Verify health annotation on the PVC is updated to accessible
9. Delete PVC
10.Verify PV entry is deleted from CNS
11.Delete the SC
*/
ginkgo.It("[csi-supervisor] [csi-guest] Verify health annotation added on the pvc is changed from accessible to inaccessible", func() {
var storageclass *storagev1.StorageClass
var err error
var pvclaims []*v1.PersistentVolumeClaim
var pv *v1.PersistentVolume
ctx, cancel := context.WithCancel(context.Background())
log := logger.GetLogger(ctx)
defer cancel()
raid0StoragePolicyName = os.Getenv("RAID_0_STORAGE_POLICY")
if raid0StoragePolicyName == "" {
ginkgo.Skip("Env RAID_0_STORAGE_POLICY is missing")
}
ginkgo.By("Invoking Test for validating health status")
// decide which test setup is available to run
if supervisorCluster {
ginkgo.By("CNS_TEST: Running for WCP setup")
profileID := e2eVSphere.GetSpbmPolicyID(raid0StoragePolicyName)
scParameters[scParamStoragePolicyID] = profileID
// create resource quota
createResourceQuota(client, namespace, rqLimit, raid0StoragePolicyName)
storageclass, pvclaim, err = createPVCAndStorageClass(client, namespace, nil, scParameters, diskSize, nil, "", false, "", raid0StoragePolicyName)
} else if guestCluster {
ginkgo.By("CNS_TEST: Running for GC setup")
scParameters[svStorageClassName] = raid0StoragePolicyName
storageclass, pvclaim, err = createPVCAndStorageClass(client, namespace, nil, scParameters, diskSize, nil, "", false, "")
}
gomega.Expect(err).NotTo(gomega.HaveOccurred())
defer func() {
err := client.StorageV1().StorageClasses().Delete(ctx, storageclass.Name, *metav1.NewDeleteOptions(0))
gomega.Expect(err).NotTo(gomega.HaveOccurred())
}()
ginkgo.By("Expect claim to provision volume successfully")
pvclaims = append(pvclaims, pvclaim)
persistentvolumes, err := fpv.WaitForPVClaimBoundPhase(client, pvclaims, framework.ClaimProvisionTimeout)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
volHandle := persistentvolumes[0].Spec.CSI.VolumeHandle
svPVCName := volHandle
if supervisorCluster {
pv := getPvFromClaim(client, namespace, pvclaim.Name)
framework.Logf("volume name %v", pv.Name)
}
if guestCluster {
// svcPVCName refers to PVC Name in the supervisor cluster
svcPVCName := volHandle
volHandle = getVolumeIDFromSupervisorCluster(svcPVCName)
ginkgo.By("Get svcClient and svNamespace")
svcClient, svNamespace := getSvcClientAndNamespace()
pv = getPvFromClaim(svcClient, svNamespace, svPVCName)
framework.Logf("volume name %v", pv.Name)
}
gomega.Expect(volHandle).NotTo(gomega.BeEmpty())
ginkgo.By("poll for health status annotation")
err = pvcHealthAnnotationWatcher(ctx, client, pvclaim, healthStatusAccessible)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
ginkgo.By("Expect health status of the pvc to be accessible")
pvc, err := client.CoreV1().PersistentVolumeClaims(pvclaim.Namespace).Get(ctx, pvclaim.Name, metav1.GetOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
gomega.Expect(pvc.Annotations[volumeHealthAnnotation]).Should(gomega.BeEquivalentTo(healthStatusAccessible))
if guestCluster {
//verifying svc pvc health status also to be inaccessible
ginkgo.By("Expect health annotation is added on the SV pvc")
svPVC := getPVCFromSupervisorCluster(svPVCName)
gomega.Expect(svPVC.Annotations[volumeHealthAnnotation]).Should(gomega.BeEquivalentTo(healthStatusAccessible))
}
//PSOD the host
ginkgo.By("PSOD the host")
hostIP = psodHostWithPv(ctx, &e2eVSphere, pv.Name)
defer func() {
ginkgo.By("checking host status")
err := waitForHostToBeUp(hostIP)
time.Sleep(pollTimeoutShort)
if err != nil {
time.Sleep(hostRecoveryTime)
}
err = fpv.DeletePersistentVolumeClaim(client, pvclaim.Name, namespace)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
pvclaim = nil
err = e2eVSphere.waitForCNSVolumeToBeDeleted(volHandle)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
}()
ginkgo.By("poll for health status annotation")
err = pvcHealthAnnotationWatcher(ctx, client, pvclaim, healthStatusInAccessible)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
if guestCluster {
//verifying svc pvc health status also to be inaccessible
ginkgo.By("Expect health annotation is added on the SV pvc")
svPVC := getPVCFromSupervisorCluster(svPVCName)
gomega.Expect(svPVC.Annotations[volumeHealthAnnotation]).Should(gomega.BeEquivalentTo(healthStatusInAccessible))
}
ginkgo.By("Expect health status of the pvc to be inaccessible")
pvc, err = client.CoreV1().PersistentVolumeClaims(pvclaim.Namespace).Get(ctx, pvclaim.Name, metav1.GetOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
gomega.Expect(pvc.Annotations[volumeHealthAnnotation]).Should(gomega.BeEquivalentTo(healthStatusInAccessible))
//CNS should return the health status as red when its inaccessible
ginkgo.By(fmt.Sprintf("Invoking QueryCNSVolumeWithResult with VolumeID: %s", volHandle))
queryResult, err := e2eVSphere.queryCNSVolumeWithResult(volHandle)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
gomega.Expect(len(queryResult.Volumes) > 0)
//It checks the colour code returned by cns for pv
ginkgo.By("Verifying the volume health status returned by CNS(green/yellow/red)")
for _, vol := range queryResult.Volumes {
log.Infof("Volume health status: %s", vol.HealthStatus)
gomega.Expect(vol.HealthStatus).Should(gomega.BeEquivalentTo(healthRed))
}
ginkgo.By("poll for health status annotation")
err = pvcHealthAnnotationWatcher(ctx, client, pvclaim, healthStatusAccessible)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
if guestCluster {
ginkgo.By("poll for health status annotation")
err = pvcHealthAnnotationWatcher(ctx, client, pvclaim, healthStatusAccessible)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
//verifying svc pvc health status
ginkgo.By("Expect health annotation is added on the SV pvc")
svPVC := getPVCFromSupervisorCluster(svPVCName)
gomega.Expect(svPVC.Annotations[volumeHealthAnnotation]).Should(gomega.BeEquivalentTo(healthStatusAccessible))
}
ginkgo.By("Expect health status of the pvc to be accessible")
pvc, err = client.CoreV1().PersistentVolumeClaims(pvclaim.Namespace).Get(ctx, pvclaim.Name, metav1.GetOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
gomega.Expect(pvc.Annotations[volumeHealthAnnotation]).Should(gomega.BeEquivalentTo(healthStatusAccessible))
ginkgo.By(fmt.Sprintf("Invoking QueryCNSVolumeWithResult with VolumeID: %s", volHandle))
queryResult, err = e2eVSphere.queryCNSVolumeWithResult(volHandle)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
gomega.Expect(len(queryResult.Volumes)).NotTo(gomega.BeZero())
ginkgo.By("Verifying the volume health status returned by CNS(green/yellow/red")
for _, vol := range queryResult.Volumes {
log.Infof("Volume health status: %s", vol.HealthStatus)
gomega.Expect(vol.HealthStatus).Should(gomega.BeEquivalentTo(healthGreen))
}
})
/*
Verify health status of pvc after bringing SV API server down
Steps
1. Create a Storage Class
2. Create a PVC using above SC
3. Wait for PVC to be in Bound phase
4. Verify that the volume health is accessible.
5. Bring down the SV API server completely.
6. Bring down link between the host and the datastore to make volume health inaccessible.
7. CNS should return the health status when API server is down (health status should be inaccessible).
8. Bring up SV API server.
9. validate that volume health on PVC changes from inaccessible to accessible after default time interval.
*/
ginkgo.It("[csi-supervisor] Verify health status of pvc after bringing SV API server down", func() {
var storageclass *storagev1.StorageClass
var err error
var pvclaims []*v1.PersistentVolumeClaim
var isSvcUp bool
ctx, cancel := context.WithCancel(context.Background())
log := logger.GetLogger(ctx)
defer cancel()
raid0StoragePolicyName = os.Getenv("RAID_0_STORAGE_POLICY")
if raid0StoragePolicyName == "" {
ginkgo.Skip("Env RAID_0_STORAGE_POLICY is missing")
}
ginkgo.By("Invoking Test for validating health status")
ginkgo.By("CNS_TEST: Running for WCP setup")
profileID := e2eVSphere.GetSpbmPolicyID(raid0StoragePolicyName)
scParameters[scParamStoragePolicyID] = profileID
// create resource quota
createResourceQuota(client, namespace, rqLimit, raid0StoragePolicyName)
storageclass, pvclaim, err = createPVCAndStorageClass(client, namespace, nil, scParameters, diskSize, nil, "", false, "", raid0StoragePolicyName)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
defer func() {
err := client.StorageV1().StorageClasses().Delete(ctx, storageclass.Name, *metav1.NewDeleteOptions(0))
gomega.Expect(err).NotTo(gomega.HaveOccurred())
}()
ginkgo.By("Expect claim to provision volume successfully")
pvclaims = append(pvclaims, pvclaim)
persistentvolumes, err := fpv.WaitForPVClaimBoundPhase(client, pvclaims, framework.ClaimProvisionTimeout)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
volHandle := persistentvolumes[0].Spec.CSI.VolumeHandle
gomega.Expect(volHandle).NotTo(gomega.BeEmpty())
pv := getPvFromClaim(client, namespace, pvclaim.Name)
framework.Logf("volume name %v", pv.Name)
ginkgo.By("poll for health status annotation")
err = pvcHealthAnnotationWatcher(ctx, client, pvclaim, healthStatusAccessible)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
ginkgo.By("Expect health status of the pvc to be accessible")
pvc, err := client.CoreV1().PersistentVolumeClaims(pvclaim.Namespace).Get(ctx, pvclaim.Name, metav1.GetOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
gomega.Expect(pvc.Annotations[volumeHealthAnnotation]).Should(gomega.BeEquivalentTo(healthStatusAccessible))
defer func() {
ginkgo.By("checking host status")
err := waitForHostToBeUp(hostIP)
time.Sleep(pollTimeoutShort)
if err != nil {
time.Sleep(hostRecoveryTime)
}
err = fpv.DeletePersistentVolumeClaim(client, pvclaim.Name, namespace)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
pvclaim = nil
err = e2eVSphere.waitForCNSVolumeToBeDeleted(volHandle)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
}()
ginkgo.By("Bringing SV API server down")
vcAddress := e2eVSphere.Config.Global.VCenterHostname + ":" + sshdPort
log.Infof("VC ip address: %v", vcAddress)
err = bringSvcK8sAPIServerDown(vcAddress)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
isSvcUp = false
defer func() {
if !isSvcUp {
ginkgo.By("Bringing SV API server UP")
err = bringSvcK8sAPIServerUp(ctx, client, pvclaim, vcAddress, healthStatusAccessible)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
}
}()
//PSOD the host
ginkgo.By("PSOD the host")
hostIP = psodHostWithPv(ctx, &e2eVSphere, pv.Name)
ginkgo.By("Query CNS volume health status")
err = queryCNSVolumeWithWait(ctx, client, volHandle)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
ginkgo.By("Bringing SV API server UP")
err = bringSvcK8sAPIServerUp(ctx, client, pvclaim, vcAddress, healthStatusAccessible)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
isSvcUp = true
ginkgo.By("Expect health status of the pvc to be accessible")
pvc, err = client.CoreV1().PersistentVolumeClaims(pvclaim.Namespace).Get(ctx, pvclaim.Name, metav1.GetOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
gomega.Expect(pvc.Annotations[volumeHealthAnnotation]).Should(gomega.BeEquivalentTo(healthStatusAccessible))
})
/*
Validate the health status is updated from "unknown" status to inaccessible .
Steps
Create a Storage Class
Create a PVC using above SC
Wait for PVC to be in Bound phase
Bring VSAN down
Verify no health annotation is added on the PVC
Bring VSAN up
Bring down link between all the hosts and datastore.
Verify health annotation which is added on the PVC is inaccessible
Restore link between all the hosts and datastore.
Delete PVCs
Verify PV entry is deleted from CNS
Delete the SC
*/
ginkgo.It("[csi-supervisor] [csi-guest] Verify health annotation is updated from unknown status to inaccessible", func() {
var storageclass *storagev1.StorageClass
var err error
var pvclaims []*v1.PersistentVolumeClaim
var pv *v1.PersistentVolume
ctx, cancel := context.WithCancel(context.Background())
log := logger.GetLogger(ctx)
defer cancel()
raid0StoragePolicyName = os.Getenv("RAID_0_STORAGE_POLICY")
if raid0StoragePolicyName == "" {
ginkgo.Skip("Env RAID_0_STORAGE_POLICY is missing")
}
ginkgo.By("Invoking Test for validating health status")
// decide which test setup is available to run
if supervisorCluster {
ginkgo.By("CNS_TEST: Running for WCP setup")
profileID := e2eVSphere.GetSpbmPolicyID(raid0StoragePolicyName)
scParameters[scParamStoragePolicyID] = profileID
// create resource quota
createResourceQuota(client, namespace, rqLimit, raid0StoragePolicyName)
storageclass, pvclaim, err = createPVCAndStorageClass(client, namespace, nil, scParameters, diskSize, nil, "", false, "", raid0StoragePolicyName)
} else if guestCluster {
ginkgo.By("CNS_TEST: Running for GC setup")
scParameters[svStorageClassName] = raid0StoragePolicyName
storageclass, pvclaim, err = createPVCAndStorageClass(client, namespace, nil, scParameters, diskSize, nil, "", false, "")
}
gomega.Expect(err).NotTo(gomega.HaveOccurred())
defer func() {
err := client.StorageV1().StorageClasses().Delete(ctx, storageclass.Name, *metav1.NewDeleteOptions(0))
gomega.Expect(err).NotTo(gomega.HaveOccurred())
}()
ginkgo.By("Expect claim to provision volume successfully")
pvclaims = append(pvclaims, pvclaim)
persistentvolumes, err := fpv.WaitForPVClaimBoundPhase(client, pvclaims, framework.ClaimProvisionTimeout)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
volHandle := persistentvolumes[0].Spec.CSI.VolumeHandle
svPVCName := volHandle
if guestCluster {
// svcPVCName refers to PVC Name in the supervisor cluster
svcPVCName := volHandle
volHandle = getVolumeIDFromSupervisorCluster(svcPVCName)
}
gomega.Expect(volHandle).NotTo(gomega.BeEmpty())
ginkgo.By(fmt.Sprintln("Stopping vsan-health on the vCenter host"))
vcAddress := e2eVSphere.Config.Global.VCenterHostname + ":" + sshdPort
err = invokeVCenterServiceControl(stopOperation, vsanhealthServiceName, vcAddress)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
ginkgo.By(fmt.Sprintf("Sleeping for %v seconds to allow vsan-health to completely shutdown", vsanHealthServiceWaitTime))
time.Sleep(time.Duration(vsanHealthServiceWaitTime) * time.Second)
ginkgo.By(fmt.Sprintf("Sleeping for %v minutes to allow volume health check to be triggered", healthStatusWaitTime))
time.Sleep(healthStatusWaitTime)
ginkgo.By("Expect health annotation is not added on the pvc")
pvc, err := client.CoreV1().PersistentVolumeClaims(pvclaim.Namespace).Get(ctx, pvclaim.Name, metav1.GetOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
for describe := range pvc.Annotations {
gomega.Expect(pvc.Annotations[describe]).ShouldNot(gomega.BeEquivalentTo(volumeHealthAnnotation))
}
if supervisorCluster {
pv = getPvFromClaim(client, namespace, pvclaim.Name)
framework.Logf("volume name %v", pv.Name)
}
if guestCluster {
ginkgo.By("Expect health annotation is not added on the SV pvc")
svPVC := getPVCFromSupervisorCluster(svPVCName)
for describe := range svPVC.Annotations {
gomega.Expect(svPVC.Annotations[describe]).ShouldNot(gomega.BeEquivalentTo(volumeHealthAnnotation))
}
svcClient, svNamespace := getSvcClientAndNamespace()
pv = getPvFromClaim(svcClient, svNamespace, svPVCName)
framework.Logf("PV name in SVC for PVC in GC %v", pv.Name)
}
ginkgo.By(fmt.Sprintln("Starting vsan-health on the vCenter host"))
err = invokeVCenterServiceControl(startOperation, vsanhealthServiceName, vcAddress)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
ginkgo.By(fmt.Sprintf("Sleeping for %v seconds to allow vsan-health to come up again", vsanHealthServiceWaitTime))
time.Sleep(time.Duration(vsanHealthServiceWaitTime) * time.Second)
//PSOD the host
ginkgo.By("PSOD the host")
hostIP = psodHostWithPv(ctx, &e2eVSphere, pv.Name)
defer func() {
ginkgo.By("checking host status")
err := waitForHostToBeUp(hostIP)
time.Sleep(pollTimeoutShort)
if err != nil {
time.Sleep(hostRecoveryTime)
}
err = fpv.DeletePersistentVolumeClaim(client, pvclaim.Name, namespace)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
pvclaim = nil
err = e2eVSphere.waitForCNSVolumeToBeDeleted(volHandle)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
}()
ginkgo.By("poll for health status annotation")
err = pvcHealthAnnotationWatcher(ctx, client, pvclaim, healthStatusInAccessible)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
ginkgo.By("Expect health annotation is added on the pvc and its inaccessible")
pvc, err = client.CoreV1().PersistentVolumeClaims(pvclaim.Namespace).Get(ctx, pvclaim.Name, metav1.GetOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
gomega.Expect(pvc.Annotations[volumeHealthAnnotation]).Should(gomega.BeEquivalentTo(healthStatusInAccessible))
if guestCluster {
//verifying svc pvc health status also to be inaccessible
ginkgo.By("Expect health annotation is added on the SV pvc")
svPVC := getPVCFromSupervisorCluster(svPVCName)
gomega.Expect(svPVC.Annotations[volumeHealthAnnotation]).Should(gomega.BeEquivalentTo(healthStatusInAccessible))
}
ginkgo.By("poll for health status annotation")
err = pvcHealthAnnotationWatcher(ctx, client, pvclaim, healthStatusAccessible)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
if guestCluster {
ginkgo.By("poll for health status annotation")
err = pvcHealthAnnotationWatcher(ctx, client, pvclaim, healthStatusAccessible)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
//verifying svc pvc health status
ginkgo.By("Expect health annotation is added on the SV pvc")
svPVC := getPVCFromSupervisorCluster(svPVCName)
gomega.Expect(svPVC.Annotations[volumeHealthAnnotation]).Should(gomega.BeEquivalentTo(healthStatusAccessible))
}
ginkgo.By("Expect health annotation is added on the pvc and its accessible")
pvc, err = client.CoreV1().PersistentVolumeClaims(pvclaim.Namespace).Get(ctx, pvclaim.Name, metav1.GetOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
gomega.Expect(pvc.Annotations[volumeHealthAnnotation]).Should(gomega.BeEquivalentTo(healthStatusAccessible))
ginkgo.By(fmt.Sprintf("Invoking QueryCNSVolumeWithResult with VolumeID: %s", volHandle))
queryResult, err := e2eVSphere.queryCNSVolumeWithResult(volHandle)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
gomega.Expect(len(queryResult.Volumes) > 0)
ginkgo.By("Verifying the volume health status returned by CNS(green/yellow/red")
for _, vol := range queryResult.Volumes {
log.Infof("Volume health status: %s", vol.HealthStatus)
gomega.Expect(vol.HealthStatus).Should(gomega.BeEquivalentTo(healthGreen))
}
})
/*
Bring the CSI controller down when there is change in health status
Create a Storage Class
Create a GC PVC using above SC
Wait for PVC to be in Bound phase
Verify health annotation format which is added on the SV PVC and GC PVC is accessible
Bring down link between all the hosts and datastore
Bring GC CSI down
Verify health annotation which is added on the GC PVC is not changed to inaccessible
Bring GC CSI controller Up
wait for healthStatusWaitTime to make sure the GC PVC is updated with the health annotation
Verify health annotation which is added on the SV PVC and GC PVC is changed to inaccessible
Restore link between all the hosts and datastore
Delete GC PVC
Verify PV entry is deleted from CNS
Delete the SC
*/
ginkgo.It("[csi-guest] Verify Inaccesssible Volume health when GC CSI is down", func() {
var sc *storagev1.StorageClass
var err error
var isControllerUP = true
ctx, cancel := context.WithCancel(context.Background())
log := logger.GetLogger(ctx)
defer cancel()
raid0StoragePolicyName = os.Getenv("RAID_0_STORAGE_POLICY")
if raid0StoragePolicyName == "" {
ginkgo.Skip("Env RAID_0_STORAGE_POLICY is missing")
}
ginkgo.By("Creating Storage Class and PVC")
scParameters[svStorageClassName] = raid0StoragePolicyName
sc, pvc, err = createPVCAndStorageClass(client, namespace, nil, scParameters, "", nil, "", false, "")
gomega.Expect(err).NotTo(gomega.HaveOccurred())
defer func() {
err := client.StorageV1().StorageClasses().Delete(ctx, sc.Name, *metav1.NewDeleteOptions(0))
gomega.Expect(err).NotTo(gomega.HaveOccurred())
}()
ginkgo.By(fmt.Sprintf("Waiting for claim %s to be in bound phase", pvc.Name))
pvs, err := fpv.WaitForPVClaimBoundPhase(client, []*v1.PersistentVolumeClaim{pvc}, framework.ClaimProvisionTimeout)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
gomega.Expect(pvs).NotTo(gomega.BeEmpty())
pv := pvs[0]
volumeID := pv.Spec.CSI.VolumeHandle
//svPVCName refers to PVC Name in the supervisor cluster
svPVCName := volumeID
volumeID = getVolumeIDFromSupervisorCluster(svPVCName)
framework.Logf("volume ID from SVC %v", volumeID)
gomega.Expect(volumeID).NotTo(gomega.BeEmpty())
svcClient, svNamespace := getSvcClientAndNamespace()
svcPV := getPvFromClaim(svcClient, svNamespace, svPVCName)
framework.Logf("PV name in SVC for PVC in GC %v", svcPV.Name)
var gcClient clientset.Interface
if k8senv := GetAndExpectStringEnvVar("KUBECONFIG"); k8senv != "" {
gcClient, err = k8s.CreateKubernetesClientFromConfig(k8senv)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
}
defer func() {
ginkgo.By("checking host status")
err := waitForHostToBeUp(hostIP)
time.Sleep(pollTimeoutShort)
if err != nil {
time.Sleep(hostRecoveryTime)
}
if !isControllerUP {
bringUpTKGController(svcClient)
bringUpCsiController(gcClient)
}
err = fpv.DeletePersistentVolumeClaim(client, pvc.Name, namespace)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
pvc = nil
err = e2eVSphere.waitForCNSVolumeToBeDeleted(pv.Spec.CSI.VolumeHandle)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
}()
ginkgo.By("poll for health status annotation")
err = pvcHealthAnnotationWatcher(ctx, client, pvc, healthStatusAccessible)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
ginkgo.By("Expect health status of the pvc to be accessible")
pvclaim, err := client.CoreV1().PersistentVolumeClaims(pvc.Namespace).Get(ctx, pvc.Name, metav1.GetOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
gomega.Expect(pvclaim.Annotations[volumeHealthAnnotation]).Should(gomega.BeEquivalentTo(healthStatusAccessible))
ginkgo.By("Bring down csi-controller pod in GC")
bringDownTKGController(svcClient)
bringDownCsiController(gcClient)
isControllerUP = false
//PSOD the host
ginkgo.By("PSOD the host")
hostIP = psodHostWithPv(ctx, &e2eVSphere, svcPV.Name)
//Health status in gc pvc should be still accessible
ginkgo.By("poll for health status annotation")
err = pvcHealthAnnotationWatcher(ctx, client, pvc, healthStatusAccessible)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
ginkgo.By("Expect health status of the pvc to be accessible")
pvclaim, err = client.CoreV1().PersistentVolumeClaims(pvc.Namespace).Get(ctx, pvc.Name, metav1.GetOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
gomega.Expect(pvclaim.Annotations[volumeHealthAnnotation]).Should(gomega.BeEquivalentTo(healthStatusAccessible))
ginkgo.By("Expect health annotation is added on the SV pvc")
svPVC := getPVCFromSupervisorCluster(svPVCName)
err = pvcHealthAnnotationWatcher(ctx, svcClient, svPVC, healthStatusInAccessible)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
gomega.Expect(svPVC.Annotations[volumeHealthAnnotation]).Should(gomega.BeEquivalentTo(healthStatusInAccessible))
ginkgo.By("Bring up csi-controller pod in GC")
bringUpTKGController(svcClient)
bringUpCsiController(gcClient)
isControllerUP = true
ginkgo.By("Verify health status of GC PVC after GC csi is up")
ginkgo.By("poll for health status annotation")
err = pvcHealthAnnotationWatcher(ctx, client, pvclaim, healthStatusInAccessible)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
pvclaim, err = client.CoreV1().PersistentVolumeClaims(pvc.Namespace).Get(ctx, pvc.Name, metav1.GetOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
gomega.Expect(pvclaim.Annotations[volumeHealthAnnotation]).Should(gomega.BeEquivalentTo(healthStatusInAccessible))
ginkgo.By("Expect health annotation is added on the SV pvc")
svPVC = getPVCFromSupervisorCluster(svPVCName)
gomega.Expect(svPVC.Annotations[volumeHealthAnnotation]).Should(gomega.BeEquivalentTo(healthStatusInAccessible))
//ESX Host Recovery time
ginkgo.By("poll for health status annotation")
err = pvcHealthAnnotationWatcher(ctx, client, pvclaim, healthStatusAccessible)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
ginkgo.By(fmt.Sprintf("Invoking QueryCNSVolumeWithResult with VolumeID: %s", volumeID))
queryResult, err := e2eVSphere.queryCNSVolumeWithResult(volumeID)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
gomega.Expect(len(queryResult.Volumes) > 0)
ginkgo.By("Verifying the volume health status returned by CNS(green/yellow/red")
for _, vol := range queryResult.Volumes {
log.Infof("Volume health status: %s", vol.HealthStatus)
gomega.Expect(vol.HealthStatus).Should(gomega.BeEquivalentTo(healthGreen))
}
})
/*
Verify health annotation is added on the volume created by statefulset
steps
Create a storage class.
Create nginx service.
Create nginx statefulset
Wait until all Pods are ready and PVCs are bounded with PV.
Verify health annotation added on the PVC is accessible
Bring down link between all the hosts and datastore.
Verify health annotation on the PVC is updated to inaccessible
Restore the link between all the hosts and datastore.
Delete the pod(make the replicas to 0)
Delete PVC from the tests namespace
Delete the storage class.
*/
ginkgo.It("[csi-supervisor] [csi-guest] Verify Volume health Inaccessible on Statefulset", func() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var statusFlag bool = false
var pvSVC *v1.PersistentVolume
raid0StoragePolicyName = os.Getenv("RAID_0_STORAGE_POLICY")
if raid0StoragePolicyName == "" {
ginkgo.Skip("Env RAID_0_STORAGE_POLICY is missing")
}
ginkgo.By("Creating StorageClass for Statefulset")
// decide which test setup is available to run
if supervisorCluster {
ginkgo.By("CNS_TEST: Running for WCP setup")
profileID := e2eVSphere.GetSpbmPolicyID(raid0StoragePolicyName)
scParameters[scParamStoragePolicyID] = profileID
// create resource quota
createResourceQuota(client, namespace, rqLimit, storageclassname)
scSpec := getVSphereStorageClassSpec(storageclassname, scParameters, nil, "", "", false)
sc, err := client.StorageV1().StorageClasses().Create(ctx, scSpec, metav1.CreateOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
defer func() {
err := client.StorageV1().StorageClasses().Delete(ctx, sc.Name, *metav1.NewDeleteOptions(0))
gomega.Expect(err).NotTo(gomega.HaveOccurred())
}()
}
if guestCluster {
scParameters[svStorageClassName] = raid0StoragePolicyName
sc, err := createStorageClass(client, scParameters, nil, "", "", false, "nginx-sc")
gomega.Expect(err).NotTo(gomega.HaveOccurred())
defer func() {
err := client.StorageV1().StorageClasses().Delete(ctx, sc.Name, *metav1.NewDeleteOptions(0))
gomega.Expect(err).NotTo(gomega.HaveOccurred())
}()
}
ginkgo.By("Creating service")
service := CreateService(namespace, client)
defer func() {
deleteService(namespace, client, service)
}()
statefulset := GetStatefulSetFromManifest(namespace)
ginkgo.By("Creating statefulset")
CreateStatefulSet(namespace, statefulset, client)
replicas := *(statefulset.Spec.Replicas)
// Waiting for pods status to be Ready
fss.WaitForStatusReadyReplicas(client, statefulset, replicas)
gomega.Expect(fss.CheckMount(client, statefulset, mountPath)).NotTo(gomega.HaveOccurred())
ssPodsBeforeScaleDown := fss.GetPodList(client, statefulset)
gomega.Expect(ssPodsBeforeScaleDown.Items).NotTo(gomega.BeEmpty(), fmt.Sprintf("Unable to get list of Pods from the Statefulset: %v", statefulset.Name))
gomega.Expect(len(ssPodsBeforeScaleDown.Items) == int(replicas)).To(gomega.BeTrue(), "Number of Pods in the statefulset should match with number of replicas")
if supervisorCluster {
// Get the list of Volumes attached to Pods
for _, sspod := range ssPodsBeforeScaleDown.Items {
for _, volumespec := range sspod.Spec.Volumes {
if volumespec.PersistentVolumeClaim != nil {
pv := getPvFromClaim(client, statefulset.Namespace, volumespec.PersistentVolumeClaim.ClaimName)
// Verify the attached volume match the one in CNS cache
err := verifyVolumeMetadataInCNS(&e2eVSphere, pv.Spec.CSI.VolumeHandle, volumespec.PersistentVolumeClaim.ClaimName, pv.ObjectMeta.Name, sspod.Name)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
ginkgo.By("Expect health status of the pvc to be accessible")
pvc, err := client.CoreV1().PersistentVolumeClaims(namespace).Get(ctx, volumespec.PersistentVolumeClaim.ClaimName, metav1.GetOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
ginkgo.By("poll for health status annotation")
err = pvcHealthAnnotationWatcher(ctx, client, pvc, healthStatusAccessible)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
}
}
}
}
if guestCluster {
for _, sspod := range ssPodsBeforeScaleDown.Items {
_, err := client.CoreV1().Pods(namespace).Get(ctx, sspod.Name, metav1.GetOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
for _, volumespec := range sspod.Spec.Volumes {
if volumespec.PersistentVolumeClaim != nil {
pv := getPvFromClaim(client, statefulset.Namespace, volumespec.PersistentVolumeClaim.ClaimName)
ginkgo.By("Verify CnsNodeVmAttachment CRD is created")
volumeID := pv.Spec.CSI.VolumeHandle
// svcPVCName refers to PVC Name in the supervisor cluster
svcPVCName := volumeID
volumeID = getVolumeIDFromSupervisorCluster(svcPVCName)
gomega.Expect(volumeID).NotTo(gomega.BeEmpty())
verifyCRDInSupervisor(ctx, f, sspod.Spec.NodeName+"-"+svcPVCName, crdCNSNodeVMAttachment, crdVersion, crdGroup, true)
ginkgo.By("Expect health status of the pvc to be accessible")
pvc, err := client.CoreV1().PersistentVolumeClaims(namespace).Get(ctx, volumespec.PersistentVolumeClaim.ClaimName, metav1.GetOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
ginkgo.By("poll for health status annotation")
err = pvcHealthAnnotationWatcher(ctx, client, pvc, healthStatusAccessible)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
ginkgo.By("Expect health annotation is added on the SV pvc")
svPVC := getPVCFromSupervisorCluster(pv.Spec.CSI.VolumeHandle)
framework.Logf("svPVC %v", svPVC)
ginkgo.By("Get svcClient and svNamespace")
svcClient, svNamespace := getSvcClientAndNamespace()
ginkgo.By("poll for health status annotation")
err = pvcHealthAnnotationWatcher(ctx, svcClient, svPVC, healthStatusAccessible)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
pvSVC = getPvFromClaim(svcClient, svNamespace, pv.Spec.CSI.VolumeHandle)
framework.Logf("PV name in SVC for PVC in GC %v", pvSVC.Name)
}
}
}
}
//PSOD the host
ginkgo.By("PSOD the host")
framework.Logf("pv.Name %v", pvSVC.Name)
hostIP = psodHostWithPv(ctx, &e2eVSphere, pvSVC.Name)
defer func() {
ginkgo.By("checking host status")
err := waitForHostToBeUp(hostIP)
time.Sleep(pollTimeoutShort)
if err != nil {
time.Sleep(hostRecoveryTime)
}
ginkgo.By(fmt.Sprintf("Deleting all statefulsets in namespace: %v", namespace))
fss.DeleteAllStatefulSets(client, namespace)
}()
ginkgo.By(fmt.Sprintf("Sleeping for %v to allow volume health check to be triggered", svOperationTimeout))
time.Sleep(svOperationTimeout)
ginkgo.By("Expect health status of a pvc to be inaccessible")
// Get the list of Volumes attached to Pods
for _, sspod := range ssPodsBeforeScaleDown.Items {
for _, volumespec := range sspod.Spec.Volumes {
if volumespec.PersistentVolumeClaim != nil {
if supervisorCluster {
pv := getPvFromClaim(client, statefulset.Namespace, volumespec.PersistentVolumeClaim.ClaimName)
// Verify the attached volume match the one in CNS cache
err := verifyVolumeMetadataInCNS(&e2eVSphere, pv.Spec.CSI.VolumeHandle, volumespec.PersistentVolumeClaim.ClaimName, pv.ObjectMeta.Name, sspod.Name)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
}
pvc, err := client.CoreV1().PersistentVolumeClaims(namespace).Get(ctx, volumespec.PersistentVolumeClaim.ClaimName, metav1.GetOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
if pvc.Annotations[volumeHealthAnnotation] == healthStatusInAccessible {
statusFlag = true
break
}
}
}
}
ginkgo.By("Expect health annotation is added on the SV pvc is inaccessible")
if guestCluster {
for _, sspod := range ssPodsBeforeScaleDown.Items {
for _, volumespec := range sspod.Spec.Volumes {
if volumespec.PersistentVolumeClaim != nil {
pv := getPvFromClaim(client, statefulset.Namespace, volumespec.PersistentVolumeClaim.ClaimName)
svPVC := getPVCFromSupervisorCluster(pv.Spec.CSI.VolumeHandle)
if svPVC.Annotations[volumeHealthAnnotation] == healthStatusInAccessible {
statusFlag = true
break
} else {
statusFlag = false
}
}
}
}
}
if !statusFlag {
framework.Logf("Volume health status is not as expected")
gomega.Expect(statusFlag).NotTo(gomega.BeFalse())
}
if supervisorCluster {
// Get the list of Volumes attached to Pods
for _, sspod := range ssPodsBeforeScaleDown.Items {
for _, volumespec := range sspod.Spec.Volumes {
if volumespec.PersistentVolumeClaim != nil {
pv := getPvFromClaim(client, statefulset.Namespace, volumespec.PersistentVolumeClaim.ClaimName)
// Verify the attached volume match the one in CNS cache
err := verifyVolumeMetadataInCNS(&e2eVSphere, pv.Spec.CSI.VolumeHandle, volumespec.PersistentVolumeClaim.ClaimName, pv.ObjectMeta.Name, sspod.Name)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
ginkgo.By("Expect health status of the pvc to be accessible")
pvc, err := client.CoreV1().PersistentVolumeClaims(namespace).Get(ctx, volumespec.PersistentVolumeClaim.ClaimName, metav1.GetOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
ginkgo.By("poll for health status annotation")
err = pvcHealthAnnotationWatcher(ctx, client, pvc, healthStatusAccessible)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
}
}
}
}
})
/*
Validate the health status is not updated to "unknown" status from inaccessible
Steps
Create a Storage Class
Create a PVC using above SC
Wait for PVC to be in Bound phase
Bring down link between all the hosts and datastore.
Verify health annotation which is added on the PVC is inaccessible
Bring VSAN down
Verify the health annotation of the PVC remains inaccessible
Bring VSAN up
Restore link between all the hosts and datastore.
Delete PVC
Verify PV entry is deleted from CNS
Delete the SC
*/
ginkgo.It("[csi-supervisor] [csi-guest] Verify health annotation is not updated to unknown status from inaccessible", func() {
var storageclass *storagev1.StorageClass
var err error
var pvclaims []*v1.PersistentVolumeClaim
ctx, cancel := context.WithCancel(context.Background())
log := logger.GetLogger(ctx)
defer cancel()
raid0StoragePolicyName = os.Getenv("RAID_0_STORAGE_POLICY")
if raid0StoragePolicyName == "" {
ginkgo.Skip("Env RAID_0_STORAGE_POLICY is missing")
}
ginkgo.By("Invoking Test for validating health status")
// decide which test setup is available to run
if supervisorCluster {
ginkgo.By("CNS_TEST: Running for WCP setup")
profileID := e2eVSphere.GetSpbmPolicyID(raid0StoragePolicyName)
scParameters[scParamStoragePolicyID] = profileID
// create resource quota
createResourceQuota(client, namespace, rqLimit, raid0StoragePolicyName)
storageclass, pvclaim, err = createPVCAndStorageClass(client, namespace, nil, scParameters, diskSize, nil, "", false, "", raid0StoragePolicyName)
} else if guestCluster {
ginkgo.By("CNS_TEST: Running for GC setup")
scParameters[svStorageClassName] = raid0StoragePolicyName
storageclass, pvclaim, err = createPVCAndStorageClass(client, namespace, nil, scParameters, diskSize, nil, "", false, "")
}
gomega.Expect(err).NotTo(gomega.HaveOccurred())
defer func() {
err := client.StorageV1().StorageClasses().Delete(ctx, storageclass.Name, *metav1.NewDeleteOptions(0))
gomega.Expect(err).NotTo(gomega.HaveOccurred())
}()
ginkgo.By("Expect claim to provision volume successfully")
pvclaims = append(pvclaims, pvclaim)
persistentvolumes, err := fpv.WaitForPVClaimBoundPhase(client, pvclaims, framework.ClaimProvisionTimeout)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
volHandle := persistentvolumes[0].Spec.CSI.VolumeHandle
svPVCName := volHandle
pv := getPvFromClaim(client, namespace, pvclaim.Name)
framework.Logf("volume name %v", pv.Name)
if guestCluster {
// svcPVCName refers to PVC Name in the supervisor cluster
svcPVCName := volHandle
volHandle = getVolumeIDFromSupervisorCluster(svcPVCName)
svcClient, svNamespace := getSvcClientAndNamespace()
pv = getPvFromClaim(svcClient, svNamespace, svPVCName)
framework.Logf("PV name in SVC for PVC in GC %v", pv.Name)
}
gomega.Expect(volHandle).NotTo(gomega.BeEmpty())
//PSOD the host
ginkgo.By("PSOD the host")
hostIP = psodHostWithPv(ctx, &e2eVSphere, pv.Name)
defer func() {
ginkgo.By("checking host status")
err := waitForHostToBeUp(hostIP)
time.Sleep(pollTimeoutShort)
if err != nil {
time.Sleep(hostRecoveryTime)
}
err = fpv.DeletePersistentVolumeClaim(client, pvclaim.Name, namespace)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
pvclaim = nil
err = e2eVSphere.waitForCNSVolumeToBeDeleted(volHandle)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
}()
ginkgo.By("poll for health status annotation")
err = pvcHealthAnnotationWatcher(ctx, client, pvclaim, healthStatusInAccessible)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
ginkgo.By("Expect health annotation is added on the pvc and its inaccessible")
pvc, err := client.CoreV1().PersistentVolumeClaims(pvclaim.Namespace).Get(ctx, pvclaim.Name, metav1.GetOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
gomega.Expect(pvc.Annotations[volumeHealthAnnotation]).Should(gomega.BeEquivalentTo(healthStatusInAccessible))
if guestCluster {
//verifying svc pvc health status
ginkgo.By("Expect health annotation is added on the SV pvc")
svPVC := getPVCFromSupervisorCluster(svPVCName)
gomega.Expect(svPVC.Annotations[volumeHealthAnnotation]).Should(gomega.BeEquivalentTo(healthStatusInAccessible))
}
ginkgo.By("Verifying the volume health status returned by CNS(green/yellow/red")
queryResult, err := e2eVSphere.queryCNSVolumeWithResult(volHandle)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
for _, vol := range queryResult.Volumes {
log.Infof("Volume health status: %s", vol.HealthStatus)
gomega.Expect(vol.HealthStatus).Should(gomega.BeEquivalentTo(healthRed))
}
ginkgo.By(fmt.Sprintln("Stopping vsan-health on the vCenter host"))
isVsanhealthServiceStopped = true
vcAddress := e2eVSphere.Config.Global.VCenterHostname + ":" + sshdPort
err = invokeVCenterServiceControl(stopOperation, vsanhealthServiceName, vcAddress)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
ginkgo.By(fmt.Sprintf("Sleeping for %v seconds to allow vsan-health to completely shutdown", vsanHealthServiceWaitTime))
time.Sleep(time.Duration(vsanHealthServiceWaitTime) * time.Second)
ginkgo.By("poll for health status annotation")
err = pvcHealthAnnotationWatcher(ctx, client, pvclaim, healthStatusInAccessible)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
ginkgo.By("Expect health annotation is added on the pvc and its inaccessible after the vsan health is down")
pvc, err = client.CoreV1().PersistentVolumeClaims(pvclaim.Namespace).Get(ctx, pvclaim.Name, metav1.GetOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
gomega.Expect(pvc.Annotations[volumeHealthAnnotation]).Should(gomega.BeEquivalentTo(healthStatusInAccessible))
if guestCluster {
//verifying svc pvc health status
ginkgo.By("Expect health annotation is added on the SV pvc")
svPVC := getPVCFromSupervisorCluster(svPVCName)
gomega.Expect(svPVC.Annotations[volumeHealthAnnotation]).Should(gomega.BeEquivalentTo(healthStatusInAccessible))
}
ginkgo.By(fmt.Sprintln("Starting vsan-health on the vCenter host"))
err = invokeVCenterServiceControl(startOperation, vsanhealthServiceName, vcAddress)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
ginkgo.By(fmt.Sprintf("Sleeping for %v seconds to allow vsan-health to come up again", vsanHealthServiceWaitTime))
time.Sleep(time.Duration(vsanHealthServiceWaitTime) * time.Second)
isVsanhealthServiceStopped = false
ginkgo.By("poll for health status annotation")
err = pvcHealthAnnotationWatcher(ctx, client, pvclaim, healthStatusAccessible)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
if guestCluster {
ginkgo.By("poll for health status annotation")
err = pvcHealthAnnotationWatcher(ctx, client, pvclaim, healthStatusAccessible)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
//verifying svc pvc health status
ginkgo.By("Expect health annotation is added on the SV pvc")
svPVC := getPVCFromSupervisorCluster(svPVCName)
gomega.Expect(svPVC.Annotations[volumeHealthAnnotation]).Should(gomega.BeEquivalentTo(healthStatusAccessible))
}
ginkgo.By("Expect health annotation is added on the pvc and its accessible")
pvc, err = client.CoreV1().PersistentVolumeClaims(pvclaim.Namespace).Get(ctx, pvclaim.Name, metav1.GetOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
gomega.Expect(pvc.Annotations[volumeHealthAnnotation]).Should(gomega.BeEquivalentTo(healthStatusAccessible))
ginkgo.By(fmt.Sprintf("Invoking QueryCNSVolumeWithResult with VolumeID: %s", volHandle))
queryResult, err = e2eVSphere.queryCNSVolumeWithResult(volHandle)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
gomega.Expect(len(queryResult.Volumes) > 0)
ginkgo.By("Verifying the volume health status returned by CNS(green/yellow/red")
for _, vol := range queryResult.Volumes {
log.Infof("Volume health status: %s", vol.HealthStatus)
gomega.Expect(vol.HealthStatus).Should(gomega.BeEquivalentTo(healthGreen))
}
})
/*
Verify pvc is not annotated with health status in block vanilla setup.
Steps
Create a Storage Class
Create a PVC using above SC
Wait for PVC to be in Bound phase
Verify health annotation is not added on the PVC
Delete PVC
Verify PV entry is deleted from CNS
Delete the SC
*/
ginkgo.It("[csi-block-vanilla] Verify pvc is not annotated with health status in vanilla setup", func() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
ginkgo.By("Invoking Test volume health status")
var storageclass *storagev1.StorageClass
var pvclaim *v1.PersistentVolumeClaim
var pvclaims []*v1.PersistentVolumeClaim
var err error
ginkgo.By("CNS_TEST: Running for vanilla k8s setup")
scParameters[scParamDatastoreURL] = datastoreURL
storageclass, pvclaim, err = createPVCAndStorageClass(client, namespace, nil, scParameters, diskSize, nil, "", false, "")
gomega.Expect(err).NotTo(gomega.HaveOccurred())
defer func() {
err := client.StorageV1().StorageClasses().Delete(ctx, storageclass.Name, *metav1.NewDeleteOptions(0))
gomega.Expect(err).NotTo(gomega.HaveOccurred())
}()
pvclaims = append(pvclaims, pvclaim)
persistentvolumes, err := fpv.WaitForPVClaimBoundPhase(client, pvclaims, framework.ClaimProvisionTimeout)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
volHandle := persistentvolumes[0].Spec.CSI.VolumeHandle
ginkgo.By(fmt.Sprintf("Sleeping for %v minutes to allow volume health check to be triggered", pollTimeout))
time.Sleep(pollTimeout)
ginkgo.By("Expect health annotation is not added on the pvc")
pvc, err := client.CoreV1().PersistentVolumeClaims(pvclaim.Namespace).Get(ctx, pvclaim.Name, metav1.GetOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
for describe := range pvc.Annotations {
gomega.Expect(pvc.Annotations[describe]).ShouldNot(gomega.BeEquivalentTo(volumeHealthAnnotation))
}
defer func() {
err := fpv.DeletePersistentVolumeClaim(client, pvclaim.Name, namespace)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
err = e2eVSphere.waitForCNSVolumeToBeDeleted(volHandle)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
}()
ginkgo.By(fmt.Sprintf("Invoking QueryCNSVolumeWithResult with VolumeID: %s", volHandle))
queryResult, err := e2eVSphere.queryCNSVolumeWithResult(volHandle)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
if len(queryResult.Volumes) == 0 {
err = fmt.Errorf("QueryCNSVolumeWithResult returned no volume")
}
gomega.Expect(err).NotTo(gomega.HaveOccurred())
})
/*
Verify pvc is not annotated with health status in file vanilla setup .
Steps
Create a Storage Class
Create a PVC using above SC
Wait for PVC to be in Bound phase
Verify health annotation is not added on the PVC
Delete PVC
Verify PV entry is deleted from CNS
Delete the SC
*/
ginkgo.It("[csi-file-vanilla] File Vanilla Verify pvc is not annotated with health status", func() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
scParameters := make(map[string]string)
scParameters[scParamFsType] = nfs4FSType
accessMode := v1.ReadWriteMany
// Create Storage class and PVC
ginkgo.By(fmt.Sprintf("Creating Storage Class with access mode %q and fstype %q", accessMode, nfs4FSType))
var storageclass *storagev1.StorageClass
var pvclaim *v1.PersistentVolumeClaim
var err error
storageclass, pvclaim, err = createPVCAndStorageClass(client, namespace, nil, scParameters, "", nil, "", false, accessMode)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
defer func() {
err := client.StorageV1().StorageClasses().Delete(ctx, storageclass.Name, *metav1.NewDeleteOptions(0))
gomega.Expect(err).NotTo(gomega.HaveOccurred())
}()
// Waiting for PVC to be bound
var pvclaims []*v1.PersistentVolumeClaim
pvclaims = append(pvclaims, pvclaim)
ginkgo.By("Waiting for all claims to be in bound state")
persistentvolumes, err := fpv.WaitForPVClaimBoundPhase(client, pvclaims, framework.ClaimProvisionTimeout)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
volHandle := persistentvolumes[0].Spec.CSI.VolumeHandle
defer func() {
err := fpv.DeletePersistentVolumeClaim(client, pvclaim.Name, namespace)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
err = e2eVSphere.waitForCNSVolumeToBeDeleted(volHandle)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
}()
ginkgo.By(fmt.Sprintf("Sleeping for %v minutes to allow volume health check to be triggered", pollTimeout))
time.Sleep(pollTimeout)
ginkgo.By("Expect health annotation is not added on the pvc")
pvc, err := client.CoreV1().PersistentVolumeClaims(pvclaim.Namespace).Get(ctx, pvclaim.Name, metav1.GetOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred())
for describe := range pvc.Annotations {
gomega.Expect(pvc.Annotations[describe]).ShouldNot(gomega.BeEquivalentTo(pvcHealthAnnotation))
}
ginkgo.By(fmt.Sprintf("Invoking QueryCNSVolumeWithResult with VolumeID: %s", volHandle))
queryResult, err := e2eVSphere.queryCNSVolumeWithResult(volHandle)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
gomega.Expect(queryResult.Volumes).ShouldNot(gomega.BeEmpty())
ginkgo.By(fmt.Sprintf("volume Name:%s , capacity:%d volumeType:%s health:%s", queryResult.Volumes[0].Name, queryResult.Volumes[0].BackingObjectDetails.(*cnstypes.CnsVsanFileShareBackingDetails).CapacityInMb, queryResult.Volumes[0].VolumeType, queryResult.Volumes[0].HealthStatus))
ginkgo.By("Verifying volume type specified in PVC is honored")
if queryResult.Volumes[0].VolumeType != testVolumeType {
err = fmt.Errorf("volume type is not %q", testVolumeType)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
}
})
})
| [
"\"RAID_0_STORAGE_POLICY\"",
"\"RAID_0_STORAGE_POLICY\"",
"\"RAID_0_STORAGE_POLICY\"",
"\"RAID_0_STORAGE_POLICY\"",
"\"RAID_0_STORAGE_POLICY\"",
"\"RAID_0_STORAGE_POLICY\"",
"\"RAID_0_STORAGE_POLICY\""
] | [] | [
"RAID_0_STORAGE_POLICY"
] | [] | ["RAID_0_STORAGE_POLICY"] | go | 1 | 0 | |
go/src/github.com/hashicorp/terraform/builtin/providers/heroku/resource_heroku_app_test.go | package heroku
import (
"fmt"
"os"
"testing"
"github.com/cyberdelia/heroku-go/v3"
"github.com/hashicorp/terraform/helper/acctest"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform"
)
func TestAccHerokuApp_Basic(t *testing.T) {
var app heroku.App
appName := fmt.Sprintf("tftest-%s", acctest.RandString(10))
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckHerokuAppDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccCheckHerokuAppConfig_basic(appName),
Check: resource.ComposeTestCheckFunc(
testAccCheckHerokuAppExists("heroku_app.foobar", &app),
testAccCheckHerokuAppAttributes(&app, appName),
resource.TestCheckResourceAttr(
"heroku_app.foobar", "name", appName),
resource.TestCheckResourceAttr(
"heroku_app.foobar", "config_vars.0.FOO", "bar"),
),
},
},
})
}
func TestAccHerokuApp_NameChange(t *testing.T) {
var app heroku.App
appName := fmt.Sprintf("tftest-%s", acctest.RandString(10))
appName2 := fmt.Sprintf("%s-v2", appName)
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckHerokuAppDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccCheckHerokuAppConfig_basic(appName),
Check: resource.ComposeTestCheckFunc(
testAccCheckHerokuAppExists("heroku_app.foobar", &app),
testAccCheckHerokuAppAttributes(&app, appName),
resource.TestCheckResourceAttr(
"heroku_app.foobar", "name", appName),
resource.TestCheckResourceAttr(
"heroku_app.foobar", "config_vars.0.FOO", "bar"),
),
},
resource.TestStep{
Config: testAccCheckHerokuAppConfig_updated(appName2),
Check: resource.ComposeTestCheckFunc(
testAccCheckHerokuAppExists("heroku_app.foobar", &app),
testAccCheckHerokuAppAttributesUpdated(&app, appName2),
resource.TestCheckResourceAttr(
"heroku_app.foobar", "name", appName2),
resource.TestCheckResourceAttr(
"heroku_app.foobar", "config_vars.0.FOO", "bing"),
resource.TestCheckResourceAttr(
"heroku_app.foobar", "config_vars.0.BAZ", "bar"),
),
},
},
})
}
func TestAccHerokuApp_NukeVars(t *testing.T) {
var app heroku.App
appName := fmt.Sprintf("tftest-%s", acctest.RandString(10))
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckHerokuAppDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccCheckHerokuAppConfig_basic(appName),
Check: resource.ComposeTestCheckFunc(
testAccCheckHerokuAppExists("heroku_app.foobar", &app),
testAccCheckHerokuAppAttributes(&app, appName),
resource.TestCheckResourceAttr(
"heroku_app.foobar", "name", appName),
resource.TestCheckResourceAttr(
"heroku_app.foobar", "config_vars.0.FOO", "bar"),
),
},
resource.TestStep{
Config: testAccCheckHerokuAppConfig_no_vars(appName),
Check: resource.ComposeTestCheckFunc(
testAccCheckHerokuAppExists("heroku_app.foobar", &app),
testAccCheckHerokuAppAttributesNoVars(&app, appName),
resource.TestCheckResourceAttr(
"heroku_app.foobar", "name", appName),
resource.TestCheckResourceAttr(
"heroku_app.foobar", "config_vars.0.FOO", ""),
),
},
},
})
}
func TestAccHerokuApp_Organization(t *testing.T) {
var app heroku.OrganizationApp
appName := fmt.Sprintf("tftest-%s", acctest.RandString(10))
org := os.Getenv("HEROKU_ORGANIZATION")
resource.Test(t, resource.TestCase{
PreCheck: func() {
testAccPreCheck(t)
if org == "" {
t.Skip("HEROKU_ORGANIZATION is not set; skipping test.")
}
},
Providers: testAccProviders,
CheckDestroy: testAccCheckHerokuAppDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccCheckHerokuAppConfig_organization(appName, org),
Check: resource.ComposeTestCheckFunc(
testAccCheckHerokuAppExistsOrg("heroku_app.foobar", &app),
testAccCheckHerokuAppAttributesOrg(&app, appName, org),
),
},
},
})
}
func testAccCheckHerokuAppDestroy(s *terraform.State) error {
client := testAccProvider.Meta().(*heroku.Service)
for _, rs := range s.RootModule().Resources {
if rs.Type != "heroku_app" {
continue
}
_, err := client.AppInfo(rs.Primary.ID)
if err == nil {
return fmt.Errorf("App still exists")
}
}
return nil
}
func testAccCheckHerokuAppAttributes(app *heroku.App, appName string) resource.TestCheckFunc {
return func(s *terraform.State) error {
client := testAccProvider.Meta().(*heroku.Service)
if app.Region.Name != "us" {
return fmt.Errorf("Bad region: %s", app.Region.Name)
}
if app.Stack.Name != "cedar-14" {
return fmt.Errorf("Bad stack: %s", app.Stack.Name)
}
if app.Name != appName {
return fmt.Errorf("Bad name: %s", app.Name)
}
vars, err := client.ConfigVarInfo(app.Name)
if err != nil {
return err
}
if vars["FOO"] != "bar" {
return fmt.Errorf("Bad config vars: %v", vars)
}
return nil
}
}
func testAccCheckHerokuAppAttributesUpdated(app *heroku.App, appName string) resource.TestCheckFunc {
return func(s *terraform.State) error {
client := testAccProvider.Meta().(*heroku.Service)
if app.Name != appName {
return fmt.Errorf("Bad name: %s", app.Name)
}
vars, err := client.ConfigVarInfo(app.Name)
if err != nil {
return err
}
// Make sure we kept the old one
if vars["FOO"] != "bing" {
return fmt.Errorf("Bad config vars: %v", vars)
}
if vars["BAZ"] != "bar" {
return fmt.Errorf("Bad config vars: %v", vars)
}
return nil
}
}
func testAccCheckHerokuAppAttributesNoVars(app *heroku.App, appName string) resource.TestCheckFunc {
return func(s *terraform.State) error {
client := testAccProvider.Meta().(*heroku.Service)
if app.Name != appName {
return fmt.Errorf("Bad name: %s", app.Name)
}
vars, err := client.ConfigVarInfo(app.Name)
if err != nil {
return err
}
if len(vars) != 0 {
return fmt.Errorf("vars exist: %v", vars)
}
return nil
}
}
func testAccCheckHerokuAppAttributesOrg(app *heroku.OrganizationApp, appName string, org string) resource.TestCheckFunc {
return func(s *terraform.State) error {
client := testAccProvider.Meta().(*heroku.Service)
if app.Region.Name != "us" {
return fmt.Errorf("Bad region: %s", app.Region.Name)
}
if app.Stack.Name != "cedar-14" {
return fmt.Errorf("Bad stack: %s", app.Stack.Name)
}
if app.Name != appName {
return fmt.Errorf("Bad name: %s", app.Name)
}
if app.Organization == nil || app.Organization.Name != org {
return fmt.Errorf("Bad org: %v", app.Organization)
}
vars, err := client.ConfigVarInfo(app.Name)
if err != nil {
return err
}
if vars["FOO"] != "bar" {
return fmt.Errorf("Bad config vars: %v", vars)
}
return nil
}
}
func testAccCheckHerokuAppExists(n string, app *heroku.App) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[n]
if !ok {
return fmt.Errorf("Not found: %s", n)
}
if rs.Primary.ID == "" {
return fmt.Errorf("No App Name is set")
}
client := testAccProvider.Meta().(*heroku.Service)
foundApp, err := client.AppInfo(rs.Primary.ID)
if err != nil {
return err
}
if foundApp.Name != rs.Primary.ID {
return fmt.Errorf("App not found")
}
*app = *foundApp
return nil
}
}
func testAccCheckHerokuAppExistsOrg(n string, app *heroku.OrganizationApp) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[n]
if !ok {
return fmt.Errorf("Not found: %s", n)
}
if rs.Primary.ID == "" {
return fmt.Errorf("No App Name is set")
}
client := testAccProvider.Meta().(*heroku.Service)
foundApp, err := client.OrganizationAppInfo(rs.Primary.ID)
if err != nil {
return err
}
if foundApp.Name != rs.Primary.ID {
return fmt.Errorf("App not found")
}
*app = *foundApp
return nil
}
}
func testAccCheckHerokuAppConfig_basic(appName string) string {
return fmt.Sprintf(`
resource "heroku_app" "foobar" {
name = "%s"
region = "us"
config_vars {
FOO = "bar"
}
}`, appName)
}
func testAccCheckHerokuAppConfig_updated(appName string) string {
return fmt.Sprintf(`
resource "heroku_app" "foobar" {
name = "%s"
region = "us"
config_vars {
FOO = "bing"
BAZ = "bar"
}
}`, appName)
}
func testAccCheckHerokuAppConfig_no_vars(appName string) string {
return fmt.Sprintf(`
resource "heroku_app" "foobar" {
name = "%s"
region = "us"
}`, appName)
}
func testAccCheckHerokuAppConfig_organization(appName, org string) string {
return fmt.Sprintf(`
resource "heroku_app" "foobar" {
name = "%s"
region = "us"
organization {
name = "%s"
}
config_vars {
FOO = "bar"
}
}`, appName, org)
}
| [
"\"HEROKU_ORGANIZATION\""
] | [] | [
"HEROKU_ORGANIZATION"
] | [] | ["HEROKU_ORGANIZATION"] | go | 1 | 0 | |
account-service/internal/connections.go | package internal
import (
"github.com/ProjectReferral/Get-me-in/account-service/configs"
"github.com/ProjectReferral/Get-me-in/pkg/dynamodb"
"github.com/aws/aws-sdk-go/aws/credentials"
)
func ConnectToDynamoDB(){
c := credentials.NewSharedCredentials("", "default")
err := dynamodb.Connect(c, configs.EU_WEST_2)
if err != nil {
panic(err)
}
} | [] | [] | [] | [] | [] | go | null | null | null |
cmd/apiserver/main.go | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// This server implements the device facing APIs for exchanging verification codes
// for tokens and tokens for certificates.
package main
import (
"context"
"crypto/sha1"
"fmt"
"net/http"
"os"
"strconv"
"github.com/google/exposure-notifications-verification-server/pkg/buildinfo"
"github.com/google/exposure-notifications-verification-server/pkg/cache"
"github.com/google/exposure-notifications-verification-server/pkg/config"
"github.com/google/exposure-notifications-verification-server/pkg/controller"
"github.com/google/exposure-notifications-verification-server/pkg/controller/certapi"
"github.com/google/exposure-notifications-verification-server/pkg/controller/middleware"
"github.com/google/exposure-notifications-verification-server/pkg/controller/verifyapi"
"github.com/google/exposure-notifications-verification-server/pkg/database"
"github.com/google/exposure-notifications-verification-server/pkg/ratelimit"
"github.com/google/exposure-notifications-verification-server/pkg/ratelimit/limitware"
"github.com/google/exposure-notifications-verification-server/pkg/render"
"github.com/google/exposure-notifications-server/pkg/keys"
"github.com/google/exposure-notifications-server/pkg/logging"
"github.com/google/exposure-notifications-server/pkg/observability"
"github.com/google/exposure-notifications-server/pkg/server"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"github.com/mikehelmick/go-chaff"
"github.com/sethvargo/go-signalcontext"
)
func main() {
ctx, done := signalcontext.OnInterrupt()
debug, _ := strconv.ParseBool(os.Getenv("LOG_DEBUG"))
logger := logging.NewLogger(debug)
logger = logger.With("build_id", buildinfo.BuildID)
logger = logger.With("build_tag", buildinfo.BuildTag)
ctx = logging.WithLogger(ctx, logger)
err := realMain(ctx)
done()
if err != nil {
logger.Fatal(err)
}
logger.Info("successful shutdown")
}
func realMain(ctx context.Context) error {
logger := logging.FromContext(ctx)
cfg, err := config.NewAPIServerConfig(ctx)
if err != nil {
return fmt.Errorf("failed to process config: %w", err)
}
// Setup monitoring
logger.Info("configuring observability exporter")
oeConfig := cfg.ObservabilityExporterConfig()
oe, err := observability.NewFromEnv(ctx, oeConfig)
if err != nil {
return fmt.Errorf("unable to create ObservabilityExporter provider: %w", err)
}
if err := oe.StartExporter(); err != nil {
return fmt.Errorf("error initializing observability exporter: %w", err)
}
defer oe.Close()
logger.Infow("observability exporter", "config", oeConfig)
// Setup cacher
cacher, err := cache.CacherFor(ctx, &cfg.Cache, cache.HMACKeyFunc(sha1.New, cfg.Cache.HMACKey))
if err != nil {
return fmt.Errorf("failed to create cacher: %w", err)
}
defer cacher.Close()
// Setup database
db, err := cfg.Database.Load(ctx)
if err != nil {
return fmt.Errorf("failed to load database config: %w", err)
}
if err := db.OpenWithCacher(ctx, cacher); err != nil {
return fmt.Errorf("failed to connect to database: %w", err)
}
defer db.Close()
// Setup signers
tokenSigner, err := keys.KeyManagerFor(ctx, &cfg.TokenSigning.Keys)
if err != nil {
return fmt.Errorf("failed to create token key manager: %w", err)
}
certificateSigner, err := keys.KeyManagerFor(ctx, &cfg.CertificateSigning.Keys)
if err != nil {
return fmt.Errorf("failed to create certificate key manager: %w", err)
}
// Create the router
r := mux.NewRouter()
// Rate limiting
limiterStore, err := ratelimit.RateLimiterFor(ctx, &cfg.RateLimit)
if err != nil {
return fmt.Errorf("failed to create limiter: %w", err)
}
defer limiterStore.Close(ctx)
httplimiter, err := limitware.NewMiddleware(ctx, limiterStore,
limitware.APIKeyFunc(ctx, db, "apiserver:ratelimit:", cfg.RateLimit.HMACKey),
limitware.AllowOnError(false))
if err != nil {
return fmt.Errorf("failed to create limiter middleware: %w", err)
}
rateLimit := httplimiter.Handle
// Install common security headers
r.Use(middleware.SecureHeaders(ctx, cfg.DevMode, "json"))
// Enable debug headers
processDebug := middleware.ProcessDebug(ctx)
r.Use(processDebug)
// Create the renderer
h, err := render.New(ctx, "", cfg.DevMode)
if err != nil {
return fmt.Errorf("failed to create renderer: %w", err)
}
// Install the rate limiting first. In this case, we want to limit by key
// first to reduce the chance of a database lookup.
r.Use(rateLimit)
// Other common middlewares
requireAPIKey := middleware.RequireAPIKey(ctx, cacher, db, h, []database.APIKeyType{
database.APIKeyTypeDevice,
})
processFirewall := middleware.ProcessFirewall(ctx, h, "apiserver")
r.Handle("/health", controller.HandleHealthz(ctx, &cfg.Database, h)).Methods("GET")
{
sub := r.PathPrefix("/api").Subrouter()
sub.Use(requireAPIKey)
sub.Use(processFirewall)
// POST /api/verify
verifyChaff := chaff.New()
defer verifyChaff.Close()
verifyapiController, err := verifyapi.New(ctx, cfg, db, h, tokenSigner)
if err != nil {
return fmt.Errorf("failed to create verify api controller: %w", err)
}
sub.Handle("/verify", handleChaff(verifyChaff, verifyapiController.HandleVerify())).Methods("POST")
// POST /api/certificate
certChaff := chaff.New()
defer certChaff.Close()
certapiController, err := certapi.New(ctx, cfg, db, cacher, certificateSigner, h)
if err != nil {
return fmt.Errorf("failed to create certapi controller: %w", err)
}
sub.Handle("/certificate", handleChaff(certChaff, certapiController.HandleCertificate())).Methods("POST")
}
srv, err := server.New(cfg.Port)
if err != nil {
return fmt.Errorf("failed to create server: %w", err)
}
logger.Infow("server listening", "port", cfg.Port)
return srv.ServeHTTPHandler(ctx, handlers.CombinedLoggingHandler(os.Stdout, r))
}
func handleChaff(tracker *chaff.Tracker, next http.Handler) http.Handler {
return tracker.HandleTrack(chaff.HeaderDetector("X-Chaff"), next)
}
| [
"\"LOG_DEBUG\""
] | [] | [
"LOG_DEBUG"
] | [] | ["LOG_DEBUG"] | go | 1 | 0 | |
sock-merchant/main.go | package main
import (
"bufio"
"fmt"
"io"
"os"
"strconv"
"strings"
)
// Complete the sockMerchant function below.
func sockMerchant(n int, ar []int) int {
counter := make(map[int]int)
for i := int(0); i < n; i++ {
counter[ar[i]] += 1
}
numPairs := 0
for _, v := range counter {
numPairs += v / 2
}
return numPairs
}
func main() {
reader := bufio.NewReaderSize(os.Stdin, 1024*1024)
stdout, err := os.Create(os.Getenv("OUTPUT_PATH"))
checkError(err)
defer stdout.Close()
writer := bufio.NewWriterSize(stdout, 1024*1024)
nTemp, err := strconv.ParseInt(readLine(reader), 10, 64)
checkError(err)
n := int(nTemp)
arTemp := strings.Split(readLine(reader), " ")
var ar []int
for i := 0; i < int(n); i++ {
arItemTemp, err := strconv.ParseInt(arTemp[i], 10, 64)
checkError(err)
arItem := int(arItemTemp)
ar = append(ar, arItem)
}
result := sockMerchant(n, ar)
fmt.Fprintf(writer, "%d\n", result)
writer.Flush()
}
func readLine(reader *bufio.Reader) string {
str, _, err := reader.ReadLine()
if err == io.EOF {
return ""
}
return strings.TrimRight(string(str), "\r\n")
}
func checkError(err error) {
if err != nil {
panic(err)
}
}
| [
"\"OUTPUT_PATH\""
] | [] | [
"OUTPUT_PATH"
] | [] | ["OUTPUT_PATH"] | go | 1 | 0 | |
goal-notifier/main.go | // Program goal-notifier is a AWS Lambda function that's invoked via DynamoDB stream events,
// processes the added goal and sends Slack notifications to configred Slack webhook URLs.
package main
import (
"context"
"encoding/json"
"log"
"os"
"strings"
"time"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
"github.com/aws/aws-sdk-go/service/dynamodb"
"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute"
"github.com/bluele/slack"
"github.com/pawelad/just-scored/just-scored"
)
// UnmarshalStreamImage is a helper function that unmarshalls a map of DynamoDB
// fields (i.e. record.Change.NewImage) onto passed struct pointer.
// It's needed because dynamodbattribute.UnmarshalMap takes dynamodb.AttributeValue
// and record.Change.NewImage returns events.DynamoDBAttributeValue.
//
// Taken from: https://stackoverflow.com/a/50017398/3023841
func UnmarshalStreamImage(attribute map[string]events.DynamoDBAttributeValue, out interface{}) error {
dbAttrMap := make(map[string]*dynamodb.AttributeValue)
for k, v := range attribute {
var dbAttr dynamodb.AttributeValue
bytes, marshalErr := v.MarshalJSON()
if marshalErr != nil {
return marshalErr
}
json.Unmarshal(bytes, &dbAttr)
dbAttrMap[k] = &dbAttr
}
return dynamodbattribute.UnmarshalMap(dbAttrMap, out)
}
// SendGoalNotification sends a scored goal notification to passed Slack
// webhook URL and sets it's DB processed value.
func SendGoalNotification(url string, goal *justscored.Goal) error {
slackWebhook := slack.NewWebHook(url)
webhookPayload := slack.WebHookPostPayload{
Text: goal.ToSlackMessage(),
IconEmoji: ":soccer:",
}
err := slackWebhook.PostMessage(&webhookPayload)
if err != nil {
log.Print(err)
return err
}
return nil
}
// Handler is the AWS Lambda entry point
func Handler(ctx context.Context, event events.DynamoDBEvent) {
var goals []*justscored.Goal
// SLACK_WEBHOOK_URLS is a comma separated list of webhook URLs
slackWebhookURLs := strings.Split(os.Getenv("SLACK_WEBHOOK_URLS"), ",")
// Convert the DynamoDB event to a list of goals
for _, record := range event.Records {
log.Printf("Processing request data for event ID '%s' (%s).", record.EventID, record.EventName)
// We only care about inserts
if record.EventName != string(events.DynamoDBOperationTypeInsert) {
return
}
var goal justscored.Goal
err := UnmarshalStreamImage(record.Change.NewImage, &goal)
if err != nil {
log.Print(err)
}
// Only add non-processed goals
if goal.EventID != 0 && goal.Processed == false {
goals = append(goals, &goal)
}
}
// Send goals notifications to all configured Slack webhook URLs
for _, goal := range goals {
var slackErr error
log.Printf("Sending Slack notifications for goal '%+v'", goal)
for _, url := range slackWebhookURLs {
log.Printf("Sending goal notification to: '%s'", url)
// TODO: Use goroutines and channels
slackErr = SendGoalNotification(url, goal)
}
goal.SetDBValue("Processed", true)
// TODO: What if the *last* webhook POST fails?
if slackErr == nil {
goal.SetDBValue("NotificationSentAt", time.Now().UTC())
}
}
}
func main() {
lambda.Start(Handler)
}
| [
"\"SLACK_WEBHOOK_URLS\""
] | [] | [
"SLACK_WEBHOOK_URLS"
] | [] | ["SLACK_WEBHOOK_URLS"] | go | 1 | 0 | |
main.go | package main
import (
"flag"
"log"
"os"
"regexp"
dingtalk "github.com/hugozhu/godingtalk"
)
var img *bool
var f *string
func init() {
img = flag.Bool("img", false, "Sending Image")
f = flag.String("f", "", "File Path")
flag.Parse()
}
func stripeMarkdown(str string) string {
str = regexp.MustCompile("[*|#]+").ReplaceAllString(str, "")
str = regexp.MustCompile("\\s+").ReplaceAllString(str, " ")
str = regexp.MustCompile("^ ").ReplaceAllString(str, "")
return str
}
func main() {
c := dingtalk.NewDingTalkClient(os.Getenv("corpid"), os.Getenv("corpsecret"))
c.RefreshAccessToken()
var title string
var message string
if *img {
f, err := os.Open(*f)
defer f.Close()
if err != nil {
log.Fatal(err)
}
m, err := c.UploadMedia("image", "screenshot.jpg", f)
if err != nil {
log.Fatal(err)
}
//log.Printf("%v %v %v", m.MediaID, *f, err)
markdown := "![Screenshot](" + m.MediaID + ")"
title = "Screenshot"
message = markdown
} else {
title = stripeMarkdown(os.Args[1])
message = os.Args[1]
}
resp, err := c.SendRobotMarkdownMessage(os.Getenv("token"), title, message)
if err!=nil {
panic(err)
} else {
log.Println(resp)
}
}
| [
"\"corpid\"",
"\"corpsecret\"",
"\"token\""
] | [] | [
"token",
"corpid",
"corpsecret"
] | [] | ["token", "corpid", "corpsecret"] | go | 3 | 0 | |
pkg/jx/cmd/step_post_build.go | package cmd
import (
"io"
"fmt"
"os"
"os/exec"
"strings"
"bufio"
"path/filepath"
"github.com/jenkins-x/jx/pkg/jx/cmd/templates"
cmdutil "github.com/jenkins-x/jx/pkg/jx/cmd/util"
"github.com/jenkins-x/jx/pkg/kube"
"github.com/jenkins-x/jx/pkg/log"
"github.com/jenkins-x/jx/pkg/util"
"github.com/spf13/cobra"
)
// StepPostBuildOptions contains the command line flags
type StepPostBuildOptions struct {
StepOptions
FullImageName string
OutputFile string
}
type anchoreDetails struct {
URL string
Username string
Password string
}
var (
StepPostBuildLong = templates.LongDesc(`
This pipeline step performs post build actions such as CVE analysis
`)
StepPostBuildExample = templates.Examples(`
jx step post build
`)
)
const podAnnotations = `
podAnnotations:
jenkins-x.io/cve-image-id: %s
`
func NewCmdStepPostBuild(f cmdutil.Factory, out io.Writer, errOut io.Writer) *cobra.Command {
options := StepPostBuildOptions{
StepOptions: StepOptions{
CommonOptions: CommonOptions{
Factory: f,
Out: out,
Err: errOut,
},
},
}
cmd := &cobra.Command{
Use: "build",
Short: "Performs post build actions in a pipeline",
Long: StepPostBuildLong,
Example: StepPostBuildExample,
Run: func(cmd *cobra.Command, args []string) {
options.Cmd = cmd
options.Args = args
err := options.Run()
cmdutil.CheckErr(err)
},
}
cmd.Flags().StringVarP(&options.FullImageName, "image", "", "", "The full image name to be analysed including the registry prefix")
return cmd
}
func (o *StepPostBuildOptions) Run() error {
_, _, err := o.KubeClient()
if err != nil {
return fmt.Errorf("error connecting to kubernetes cluster: %v", err)
}
// let's try and add image to CVE provider
err = o.addImageCVEProvider()
if err != nil {
return fmt.Errorf("error adding image to CVE provider: %v", err)
}
return nil
}
func (o *StepPostBuildOptions) addImageCVEProvider() error {
if o.FullImageName == "" {
return util.MissingOption("image")
}
present, err := kube.IsServicePresent(o.kubeClient, kube.AddonServices[defaultAnchoreName], o.currentNamespace)
if err != nil || !present {
log.Infof("no CVE provider running in the current %s namespace so skip adding image to be analysed", o.currentNamespace)
return nil
}
cveProviderHost := os.Getenv("JENKINS_X_DOCKER_REGISTRY_SERVICE_HOST")
if cveProviderHost == "" {
return fmt.Errorf("no JENKINS_X_DOCKER_REGISTRY_SERVICE_HOST env var found")
}
cveProviderPort := os.Getenv("JENKINS_X_DOCKER_REGISTRY_SERVICE_PORT")
if cveProviderPort == "" {
return fmt.Errorf("no JENKINS_X_DOCKER_REGISTRY_SERVICE_PORT env var found")
}
log.Infof("adding image %s to CVE provider\n", o.FullImageName)
imageID, err := o.addImageToAnchore()
if err != nil {
return fmt.Errorf("failed to add image %s to anchore engine: %v\n", o.FullImageName, err)
}
err = o.addImageIDtoHelmValues(imageID)
if err != nil {
return fmt.Errorf("failed to add image id %s to helm values: %v\n", imageID, err)
}
// todo use image id to annotate pods during environments helm install / upgrade
// todo then we can use `jx get cve --env staging` and list all CVEs for an environment
log.Infof("anchore image is %s \n", imageID)
return nil
}
func (o *StepPostBuildOptions) addImageToAnchore() (string, error) {
a, err := o.getAnchoreDetails()
if err != nil {
return "", err
}
cmd := exec.Command("anchore-cli", "image", "add", o.FullImageName)
cmd.Env = os.Environ()
cmd.Env = append(cmd.Env, "ANCHORE_CLI_USER="+a.Username)
cmd.Env = append(cmd.Env, "ANCHORE_CLI_PASS="+a.Password)
cmd.Env = append(cmd.Env, "ANCHORE_CLI_URL="+a.URL)
data, err := cmd.CombinedOutput()
text := string(data)
if err != nil {
return "", err
}
scanner := bufio.NewScanner(strings.NewReader(text))
var imageID string
for scanner.Scan() {
if strings.HasPrefix(scanner.Text(), "Image ID:") {
imageID = strings.Replace(scanner.Text(), "Image ID:", "", -1)
imageID = strings.TrimSpace(imageID)
break
}
}
if imageID == "" {
return "", fmt.Errorf("no Image ID returned from Anchore")
}
return imageID, nil
}
func (o *StepPostBuildOptions) getAnchoreDetails() (anchoreDetails, error) {
var a anchoreDetails
secretsList, err := o.LoadPipelineSecrets(kube.ValueKindAddon, kube.ValueKindCVE)
if err != nil {
return a, err
}
if secretsList == nil || len(secretsList.Items) == 0 {
return a, fmt.Errorf("no addon secrets found for kind cve")
}
if len(secretsList.Items) > 1 {
return a, fmt.Errorf("multiple addon secrets found for kind cve, please clean up and leave only one")
}
s := secretsList.Items[0]
a.URL = s.Annotations[kube.AnnotationURL]
if a.URL != "" && s.Data != nil {
a.Username = string(s.Data[kube.SecretDataUsername])
a.Password = string(s.Data[kube.SecretDataPassword])
} else {
return a, fmt.Errorf("secret %s is missing URL or data", s.Name)
}
return a, nil
}
func (o *StepPostBuildOptions) addImageIDtoHelmValues(imageID string) error {
pwd, err := os.Getwd()
if err != nil {
return err
}
charts := filepath.Join(pwd, "charts")
exists, err := util.FileExists(charts)
if err != nil {
return err
}
if !exists {
return fmt.Errorf("no charts folder found are you in the root folder of your project?")
}
// loop through all directories and if there's a values.yaml add image id to the end
err = filepath.Walk(charts, func(path string, f os.FileInfo, err error) error {
if f.IsDir() {
values := filepath.Join(path, "values.yaml")
valuesExist, err := util.FileExists(values)
if err != nil {
return err
}
if valuesExist {
f, err := os.OpenFile(values, os.O_APPEND|os.O_WRONLY, 0600)
if err != nil {
return err
}
defer f.Close()
if _, err = f.WriteString(fmt.Sprintf(podAnnotations, imageID)); err != nil {
return err
}
}
}
return nil
})
if err != nil {
return err
}
return nil
}
| [
"\"JENKINS_X_DOCKER_REGISTRY_SERVICE_HOST\"",
"\"JENKINS_X_DOCKER_REGISTRY_SERVICE_PORT\""
] | [] | [
"JENKINS_X_DOCKER_REGISTRY_SERVICE_PORT",
"JENKINS_X_DOCKER_REGISTRY_SERVICE_HOST"
] | [] | ["JENKINS_X_DOCKER_REGISTRY_SERVICE_PORT", "JENKINS_X_DOCKER_REGISTRY_SERVICE_HOST"] | go | 2 | 0 | |
kowalski/alert_broker_ztf.py | import argparse
from ast import literal_eval
from astropy.io import fits
from astropy.visualization import (
AsymmetricPercentileInterval,
LinearStretch,
LogStretch,
ImageNormalize,
)
import base64
from bson.json_util import loads
import confluent_kafka
from copy import deepcopy
import dask.distributed
import datetime
import fastavro
import gzip
import io
import matplotlib.pyplot as plt
import multiprocessing
import numpy as np
import os
import pandas as pd
import pathlib
import requests
from requests.packages.urllib3.util.retry import Retry
import subprocess
import sys
import tensorflow as tf
from tensorflow.keras.models import load_model
import threading
import time
import traceback
from typing import Mapping, Optional, Sequence
from utils import (
deg2dms,
deg2hms,
great_circle_distance,
in_ellipse,
init_db_sync,
load_config,
log,
memoize,
Mongo,
radec2lb,
time_stamp,
timer,
TimeoutHTTPAdapter,
ZTFAlert,
)
tf.config.optimizer.set_jit(True)
""" load config and secrets """
config = load_config(config_file="config.yaml")["kowalski"]
def read_schema_data(bytes_io):
"""
Read data that already has an Avro schema.
:param bytes_io: `_io.BytesIO` Data to be decoded.
:return: `dict` Decoded data.
"""
bytes_io.seek(0)
message = fastavro.reader(bytes_io)
return message
class EopError(Exception):
"""
Exception raised when reaching end of a Kafka topic partition.
"""
def __init__(self, msg):
"""
:param msg: The Kafka message result from consumer.poll()
"""
message = (
f"{time_stamp()}: topic:{msg.topic()}, partition:{msg.partition()}, "
f"status:end, offset:{msg.offset()}, key:{str(msg.key())}\n"
)
self.message = message
def __str__(self):
return self.message
def make_photometry(alert: dict, jd_start: float = None):
"""
Make a de-duplicated pandas.DataFrame with photometry of alert['objectId']
:param alert: ZTF alert packet/dict
:param jd_start:
:return:
"""
alert = deepcopy(alert)
df_candidate = pd.DataFrame(alert["candidate"], index=[0])
df_prv_candidates = pd.DataFrame(alert["prv_candidates"])
df_light_curve = pd.concat(
[df_candidate, df_prv_candidates], ignore_index=True, sort=False
)
ztf_filters = {1: "ztfg", 2: "ztfr", 3: "ztfi"}
df_light_curve["ztf_filter"] = df_light_curve["fid"].apply(lambda x: ztf_filters[x])
df_light_curve["magsys"] = "ab"
df_light_curve["mjd"] = df_light_curve["jd"] - 2400000.5
df_light_curve["mjd"] = df_light_curve["mjd"].apply(lambda x: np.float64(x))
df_light_curve["magpsf"] = df_light_curve["magpsf"].apply(lambda x: np.float32(x))
df_light_curve["sigmapsf"] = df_light_curve["sigmapsf"].apply(
lambda x: np.float32(x)
)
df_light_curve = (
df_light_curve.drop_duplicates(subset=["mjd", "magpsf"])
.reset_index(drop=True)
.sort_values(by=["mjd"])
)
# filter out bad data:
mask_good_diffmaglim = df_light_curve["diffmaglim"] > 0
df_light_curve = df_light_curve.loc[mask_good_diffmaglim]
# convert from mag to flux
# step 1: calculate the coefficient that determines whether the
# flux should be negative or positive
coeff = df_light_curve["isdiffpos"].apply(
lambda x: 1.0 if x in [True, 1, "y", "Y", "t", "1"] else -1.0
)
# step 2: calculate the flux normalized to an arbitrary AB zeropoint of
# 23.9 (results in flux in uJy)
df_light_curve["flux"] = coeff * 10 ** (-0.4 * (df_light_curve["magpsf"] - 23.9))
# step 3: separate detections from non detections
detected = np.isfinite(df_light_curve["magpsf"])
undetected = ~detected
# step 4: calculate the flux error
df_light_curve["fluxerr"] = None # initialize the column
# step 4a: calculate fluxerr for detections using sigmapsf
df_light_curve.loc[detected, "fluxerr"] = np.abs(
df_light_curve.loc[detected, "sigmapsf"]
* df_light_curve.loc[detected, "flux"]
* np.log(10)
/ 2.5
)
# step 4b: calculate fluxerr for non detections using diffmaglim
df_light_curve.loc[undetected, "fluxerr"] = (
10 ** (-0.4 * (df_light_curve.loc[undetected, "diffmaglim"] - 23.9)) / 5.0
) # as diffmaglim is the 5-sigma depth
# step 5: set the zeropoint and magnitude system
df_light_curve["zp"] = 23.9
df_light_curve["zpsys"] = "ab"
# only "new" photometry requested?
if jd_start is not None:
w_after_jd = df_light_curve["jd"] > jd_start
df_light_curve = df_light_curve.loc[w_after_jd]
return df_light_curve
def make_thumbnail(alert, ttype: str, ztftype: str):
"""
Convert lossless FITS cutouts from ZTF alerts into PNGs
:param alert: ZTF alert packet/dict
:param ttype: <new|ref|sub>
:param ztftype: <Science|Template|Difference>
:return:
"""
alert = deepcopy(alert)
cutout_data = alert[f"cutout{ztftype}"]["stampData"]
with gzip.open(io.BytesIO(cutout_data), "rb") as f:
with fits.open(io.BytesIO(f.read())) as hdu:
# header = hdu[0].header
data_flipped_y = np.flipud(hdu[0].data)
# fixme: png, switch to fits eventually
buff = io.BytesIO()
plt.close("all")
fig = plt.figure()
fig.set_size_inches(4, 4, forward=False)
ax = plt.Axes(fig, [0.0, 0.0, 1.0, 1.0])
ax.set_axis_off()
fig.add_axes(ax)
# replace nans with median:
img = np.array(data_flipped_y)
# replace dubiously large values
xl = np.greater(np.abs(img), 1e20, where=~np.isnan(img))
if img[xl].any():
img[xl] = np.nan
if np.isnan(img).any():
median = float(np.nanmean(img.flatten()))
img = np.nan_to_num(img, nan=median)
norm = ImageNormalize(
img, stretch=LinearStretch() if ztftype == "Difference" else LogStretch()
)
img_norm = norm(img)
normalizer = AsymmetricPercentileInterval(lower_percentile=1, upper_percentile=100)
vmin, vmax = normalizer.get_limits(img_norm)
ax.imshow(img_norm, cmap="bone", origin="lower", vmin=vmin, vmax=vmax)
plt.savefig(buff, dpi=42)
buff.seek(0)
plt.close("all")
thumb = {
"obj_id": alert["objectId"],
"data": base64.b64encode(buff.read()).decode("utf-8"),
"ttype": ttype,
}
return thumb
""" Alert filters """
def make_triplet(alert, to_tpu: bool = False):
"""
Make an L2-normalized cutout triplet out of a ZTF alert
:param alert:
:param to_tpu:
:return:
"""
cutout_dict = dict()
for cutout in ("science", "template", "difference"):
cutout_data = alert[f"cutout{cutout.capitalize()}"]["stampData"]
# unzip
with gzip.open(io.BytesIO(cutout_data), "rb") as f:
with fits.open(io.BytesIO(f.read())) as hdu:
data = hdu[0].data
# replace nans with zeros
cutout_dict[cutout] = np.nan_to_num(data)
# L2-normalize
cutout_dict[cutout] /= np.linalg.norm(cutout_dict[cutout])
# pad to 63x63 if smaller
shape = cutout_dict[cutout].shape
if shape != (63, 63):
# print(f'Shape of {candid}/{cutout}: {shape}, padding to (63, 63)')
cutout_dict[cutout] = np.pad(
cutout_dict[cutout],
[(0, 63 - shape[0]), (0, 63 - shape[1])],
mode="constant",
constant_values=1e-9,
)
triplet = np.zeros((63, 63, 3))
triplet[:, :, 0] = cutout_dict["science"]
triplet[:, :, 1] = cutout_dict["template"]
triplet[:, :, 2] = cutout_dict["difference"]
if to_tpu:
# Edge TPUs require additional processing
triplet = np.rint(triplet * 128 + 128).astype(np.uint8).flatten()
return triplet
def alert_filter__ml(alert, ml_models: dict = None) -> dict:
"""Execute ML models on a ZTF alert
:param alert:
:param ml_models:
:return:
"""
scores = dict()
if ml_models is not None and len(ml_models) > 0:
try:
with timer("ZTFAlert(alert)"):
ztf_alert = ZTFAlert(alert)
with timer("Prepping features"):
features = np.expand_dims(ztf_alert.data["features"], axis=[0, -1])
triplet = np.expand_dims(ztf_alert.data["triplet"], axis=[0])
# braai
if "braai" in ml_models.keys():
with timer("braai"):
braai = ml_models["braai"]["model"].predict(x=triplet)[0]
scores["braai"] = float(braai)
scores["braai_version"] = ml_models["braai"]["version"]
# acai
for model_name in ("acai_h", "acai_v", "acai_o", "acai_n", "acai_b"):
if model_name in ml_models.keys():
with timer(model_name):
score = ml_models[model_name]["model"].predict(
[features, triplet]
)[0]
scores[model_name] = float(score)
scores[f"{model_name}_version"] = ml_models[model_name][
"version"
]
except Exception as e:
log(str(e))
return scores
# cone search radius:
cone_search_radius = float(config["database"]["xmatch"]["cone_search_radius"])
# convert to rad:
if config["database"]["xmatch"]["cone_search_unit"] == "arcsec":
cone_search_radius *= np.pi / 180.0 / 3600.0
elif config["database"]["xmatch"]["cone_search_unit"] == "arcmin":
cone_search_radius *= np.pi / 180.0 / 60.0
elif config["database"]["xmatch"]["cone_search_unit"] == "deg":
cone_search_radius *= np.pi / 180.0
elif config["database"]["xmatch"]["cone_search_unit"] == "rad":
cone_search_radius *= 1
else:
raise Exception("Unknown cone search unit. Must be in [deg, rad, arcsec, arcmin]")
def alert_filter__xmatch(database, alert) -> dict:
"""
Cross-match alerts
"""
xmatches = dict()
try:
ra_geojson = float(alert["candidate"]["ra"])
# geojson-friendly ra:
ra_geojson -= 180.0
dec_geojson = float(alert["candidate"]["dec"])
""" catalogs """
for catalog in config["database"]["xmatch"]["catalogs"]:
catalog_filter = config["database"]["xmatch"]["catalogs"][catalog]["filter"]
catalog_projection = config["database"]["xmatch"]["catalogs"][catalog][
"projection"
]
object_position_query = dict()
object_position_query["coordinates.radec_geojson"] = {
"$geoWithin": {
"$centerSphere": [[ra_geojson, dec_geojson], cone_search_radius]
}
}
s = database[catalog].find(
{**object_position_query, **catalog_filter}, {**catalog_projection}
)
xmatches[catalog] = list(s)
except Exception as e:
log(str(e))
return xmatches
# cone search radius in deg:
cone_search_radius_clu = 3.0
# convert deg to rad:
cone_search_radius_clu *= np.pi / 180.0
def alert_filter__xmatch_clu(
database, alert, size_margin=3, clu_version="CLU_20190625"
) -> dict:
"""
Run cross-match with the CLU catalog
:param database:
:param alert:
:param size_margin: multiply galaxy size by this much before looking for a match
:param clu_version: CLU catalog version
:return:
"""
xmatches = dict()
try:
ra = float(alert["candidate"]["ra"])
dec = float(alert["candidate"]["dec"])
# geojson-friendly ra:
ra_geojson = float(alert["candidate"]["ra"]) - 180.0
dec_geojson = dec
catalog_filter = {}
catalog_projection = {
"_id": 1,
"name": 1,
"ra": 1,
"dec": 1,
"a": 1,
"b2a": 1,
"pa": 1,
"z": 1,
"sfr_fuv": 1,
"mstar": 1,
"sfr_ha": 1,
"coordinates.radec_str": 1,
}
# first do a coarse search of everything that is around
object_position_query = dict()
object_position_query["coordinates.radec_geojson"] = {
"$geoWithin": {
"$centerSphere": [[ra_geojson, dec_geojson], cone_search_radius_clu]
}
}
galaxies = list(
database[clu_version].find(
{**object_position_query, **catalog_filter}, {**catalog_projection}
)
)
# these guys are very big, so check them separately
M31 = {
"_id": 596900,
"name": "PGC2557",
"ra": 10.6847,
"dec": 41.26901,
"a": 6.35156,
"b2a": 0.32,
"pa": 35.0,
"z": -0.00100100006,
"sfr_fuv": None,
"mstar": 253816876.412914,
"sfr_ha": 0,
"coordinates": {"radec_str": ["00:42:44.3503", "41:16:08.634"]},
}
M33 = {
"_id": 597543,
"name": "PGC5818",
"ra": 23.46204,
"dec": 30.66022,
"a": 2.35983,
"b2a": 0.59,
"pa": 23.0,
"z": -0.000597000006,
"sfr_fuv": None,
"mstar": 4502777.420493,
"sfr_ha": 0,
"coordinates": {"radec_str": ["01:33:50.8900", "30:39:36.800"]},
}
# do elliptical matches
matches = []
for galaxy in galaxies + [M31, M33]:
alpha1, delta01 = galaxy["ra"], galaxy["dec"]
redshift = galaxy["z"]
# By default, set the cross-match radius to 50 kpc at the redshift of the host galaxy
cm_radius = 50.0 * (0.05 / redshift) / 3600
if redshift < 0.01:
# for nearby galaxies and galaxies with negative redshifts, do a 5 arc-minute cross-match
# (cross-match radius would otherwise get un-physically large for nearby galaxies)
cm_radius = 300.0 / 3600
in_galaxy = in_ellipse(ra, dec, alpha1, delta01, cm_radius, 1, 0)
if in_galaxy:
match = galaxy
distance_arcsec = round(
great_circle_distance(ra, dec, alpha1, delta01) * 3600, 2
)
# also add a physical distance parameter for redshifts in the Hubble flow
if redshift > 0.005:
distance_kpc = round(
great_circle_distance(ra, dec, alpha1, delta01)
* 3600
* (redshift / 0.05),
2,
)
else:
distance_kpc = -1
match["coordinates"]["distance_arcsec"] = distance_arcsec
match["coordinates"]["distance_kpc"] = distance_kpc
matches.append(match)
xmatches[clu_version] = matches
except Exception as e:
log(str(e))
return xmatches
def alert_filter__user_defined(
database,
filter_templates,
alert,
catalog: str = "ZTF_alerts",
max_time_ms: int = 500,
) -> list:
"""
Evaluate user-defined filters
:param database:
:param filter_templates:
:param alert:
:param catalog:
:param max_time_ms:
:return:
"""
passed_filters = []
for filter_template in filter_templates:
try:
_filter = deepcopy(filter_template)
# match candid
_filter["pipeline"][0]["$match"]["candid"] = alert["candid"]
filtered_data = list(
database[catalog].aggregate(
_filter["pipeline"], allowDiskUse=False, maxTimeMS=max_time_ms
)
)
# passed filter? then len(passed_filter) must be = 1
if len(filtered_data) == 1:
log(
f'{alert["objectId"]} {alert["candid"]} passed filter {_filter["fid"]}'
)
passed_filters.append(
{
"group_id": _filter["group_id"],
"filter_id": _filter["filter_id"],
"group_name": _filter["group_name"],
"filter_name": _filter["filter_name"],
"fid": _filter["fid"],
"permissions": _filter["permissions"],
"autosave": _filter["autosave"],
"update_annotations": _filter["update_annotations"],
"data": filtered_data[0],
}
)
except Exception as e:
log(
f'Filter {filter_template["fid"]} execution failed on alert {alert["candid"]}: {e}'
)
continue
return passed_filters
def process_alert(record, topic):
"""Alert brokering task run by dask.distributed workers
:param record: decoded alert from IPAC's Kafka stream
:param topic: Kafka stream topic name for bookkeeping
:return:
"""
candid = record["candid"]
objectId = record["objectId"]
# get worker running current task
worker = dask.distributed.get_worker()
alert_worker = worker.plugins["worker-init"].alert_worker
log(f"{topic} {objectId} {candid} {worker.address}")
# return if this alert packet has already been processed and ingested into collection_alerts:
if (
alert_worker.mongo.db[alert_worker.collection_alerts].count_documents(
{"candid": candid}, limit=1
)
== 1
):
return
# candid not in db, ingest decoded avro packet into db
# todo: ?? restructure alerts even further?
# move cutouts to ZTF_alerts_cutouts? reduce the main db size for performance
# group by objectId similar to prv_candidates?? maybe this is too much
with timer(f"Mongification of {objectId} {candid}", alert_worker.verbose > 1):
alert, prv_candidates = alert_worker.alert_mongify(record)
# ML models:
with timer(f"MLing of {objectId} {candid}", alert_worker.verbose > 1):
scores = alert_filter__ml(record, ml_models=alert_worker.ml_models)
alert["classifications"] = scores
with timer(f"Ingesting {objectId} {candid}", alert_worker.verbose > 1):
alert_worker.mongo.insert_one(
collection=alert_worker.collection_alerts, document=alert
)
# prv_candidates: pop nulls - save space
prv_candidates = [
{kk: vv for kk, vv in prv_candidate.items() if vv is not None}
for prv_candidate in prv_candidates
]
# cross-match with external catalogs if objectId not in collection_alerts_aux:
if (
alert_worker.mongo.db[alert_worker.collection_alerts_aux].count_documents(
{"_id": objectId}, limit=1
)
== 0
):
with timer(f"Cross-match of {objectId} {candid}", alert_worker.verbose > 1):
xmatches = alert_filter__xmatch(alert_worker.mongo.db, alert)
# CLU cross-match:
with timer(f"CLU cross-match {objectId} {candid}", alert_worker.verbose > 1):
xmatches = {
**xmatches,
**alert_filter__xmatch_clu(alert_worker.mongo.db, alert),
}
alert_aux = {
"_id": objectId,
"cross_matches": xmatches,
"prv_candidates": prv_candidates,
}
with timer(f"Aux ingesting {objectId} {candid}", alert_worker.verbose > 1):
alert_worker.mongo.insert_one(
collection=alert_worker.collection_alerts_aux, document=alert_aux
)
else:
with timer(f"Aux updating of {objectId} {candid}", alert_worker.verbose > 1):
alert_worker.mongo.db[alert_worker.collection_alerts_aux].update_one(
{"_id": objectId},
{"$addToSet": {"prv_candidates": {"$each": prv_candidates}}},
upsert=True,
)
if config["misc"]["broker"]:
# execute user-defined alert filters
with timer(f"Filtering of {objectId} {candid}", alert_worker.verbose > 1):
passed_filters = alert_filter__user_defined(
alert_worker.mongo.db, alert_worker.filter_templates, alert
)
if alert_worker.verbose > 1:
log(f"{objectId} {candid} number of filters passed: {len(passed_filters)}")
# post to SkyPortal
alert_worker.alert_sentinel_skyportal(alert, prv_candidates, passed_filters)
# clean up after thyself
del record, alert, prv_candidates
class AlertConsumer:
"""
Creates an alert stream Kafka consumer for a given topic.
"""
def __init__(self, topic, dask_client, **kwargs):
self.verbose = kwargs.get("verbose", 2)
self.dask_client = dask_client
# keep track of disconnected partitions
self.num_disconnected_partitions = 0
self.topic = topic
def error_cb(err, _self=self):
log(f"error_cb --------> {err}")
# print(err.code())
if err.code() == -195:
_self.num_disconnected_partitions += 1
if _self.num_disconnected_partitions == _self.num_partitions:
log("All partitions got disconnected, killing thread")
sys.exit()
else:
log(
f"{_self.topic}: disconnected from partition. total: {_self.num_disconnected_partitions}"
)
# 'error_cb': error_cb
kwargs["error_cb"] = error_cb
self.consumer = confluent_kafka.Consumer(**kwargs)
self.num_partitions = 0
def on_assign(consumer, partitions, _self=self):
# force-reset offsets when subscribing to a topic:
for part in partitions:
# -2 stands for beginning and -1 for end
part.offset = -2
# keep number of partitions.
# when reaching end of last partition, kill thread and start from beginning
_self.num_partitions += 1
log(consumer.get_watermark_offsets(part))
self.consumer.subscribe([topic], on_assign=on_assign)
# set up own mongo client
self.collection_alerts = config["database"]["collections"]["alerts_ztf"]
self.mongo = Mongo(
host=config["database"]["host"],
port=config["database"]["port"],
replica_set=config["database"]["replica_set"],
username=config["database"]["username"],
password=config["database"]["password"],
db=config["database"]["db"],
verbose=self.verbose,
)
# create indexes
if config["database"]["build_indexes"]:
for index in config["database"]["indexes"][self.collection_alerts]:
try:
ind = [tuple(ii) for ii in index["fields"]]
self.mongo.db[self.collection_alerts].create_index(
keys=ind,
name=index["name"],
background=True,
unique=index["unique"],
)
except Exception as e:
log(e)
@staticmethod
def decode_message(msg):
"""
Decode Avro message according to a schema.
:param msg: The Kafka message result from consumer.poll()
:return:
"""
message = msg.value()
decoded_msg = message
try:
bytes_io = io.BytesIO(message)
decoded_msg = read_schema_data(bytes_io)
except AssertionError:
decoded_msg = None
except IndexError:
literal_msg = literal_eval(
str(message, encoding="utf-8")
) # works to give bytes
bytes_io = io.BytesIO(literal_msg) # works to give <class '_io.BytesIO'>
decoded_msg = read_schema_data(bytes_io) # yields reader
except Exception:
decoded_msg = message
finally:
return decoded_msg
def poll(self):
"""
Polls Kafka broker to consume a topic.
:return:
"""
msg = self.consumer.poll()
if msg is None:
log("Caught error: msg is None")
if msg.error():
log(f"Caught error: {msg.error()}")
raise EopError(msg)
elif msg is not None:
try:
# decode avro packet
with timer("Decoding alert", self.verbose > 1):
msg_decoded = self.decode_message(msg)
for record in msg_decoded:
# submit only unprocessed alerts:
if (
self.mongo.db[self.collection_alerts].count_documents(
{"candid": record["candid"]}, limit=1
)
== 0
):
with timer(
f"Submitting alert {record['objectId']} {record['candid']} for processing",
self.verbose > 1,
):
future = self.dask_client.submit(
process_alert, record, self.topic, pure=True
)
dask.distributed.fire_and_forget(future)
future.release()
del future
except Exception as e:
log(e)
_err = traceback.format_exc()
log(_err)
class AlertWorker:
"""Tools to handle alert processing: database ingestion, filtering, ml'ing, cross-matches, reporting to SP"""
def __init__(self, **kwargs):
self.verbose = kwargs.get("verbose", 2)
self.config = config
# Kowalski version
path_version_file = pathlib.Path(__file__).parent.absolute() / "version.txt"
version = f"v{self.config['server']['version']}"
if path_version_file.exists():
with open(
pathlib.Path(__file__).parent.absolute() / "version.txt", "r"
) as version_file:
version = version_file.read().strip()
# MongoDB collections to store the alerts:
self.collection_alerts = self.config["database"]["collections"]["alerts_ztf"]
self.collection_alerts_aux = self.config["database"]["collections"][
"alerts_ztf_aux"
]
self.collection_alerts_filter = self.config["database"]["collections"][
"alerts_ztf_filter"
]
self.mongo = Mongo(
host=config["database"]["host"],
port=config["database"]["port"],
replica_set=config["database"]["replica_set"],
username=config["database"]["username"],
password=config["database"]["password"],
db=config["database"]["db"],
verbose=self.verbose,
)
# ML models
self.ml_models = dict()
for model in config["ml_models"]:
try:
model_version = config["ml_models"][model]["version"]
# todo: allow other formats such as SavedModel
model_filepath = os.path.join(
config["path"]["ml_models"], f"{model}.{model_version}.h5"
)
self.ml_models[model] = {
"model": load_model(model_filepath),
"version": model_version,
}
except Exception as e:
log(f"Error loading ML model {model}: {str(e)}")
_err = traceback.format_exc()
log(_err)
continue
# talking to SkyPortal?
if not config["misc"]["broker"]:
return
# session to talk to SkyPortal
self.session = requests.Session()
self.session_headers = {
"Authorization": f"token {config['skyportal']['token']}",
"User-Agent": f"Kowalski {version}",
}
retries = Retry(
total=5,
backoff_factor=2,
status_forcelist=[405, 429, 500, 502, 503, 504],
method_whitelist=["HEAD", "GET", "PUT", "POST", "PATCH"],
)
adapter = TimeoutHTTPAdapter(timeout=5, max_retries=retries)
self.session.mount("https://", adapter)
self.session.mount("http://", adapter)
# get ZTF instrument id
self.instrument_id = 1
with timer("Getting ZTF instrument_id from SkyPortal", self.verbose > 1):
response = self.api_skyportal("GET", "/api/instrument", {"name": "ZTF"})
if response.json()["status"] == "success" and len(response.json()["data"]) > 0:
self.instrument_id = response.json()["data"][0]["id"]
log(f"Got ZTF instrument_id from SkyPortal: {self.instrument_id}")
else:
log("Failed to get ZTF instrument_id from SkyPortal")
raise ValueError("Failed to get ZTF instrument_id from SkyPortal")
# get ZTF alert stream ids to program ids mapping
self.ztf_program_id_to_stream_id = dict()
with timer("Getting ZTF alert stream ids from SkyPortal", self.verbose > 1):
response = self.api_skyportal("GET", "/api/streams")
if response.json()["status"] == "success" and len(response.json()["data"]) > 0:
for stream in response.json()["data"]:
if stream.get("name") == "ZTF Public":
self.ztf_program_id_to_stream_id[1] = stream["id"]
if stream.get("name") == "ZTF Public+Partnership":
self.ztf_program_id_to_stream_id[2] = stream["id"]
if stream.get("name") == "ZTF Public+Partnership+Caltech":
# programid=0 is engineering data
self.ztf_program_id_to_stream_id[0] = stream["id"]
self.ztf_program_id_to_stream_id[3] = stream["id"]
if len(self.ztf_program_id_to_stream_id) != 4:
log("Failed to map ZTF alert stream ids from SkyPortal to program ids")
raise ValueError(
"Failed to map ZTF alert stream ids from SkyPortal to program ids"
)
log(
f"Got ZTF program id to SP stream id mapping: {self.ztf_program_id_to_stream_id}"
)
else:
log("Failed to get ZTF alert stream ids from SkyPortal")
raise ValueError("Failed to get ZTF alert stream ids from SkyPortal")
# filter pipeline upstream: select current alert, ditch cutouts, and merge with aux data
# including archival photometry and cross-matches:
self.filter_pipeline_upstream = config["database"]["filters"][
self.collection_alerts
]
log("Upstream filtering pipeline:")
log(self.filter_pipeline_upstream)
# load *active* user-defined alert filter templates and pre-populate them
active_filters = self.get_active_filters()
self.filter_templates = self.make_filter_templates(active_filters)
# set up watchdog for periodic refresh of the filter templates, in case those change
self.filter_monitor = threading.Thread(target=self.reload_filters)
self.filter_monitor.start()
log("Loaded user-defined filters:")
log(self.filter_templates)
def api_skyportal(self, method: str, endpoint: str, data: Optional[Mapping] = None):
"""Make an API call to a SkyPortal instance
:param method:
:param endpoint:
:param data:
:return:
"""
method = method.lower()
methods = {
"head": self.session.head,
"get": self.session.get,
"post": self.session.post,
"put": self.session.put,
"patch": self.session.patch,
"delete": self.session.delete,
}
if endpoint is None:
raise ValueError("Endpoint not specified")
if method not in ["head", "get", "post", "put", "patch", "delete"]:
raise ValueError(f"Unsupported method: {method}")
if method == "get":
response = methods[method](
f"{config['skyportal']['protocol']}://"
f"{config['skyportal']['host']}:{config['skyportal']['port']}"
f"{endpoint}",
params=data,
headers=self.session_headers,
)
else:
response = methods[method](
f"{config['skyportal']['protocol']}://"
f"{config['skyportal']['host']}:{config['skyportal']['port']}"
f"{endpoint}",
json=data,
headers=self.session_headers,
)
return response
@memoize
def api_skyportal_get_group(self, group_id):
return self.api_skyportal(
"GET", f"/api/groups/{group_id}?includeGroupUsers=False"
)
def get_active_filters(self):
"""
Fetch user-defined filters from own db marked as active
:return:
"""
# todo: query SP to make sure the filters still exist there and we're not out of sync;
# clean up if necessary
return list(
self.mongo.db[config["database"]["collections"]["filters"]].aggregate(
[
{
"$match": {
"catalog": config["database"]["collections"]["alerts_ztf"],
"active": True,
}
},
{
"$project": {
"group_id": 1,
"filter_id": 1,
"permissions": 1,
"autosave": 1,
"update_annotations": 1,
"fv": {
"$arrayElemAt": [
{
"$filter": {
"input": "$fv",
"as": "fvv",
"cond": {
"$eq": ["$$fvv.fid", "$active_fid"]
},
}
},
0,
]
},
}
},
]
)
)
def make_filter_templates(self, active_filters: Sequence):
"""
Make filter templates by adding metadata, prepending upstream aggregation stages and setting permissions
:param active_filters:
:return:
"""
filter_templates = []
for active_filter in active_filters:
try:
# collect additional info from SkyPortal
with timer(
f"Getting info on group id={active_filter['group_id']} from SkyPortal",
self.verbose > 1,
):
response = self.api_skyportal_get_group(active_filter["group_id"])
if self.verbose > 1:
log(response.json())
if response.json()["status"] == "success":
group_name = (
response.json()["data"]["nickname"]
if response.json()["data"]["nickname"] is not None
else response.json()["data"]["name"]
)
filter_name = [
filtr["name"]
for filtr in response.json()["data"]["filters"]
if filtr["id"] == active_filter["filter_id"]
][0]
else:
log(
f"Failed to get info on group id={active_filter['group_id']} from SkyPortal"
)
group_name, filter_name = None, None
# raise ValueError(f"Failed to get info on group id={active_filter['group_id']} from SkyPortal")
log(f"Group name: {group_name}, filter name: {filter_name}")
# prepend upstream aggregation stages:
pipeline = deepcopy(self.filter_pipeline_upstream) + loads(
active_filter["fv"]["pipeline"]
)
# set permissions
pipeline[0]["$match"]["candidate.programid"]["$in"] = active_filter[
"permissions"
]
pipeline[3]["$project"]["prv_candidates"]["$filter"]["cond"]["$and"][0][
"$in"
][1] = active_filter["permissions"]
filter_template = {
"group_id": active_filter["group_id"],
"filter_id": active_filter["filter_id"],
"group_name": group_name,
"filter_name": filter_name,
"fid": active_filter["fv"]["fid"],
"permissions": active_filter["permissions"],
"autosave": active_filter["autosave"],
"update_annotations": active_filter["update_annotations"],
"pipeline": deepcopy(pipeline),
}
filter_templates.append(filter_template)
except Exception as e:
log(
"Failed to generate filter template for "
f"group_id={active_filter['group_id']} filter_id={active_filter['filter_id']}: {e}"
)
continue
return filter_templates
def reload_filters(self):
"""
Helper function to periodically reload filters from SkyPortal
:return:
"""
while True:
time.sleep(60 * 5)
active_filters = self.get_active_filters()
self.filter_templates = self.make_filter_templates(active_filters)
@staticmethod
def alert_mongify(alert: Mapping):
"""
Prepare a raw ZTF alert for ingestion into MongoDB:
- add a placeholder for ML-based classifications
- add coordinates for 2D spherical indexing and compute Galactic coordinates
- cut off the prv_candidates section
:param alert:
:return:
"""
doc = dict(alert)
# let mongo create a unique _id
# placeholders for classifications
doc["classifications"] = dict()
# GeoJSON for 2D indexing
doc["coordinates"] = {}
_ra = doc["candidate"]["ra"]
_dec = doc["candidate"]["dec"]
# string format: H:M:S, D:M:S
_radec_str = [deg2hms(_ra), deg2dms(_dec)]
doc["coordinates"]["radec_str"] = _radec_str
# for GeoJSON, must be lon:[-180, 180], lat:[-90, 90] (i.e. in deg)
_radec_geojson = [_ra - 180.0, _dec]
doc["coordinates"]["radec_geojson"] = {
"type": "Point",
"coordinates": _radec_geojson,
}
# Galactic coordinates l and b
l, b = radec2lb(doc["candidate"]["ra"], doc["candidate"]["dec"])
doc["coordinates"]["l"] = l
doc["coordinates"]["b"] = b
prv_candidates = deepcopy(doc["prv_candidates"])
doc.pop("prv_candidates", None)
if prv_candidates is None:
prv_candidates = []
return doc, prv_candidates
def alert_post_candidate(self, alert: Mapping, filter_ids: Sequence):
"""
Post a ZTF alert as a candidate for filters on SkyPortal
:param alert:
:param filter_ids:
:return:
"""
# post metadata with all filter_ids in single call to /api/candidates
alert_thin = {
"id": alert["objectId"],
"ra": alert["candidate"].get("ra"),
"dec": alert["candidate"].get("dec"),
"score": alert["candidate"].get("drb", alert["candidate"]["rb"]),
"filter_ids": filter_ids,
"passing_alert_id": alert["candid"],
"passed_at": datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S.%f"),
"origin": "Kowalski",
}
if self.verbose > 1:
log(alert_thin)
with timer(
f"Posting metadata of {alert['objectId']} {alert['candid']} to SkyPortal",
self.verbose > 1,
):
response = self.api_skyportal("POST", "/api/candidates", alert_thin)
if response.json()["status"] == "success":
log(f"Posted {alert['objectId']} {alert['candid']} metadata to SkyPortal")
else:
log(
f"Failed to post {alert['objectId']} {alert['candid']} metadata to SkyPortal"
)
log(response.json())
def alert_post_source(self, alert: Mapping, group_ids: Sequence):
"""
Save a ZTF alert as a source to groups on SkyPortal
:param alert:
:param group_ids:
:return:
"""
# save source
alert_thin = {
"id": alert["objectId"],
"group_ids": group_ids,
"origin": "Kowalski",
}
if self.verbose > 1:
log(alert_thin)
with timer(
f"Saving {alert['objectId']} {alert['candid']} as a Source on SkyPortal",
self.verbose > 1,
):
response = self.api_skyportal("POST", "/api/sources", alert_thin)
if response.json()["status"] == "success":
log(f"Saved {alert['objectId']} {alert['candid']} as a Source on SkyPortal")
else:
log(
f"Failed to save {alert['objectId']} {alert['candid']} as a Source on SkyPortal"
)
log(response.json())
def alert_post_annotations(self, alert: Mapping, passed_filters: Sequence):
"""
Post annotations to SkyPortal for an alert that passed user-defined filters
:param alert:
:param passed_filters:
:return:
"""
for passed_filter in passed_filters:
annotations = {
"obj_id": alert["objectId"],
"origin": f"{passed_filter.get('group_name')}:{passed_filter.get('filter_name')}",
"data": passed_filter.get("data", dict()).get("annotations", dict()),
"group_ids": [passed_filter.get("group_id")],
}
if len(annotations["data"]) > 0:
with timer(
f"Posting annotation for {alert['objectId']} {alert['candid']} to SkyPortal",
self.verbose > 1,
):
response = self.api_skyportal(
"POST", "/api/annotation", annotations
)
if response.json()["status"] == "success":
log(f"Posted {alert['objectId']} annotation to SkyPortal")
else:
log(f"Failed to post {alert['objectId']} annotation to SkyPortal")
log(response.json())
def alert_put_annotations(self, alert: Mapping, passed_filters: Sequence):
"""
Update annotations on SkyPortal for an alert that passed user-defined filters
:param alert:
:param passed_filters:
:return:
"""
# first need to learn existing annotation id's and corresponding author id's to use with the PUT call
with timer(
f"Getting annotations for {alert['objectId']} from SkyPortal",
self.verbose > 1,
):
response = self.api_skyportal(
"GET", f"/api/sources/{alert['objectId']}/annotations"
)
if response.json()["status"] == "success":
log(f"Got {alert['objectId']} annotations from SkyPortal")
else:
log(f"Failed to get {alert['objectId']} annotations from SkyPortal")
log(response.json())
return False
existing_annotations = {
annotation["origin"]: {
"annotation_id": annotation["id"],
"author_id": annotation["author_id"],
}
for annotation in response.json()["data"]
}
for passed_filter in passed_filters:
origin = (
f"{passed_filter.get('group_name')}:{passed_filter.get('filter_name')}"
)
# no annotation exists on SkyPortal for this object? just post then
if origin not in existing_annotations:
self.alert_post_annotations(alert, [passed_filter])
continue
annotations = {
"author_id": existing_annotations[origin]["author_id"],
"obj_id": alert["objectId"],
"origin": origin,
"data": passed_filter.get("data", dict()).get("annotations", dict()),
"group_ids": [passed_filter.get("group_id")],
}
if len(annotations["data"]) > 0 and passed_filter.get(
"update_annotations", False
):
with timer(
f"Putting annotation for {alert['objectId']} {alert['candid']} to SkyPortal",
self.verbose > 1,
):
response = self.api_skyportal(
"PUT",
f"/api/annotation/{existing_annotations[origin]['annotation_id']}",
annotations,
)
if response.json()["status"] == "success":
log(f"Posted {alert['objectId']} annotation to SkyPortal")
else:
log(f"Failed to post {alert['objectId']} annotation to SkyPortal")
log(response.json())
def alert_post_thumbnails(self, alert: Mapping):
"""
Post ZTF alert thumbnails to SkyPortal
:param alert:
:return:
"""
for ttype, ztftype in [
("new", "Science"),
("ref", "Template"),
("sub", "Difference"),
]:
with timer(
f"Making {ztftype} thumbnail for {alert['objectId']} {alert['candid']}",
self.verbose > 1,
):
thumb = make_thumbnail(alert, ttype, ztftype)
with timer(
f"Posting {ztftype} thumbnail for {alert['objectId']} {alert['candid']} to SkyPortal",
self.verbose > 1,
):
response = self.api_skyportal("POST", "/api/thumbnail", thumb)
if response.json()["status"] == "success":
log(
f"Posted {alert['objectId']} {alert['candid']} {ztftype} cutout to SkyPortal"
)
else:
log(
f"Failed to post {alert['objectId']} {alert['candid']} {ztftype} cutout to SkyPortal"
)
log(response.json())
def alert_put_photometry(self, alert):
"""PUT photometry to SkyPortal
:param alert:
:return:
"""
with timer(
f"Making alert photometry of {alert['objectId']} {alert['candid']}",
self.verbose > 1,
):
df_photometry = make_photometry(alert)
df_photometry["stream_id"] = df_photometry["programid"].apply(
lambda programid: self.ztf_program_id_to_stream_id[programid]
)
# post photometry by stream_id
for stream_id in set(df_photometry.stream_id.unique()):
stream_id_mask = df_photometry.stream_id == int(stream_id)
photometry = {
"obj_id": alert["objectId"],
"stream_ids": [int(stream_id)],
"instrument_id": self.instrument_id,
"mjd": df_photometry.loc[stream_id_mask, "mjd"].tolist(),
"flux": df_photometry.loc[stream_id_mask, "flux"].tolist(),
"fluxerr": df_photometry.loc[stream_id_mask, "fluxerr"].tolist(),
"zp": df_photometry.loc[stream_id_mask, "zp"].tolist(),
"magsys": df_photometry.loc[stream_id_mask, "zpsys"].tolist(),
"filter": df_photometry.loc[stream_id_mask, "ztf_filter"].tolist(),
"ra": df_photometry.loc[stream_id_mask, "ra"].tolist(),
"dec": df_photometry.loc[stream_id_mask, "dec"].tolist(),
}
if (len(photometry.get("flux", ())) > 0) or (
len(photometry.get("fluxerr", ())) > 0
):
with timer(
f"Posting photometry of {alert['objectId']} {alert['candid']}, "
f"stream_id={stream_id} to SkyPortal",
self.verbose > 1,
):
response = self.api_skyportal("PUT", "/api/photometry", photometry)
if response.json()["status"] == "success":
log(
f"Posted {alert['objectId']} photometry stream_id={stream_id} to SkyPortal"
)
else:
log(
f"Failed to post {alert['objectId']} photometry stream_id={stream_id} to SkyPortal"
)
log(response.json())
def alert_sentinel_skyportal(self, alert, prv_candidates, passed_filters):
"""
Post alerts to SkyPortal, if need be.
Logic:
- check if candidate/source exist on SP
- if candidate does not exist and len(passed_filters) > 0
- post metadata with all filter_ids in single call to /api/candidates
- post full light curve with all group_ids in single call to /api/photometry
- post thumbnails
- if candidate exists:
- get filter_ids of saved candidate from SP
- post to /api/candidates with new_filter_ids, if any
- post alert light curve in single PUT call to /api/photometry specifying stream_ids
- if source exists:
- get groups and check stream access
- decide which points to post to what groups based on permissions
- post alert light curve in single PUT call to /api/photometry specifying stream_ids
:param alert: ZTF_alert with a stripped-off prv_candidates section
:param prv_candidates: could be plain prv_candidates section of an alert, or extended alert history
:param passed_filters: list of filters that alert passed, with their output
:return:
"""
# check if candidate/source exist in SP:
with timer(
f"Checking if {alert['objectId']} is Candidate in SkyPortal",
self.verbose > 1,
):
response = self.api_skyportal(
"HEAD", f"/api/candidates/{alert['objectId']}"
)
is_candidate = response.status_code == 200
if self.verbose > 1:
log(
f"{alert['objectId']} {'is' if is_candidate else 'is not'} Candidate in SkyPortal"
)
with timer(
f"Checking if {alert['objectId']} is Source in SkyPortal", self.verbose > 1
):
response = self.api_skyportal("HEAD", f"/api/sources/{alert['objectId']}")
is_source = response.status_code == 200
if self.verbose > 1:
log(
f"{alert['objectId']} {'is' if is_source else 'is not'} Source in SkyPortal"
)
# obj does not exit in SP:
if (not is_candidate) and (not is_source):
# passed at least one filter?
if len(passed_filters) > 0:
# post candidate
filter_ids = [f.get("filter_id") for f in passed_filters]
self.alert_post_candidate(alert, filter_ids)
# post annotations
self.alert_post_annotations(alert, passed_filters)
# post full light curve
try:
alert["prv_candidates"] = list(
self.mongo.db[self.collection_alerts_aux].find(
{"_id": alert["objectId"]}, {"prv_candidates": 1}, limit=1
)
)[0]["prv_candidates"]
except Exception as e:
# this should never happen, but just in case
log(e)
alert["prv_candidates"] = prv_candidates
self.alert_put_photometry(alert)
# post thumbnails
self.alert_post_thumbnails(alert)
# post source if autosave=True
autosave_group_ids = [
f.get("group_id")
for f in passed_filters
if f.get("autosave", False)
]
if len(autosave_group_ids) > 0:
self.alert_post_source(alert, autosave_group_ids)
# obj exists in SP:
else:
if len(passed_filters) > 0:
filter_ids = [f.get("filter_id") for f in passed_filters]
# post candidate with new filter ids
self.alert_post_candidate(alert, filter_ids)
# put annotations
self.alert_put_annotations(alert, passed_filters)
# already saved as a source?
if is_source:
# get info on the corresponding groups:
with timer(
f"Getting source groups info on {alert['objectId']} from SkyPortal",
self.verbose > 1,
):
response = self.api_skyportal(
"GET", f"/api/sources/{alert['objectId']}/groups"
)
if response.json()["status"] == "success":
existing_groups = response.json()["data"]
existing_group_ids = [g["id"] for g in existing_groups]
# post source if autosave=True and not already saved
autosave_group_ids = [
f.get("group_id")
for f in passed_filters
if f.get("autosave", False)
and (f.get("group_id") not in existing_group_ids)
]
if len(autosave_group_ids) > 0:
self.alert_post_source(alert, autosave_group_ids)
else:
log(f"Failed to get source groups info on {alert['objectId']}")
else:
# post source if autosave=True and not is_source
autosave_group_ids = [
f.get("group_id")
for f in passed_filters
if f.get("autosave", False)
]
if len(autosave_group_ids) > 0:
self.alert_post_source(alert, autosave_group_ids)
# post alert photometry in single call to /api/photometry
alert["prv_candidates"] = prv_candidates
self.alert_put_photometry(alert)
class WorkerInitializer(dask.distributed.WorkerPlugin):
def __init__(self, *args, **kwargs):
self.alert_worker = None
def setup(self, worker: dask.distributed.Worker):
self.alert_worker = AlertWorker()
def topic_listener(
topic,
bootstrap_servers: str,
offset_reset: str = "earliest",
group: str = None,
test: bool = False,
):
"""
Listen to a topic
:param topic:
:param bootstrap_servers:
:param offset_reset:
:param group:
:param test: when testing, terminate once reached end of partition
:return:
"""
# Configure dask client
dask_client = dask.distributed.Client(
address=f"{config['dask']['host']}:{config['dask']['scheduler_port']}"
)
# init each worker with AlertWorker instance
worker_initializer = WorkerInitializer()
dask_client.register_worker_plugin(worker_initializer, name="worker-init")
# Configure consumer connection to Kafka broker
conf = {
"bootstrap.servers": bootstrap_servers,
"default.topic.config": {"auto.offset.reset": offset_reset},
}
if group is not None:
conf["group.id"] = group
else:
conf["group.id"] = os.environ.get("HOSTNAME", "kowalski")
# make it unique:
conf[
"group.id"
] = f"{conf['group.id']}_{datetime.datetime.utcnow().strftime('%Y-%m-%d_%H:%M:%S.%f')}"
# Start alert stream consumer
stream_reader = AlertConsumer(topic, dask_client, **conf)
while True:
try:
# poll!
stream_reader.poll()
except EopError as e:
# Write when reaching end of partition
log(e.message)
if test:
# when testing, terminate once reached end of partition:
sys.exit()
except IndexError:
log("Data cannot be decoded\n")
except UnicodeDecodeError:
log("Unexpected data format received\n")
except KeyboardInterrupt:
log("Aborted by user\n")
sys.exit()
except Exception as e:
log(str(e))
_err = traceback.format_exc()
log(_err)
sys.exit()
def watchdog(obs_date: str = None, test: bool = False):
"""
Watchdog for topic listeners
:param obs_date: observing date: YYYYMMDD
:param test: test mode
:return:
"""
init_db_sync(config=config, verbose=True)
topics_on_watch = dict()
while True:
try:
# get kafka topic names with kafka-topics command
if not test:
# Production Kafka stream at IPAC
kafka_cmd = [
os.path.join(config["path"]["kafka"], "bin", "kafka-topics.sh"),
"--zookeeper",
config["kafka"]["zookeeper"],
"-list",
]
else:
# Local test stream
kafka_cmd = [
os.path.join(config["path"]["kafka"], "bin", "kafka-topics.sh"),
"--zookeeper",
config["kafka"]["zookeeper.test"],
"-list",
]
topics = (
subprocess.run(kafka_cmd, stdout=subprocess.PIPE)
.stdout.decode("utf-8")
.split("\n")[:-1]
)
if obs_date is None:
datestr = datetime.datetime.utcnow().strftime("%Y%m%d")
else:
datestr = obs_date
# as of 20180403, the naming convention is ztf_%Y%m%d_programidN
# exclude ZUDS, ingest separately
topics_tonight = [
t
for t in topics
if (datestr in t) and ("programid" in t) and ("zuds" not in t)
]
log(f"Topics: {topics_tonight}")
for t in topics_tonight:
if t not in topics_on_watch:
log(f"Starting listener thread for {t}")
offset_reset = config["kafka"]["default.topic.config"][
"auto.offset.reset"
]
if not test:
bootstrap_servers = config["kafka"]["bootstrap.servers"]
else:
bootstrap_servers = config["kafka"]["bootstrap.test.servers"]
group = config["kafka"]["group"]
topics_on_watch[t] = multiprocessing.Process(
target=topic_listener,
args=(t, bootstrap_servers, offset_reset, group, test),
)
topics_on_watch[t].daemon = True
topics_on_watch[t].start()
else:
log(f"Performing thread health check for {t}")
try:
if not topics_on_watch[t].is_alive():
log(f"Thread {t} died, removing")
# topics_on_watch[t].terminate()
topics_on_watch.pop(t, None)
else:
log(f"Thread {t} appears normal")
except Exception as _e:
log(f"Failed to perform health check: {_e}")
pass
if test:
time.sleep(120)
# when testing, wait for topic listeners to pull all the data, then break
# fixme: do this more gracefully
for t in topics_on_watch:
topics_on_watch[t].kill()
break
except Exception as e:
log(str(e))
_err = traceback.format_exc()
log(str(_err))
time.sleep(60)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Kowalski's ZTF Alert Broker")
parser.add_argument("--obsdate", help="observing date YYYYMMDD")
parser.add_argument("--test", help="listen to the test stream", action="store_true")
args = parser.parse_args()
watchdog(obs_date=args.obsdate, test=args.test)
| [] | [] | [
"HOSTNAME"
] | [] | ["HOSTNAME"] | python | 1 | 0 | |
utils/alias_win.go | package utils
import (
"bufio"
"io"
"os"
)
//AddAlias will add the alias for the package name specified
func (u *Utility) AddAliasWin(name string, ed string) error {
//Set the alias for Powershell
//--------------------------------
pwshPath := os.Getenv("USERPROFILE") + "/Documents/WindowsPowerShell/"
//Create the powershell directory if it doesnt exist
err := u.MakeDir(pwshPath)
if err != nil {
return err
}
//Open the powershell alias file
file, err := u.OpenFile(pwshPath + "Microsoft.PowerShell_profile.ps1")
if err != nil {
return err
}
alias := "function " + name + "(){ " + ed + "\\packageless.exe run " + name + " $args }\n"
_, err = file.WriteString(alias)
if err != nil {
return err
}
file.Close()
return nil
}
//Remove Alias will remove the alias for the specified package name from the corresponding files
func (u *Utility) RemoveAliasWin(name string, ed string) error {
//PowerShell
//------------------------------------------------
pwshPath := os.Getenv("USERPROFILE") + "/Documents/WindowsPowerShell/"
//Open the powershell profile file
file, err := os.OpenFile(pwshPath+"Microsoft.PowerShell_profile.ps1", os.O_RDWR, 0755)
//Create the newOut array
var newOut []string
if err != nil {
return err
}
reader := bufio.NewReader(file)
//Read the file line by line
for {
line, err := reader.ReadString('\n')
//Check for EOF
if err != nil && err == io.EOF {
break
}
if err != nil {
return err
}
alias := "function " + name + "(){ " + ed + "\\packageless.exe run " + name + " $args }\n"
//if the line is the alias for this package dont include it in the new file
if line != alias {
newOut = append(newOut, line)
}
}
//Close the file
file.Close()
//Recreate the powershell profile file
newFile, err := os.OpenFile(pwshPath+"Microsoft.PowerShell_profile.ps1", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0755)
if err != nil {
return err
}
//Write the contents back to the powershell profile file
for _, line := range newOut {
_, err = newFile.WriteString(line)
if err != nil {
return err
}
}
//Close the file
newFile.Close()
return nil
}
| [
"\"USERPROFILE\"",
"\"USERPROFILE\""
] | [] | [
"USERPROFILE"
] | [] | ["USERPROFILE"] | go | 1 | 0 | |
tools/generate.go | package main
import (
"crypto/sha1"
"fmt"
"io/ioutil"
"net/http"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"text/template"
"github.com/russross/blackfriday"
)
var cacheDir = "/tmp/gobyexample-cache"
var siteDir = "./public"
var pygmentizeBin = "./vendor/pygments/pygmentize"
func check(err error) {
if err != nil {
panic(err)
}
}
func ensureDir(dir string) {
err := os.MkdirAll(dir, 0755)
check(err)
}
func copyFile(src, dst string) {
dat, err := ioutil.ReadFile(src)
check(err)
err = ioutil.WriteFile(dst, dat, 0644)
check(err)
}
func pipe(bin string, arg []string, src string) []byte {
cmd := exec.Command(bin, arg...)
in, err := cmd.StdinPipe()
check(err)
out, err := cmd.StdoutPipe()
check(err)
err = cmd.Start()
check(err)
_, err = in.Write([]byte(src))
check(err)
err = in.Close()
check(err)
bytes, err := ioutil.ReadAll(out)
check(err)
err = cmd.Wait()
check(err)
return bytes
}
func sha1Sum(s string) string {
h := sha1.New()
h.Write([]byte(s))
b := h.Sum(nil)
return fmt.Sprintf("%x", b)
}
func mustReadFile(path string) string {
bytes, err := ioutil.ReadFile(path)
check(err)
return string(bytes)
}
func cachedPygmentize(lex string, src string) string {
ensureDir(cacheDir)
arg := []string{"-l", lex, "-f", "html"}
cachePath := cacheDir + "/pygmentize-" + strings.Join(arg, "-") + "-" + sha1Sum(src)
cacheBytes, cacheErr := ioutil.ReadFile(cachePath)
if cacheErr == nil {
return string(cacheBytes)
}
renderBytes := pipe(pygmentizeBin, arg, src)
writeErr := ioutil.WriteFile(cachePath, renderBytes, 0600)
check(writeErr)
return string(renderBytes)
}
func markdown(src string) string {
return string(blackfriday.MarkdownCommon([]byte(src)))
}
func readLines(path string) []string {
src := mustReadFile(path)
return strings.Split(src, "\n")
}
func mustGlob(glob string) []string {
paths, err := filepath.Glob(glob)
check(err)
return paths
}
func whichLexer(path string) string {
if strings.HasSuffix(path, ".go") {
return "go"
} else if strings.HasSuffix(path, ".sh") {
return "console"
}
panic("No lexer for " + path)
return ""
}
func debug(msg string) {
if os.Getenv("DEBUG") == "1" {
fmt.Fprintln(os.Stderr, msg)
}
}
var docsPat = regexp.MustCompile("^\\s*(\\/\\/|#)\\s")
var todoPat = regexp.MustCompile("\\/\\/ todo: ")
var dashPat = regexp.MustCompile("\\-+")
type Seg struct {
Docs, DocsRendered string
Code, CodeRendered string
CodeEmpty, CodeLeading, CodeRun bool
}
type Example struct {
Id, Name, Title string
GoCode, GoCodeHash, UrlHash string
Segs [][]*Seg
NextExample *Example
}
func parseHashFile(sourcePath string) (string, string) {
lines := readLines(sourcePath)
return lines[0], lines[1]
}
func resetUrlHashFile(codehash, code, sourcePath string) string {
payload := strings.NewReader(code)
resp, err := http.Post("http://play.golang.org/share", "text/plain", payload)
if err != nil {
panic(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
urlkey := string(body)
data := fmt.Sprintf("%s\n%s\n", codehash, urlkey)
ioutil.WriteFile(sourcePath, []byte(data), 0644)
return urlkey
}
func parseSegs(sourcePath string) ([]*Seg, string) {
lines := readLines(sourcePath)
filecontent := strings.Join(lines, "\n")
segs := []*Seg{}
lastSeen := ""
for _, line := range lines {
if line == "" {
lastSeen = ""
continue
}
if todoPat.MatchString(line) {
continue
}
matchDocs := docsPat.MatchString(line)
matchCode := !matchDocs
newDocs := (lastSeen == "") || ((lastSeen != "docs") && (segs[len(segs)-1].Docs != ""))
newCode := (lastSeen == "") || ((lastSeen != "code") && (segs[len(segs)-1].Code != ""))
if newDocs || newCode {
debug("NEWSEG")
}
if matchDocs {
trimmed := docsPat.ReplaceAllString(line, "")
if newDocs {
newSeg := Seg{Docs: trimmed, Code: ""}
segs = append(segs, &newSeg)
} else {
segs[len(segs)-1].Docs = segs[len(segs)-1].Docs + "\n" + trimmed
}
debug("DOCS: " + line)
lastSeen = "docs"
} else if matchCode {
if newCode {
newSeg := Seg{Docs: "", Code: line}
segs = append(segs, &newSeg)
} else {
segs[len(segs)-1].Code = segs[len(segs)-1].Code + "\n" + line
}
debug("CODE: " + line)
lastSeen = "code"
}
}
for i, seg := range segs {
seg.CodeEmpty = (seg.Code == "")
seg.CodeLeading = (i < (len(segs) - 1))
seg.CodeRun = strings.Contains(seg.Code, "package main")
}
return segs, filecontent
}
func parseAndRenderSegs(sourcePath string) ([]*Seg, string) {
segs, filecontent := parseSegs(sourcePath)
lexer := whichLexer(sourcePath)
for _, seg := range segs {
if seg.Docs != "" {
seg.DocsRendered = markdown(seg.Docs)
}
if seg.Code != "" {
seg.CodeRendered = cachedPygmentize(lexer, seg.Code)
}
}
// we are only interested in the 'go' code to pass to play.golang.org
if lexer != "go" {
filecontent = ""
}
return segs, filecontent
}
func parseExamples() []*Example {
exampleNames := readLines("examples.txt")
examples := make([]*Example, 0)
for _, exampleName := range exampleNames {
if (exampleName != "") && !strings.HasPrefix(exampleName, "#") {
exampleNameArr := strings.Split(exampleName, "|")
exampleNameArr[0] = strings.TrimSpace(exampleNameArr[0])
example := Example{Name: exampleNameArr[0]}
if len(exampleNameArr) > 1 {
exampleNameArr[1] = strings.TrimSpace(exampleNameArr[1])
example.Title = exampleNameArr[1]
} else {
example.Title = exampleNameArr[0]
}
exampleId := strings.ToLower(exampleNameArr[0])
exampleId = strings.Replace(exampleId, " ", "-", -1)
exampleId = strings.Replace(exampleId, "/", "-", -1)
exampleId = strings.Replace(exampleId, "'", "", -1)
exampleId = dashPat.ReplaceAllString(exampleId, "-")
example.Id = exampleId
example.Segs = make([][]*Seg, 0)
sourcePaths := mustGlob("examples/" + exampleId + "/*")
for _, sourcePath := range sourcePaths {
if strings.HasSuffix(sourcePath, ".hash") {
example.GoCodeHash, example.UrlHash = parseHashFile(sourcePath)
} else {
sourceSegs, filecontents := parseAndRenderSegs(sourcePath)
if filecontents != "" {
example.GoCode = filecontents
}
example.Segs = append(example.Segs, sourceSegs)
}
}
newCodeHash := sha1Sum(example.GoCode)
if example.GoCodeHash != newCodeHash {
example.UrlHash = resetUrlHashFile(newCodeHash, example.GoCode, "examples/"+example.Id+"/"+example.Id+".hash")
}
examples = append(examples, &example)
}
}
for i, example := range examples {
if i < (len(examples) - 1) {
example.NextExample = examples[i+1]
}
}
return examples
}
func renderIndex(examples []*Example) {
indexTmpl := template.New("index")
_, err := indexTmpl.Parse(mustReadFile("templates/index.tmpl"))
check(err)
indexF, err := os.Create(siteDir + "/index.html")
check(err)
indexTmpl.Execute(indexF, examples)
}
func renderExamples(examples []*Example) {
exampleTmpl := template.New("example")
_, err := exampleTmpl.Parse(mustReadFile("templates/example.tmpl"))
check(err)
for _, example := range examples {
exampleF, err := os.Create(siteDir + "/" + example.Id + ".html")
check(err)
exampleTmpl.Execute(exampleF, example)
}
}
func main() {
copyFile("templates/site.css", siteDir+"/site.css")
copyFile("templates/favicon.ico", siteDir+"/favicon.ico")
copyFile("templates/404.html", siteDir+"/404.html")
copyFile("templates/play.png", siteDir+"/play.png")
copyFile("templates/CNAME", siteDir+"/CNAME")
examples := parseExamples()
renderIndex(examples)
renderExamples(examples)
}
| [
"\"DEBUG\""
] | [] | [
"DEBUG"
] | [] | ["DEBUG"] | go | 1 | 0 | |
train.py | from __future__ import print_function
import yaml
import easydict
import os
import torch
from torch import nn
import torch.nn.functional as F
from torch.autograd import Variable
from apex import amp, optimizers
from utils.utils import log_set, save_model
from utils.loss import ova_loss, open_entropy
from utils.lr_schedule import inv_lr_scheduler
from utils.defaults import get_dataloaders, get_models
from eval import test
import argparse
import random
import numpy as np
parser = argparse.ArgumentParser(
description='Pytorch OVANet',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--config',
type=str,
default='config.yaml',
help='/path/to/config/file')
parser.add_argument('--source_data',
type=str,
default='./utils/source_list.txt',
help='path to source list')
parser.add_argument('--target_data',
type=str,
default='./utils/target_list.txt',
help='path to target list')
parser.add_argument('--log-interval',
type=int,
default=100,
help='how many batches before logging training status')
parser.add_argument('--exp_name',
type=str,
default='office',
help='/path/to/config/file')
parser.add_argument('--network',
type=str,
default='resnet50',
help='network name')
parser.add_argument("--gpu_devices",
type=int,
nargs='+',
default=None,
help="")
parser.add_argument("--no_adapt", default=False, action='store_true')
parser.add_argument("--save_model", default=False, action='store_true')
parser.add_argument("--save_path",
type=str,
default="record/ova_model",
help='/path/to/save/model')
parser.add_argument('--multi',
type=float,
default=0.1,
help='weight factor for adaptation')
parser.add_argument("--seed",
type=int,
default=-1,
help="only positive value enables a fixed seed")
parser.add_argument("--output-dir",
type=str,
default="",
help="output directory")
args = parser.parse_args()
def set_random_seed(seed):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
# set seed
if args.seed >= 0:
print("Setting fixed seed: {}".format(args.seed))
set_random_seed(args.seed)
torch.backends.cudnn.benchmark = False
torch.backends.cudnn.detrministic = True
config_file = args.config
conf = yaml.safe_load(open(config_file))
save_config = yaml.safe_load(open(config_file))
conf = easydict.EasyDict(conf)
gpu_devices = ','.join([str(id) for id in args.gpu_devices])
os.environ["CUDA_VISIBLE_DEVICES"] = gpu_devices
args.cuda = torch.cuda.is_available()
source_data = args.source_data
target_data = args.target_data
evaluation_data = args.target_data
network = args.network
use_gpu = torch.cuda.is_available()
n_share = conf.data.dataset.n_share
n_source_private = conf.data.dataset.n_source_private
n_total = conf.data.dataset.n_total
open = n_total - n_share - n_source_private > 0
num_class = n_share + n_source_private
script_name = os.path.basename(__file__)
inputs = vars(args)
inputs["evaluation_data"] = evaluation_data
inputs["conf"] = conf
inputs["script_name"] = script_name
inputs["num_class"] = num_class
inputs["config_file"] = config_file
source_loader, target_loader, \
test_loader, target_folder = get_dataloaders(inputs)
logname = log_set(inputs)
G, C1, C2, opt_g, opt_c, \
param_lr_g, param_lr_c = get_models(inputs)
ndata = target_folder.__len__()
def train():
criterion = nn.CrossEntropyLoss().cuda()
print('train start!')
data_iter_s = iter(source_loader)
data_iter_t = iter(target_loader)
len_train_source = len(source_loader)
len_train_target = len(target_loader)
for step in range(conf.train.min_step + 1):
G.train()
C1.train()
C2.train()
if step % len_train_target == 0:
data_iter_t = iter(target_loader)
if step % len_train_source == 0:
data_iter_s = iter(source_loader)
data_t = next(data_iter_t)
data_s = next(data_iter_s)
inv_lr_scheduler(param_lr_g,
opt_g,
step,
init_lr=conf.train.lr,
max_iter=conf.train.min_step)
inv_lr_scheduler(param_lr_c,
opt_c,
step,
init_lr=conf.train.lr,
max_iter=conf.train.min_step)
img_s = data_s[0]
label_s = data_s[1]
img_t = data_t[0]
img_s, label_s = Variable(img_s.cuda()), \
Variable(label_s.cuda())
img_t = Variable(img_t.cuda())
opt_g.zero_grad()
opt_c.zero_grad()
C2.module.weight_norm()
## Source loss calculation
feat = G(img_s)
out_s = C1(feat)
out_open = C2(feat)
## source classification loss
loss_s = criterion(out_s, label_s)
## open set loss for source
out_open = out_open.view(out_s.size(0), 2, -1)
open_loss_pos, open_loss_neg = ova_loss(out_open, label_s)
## b x 2 x C
loss_open = 0.5 * (open_loss_pos + open_loss_neg)
## open set loss for target
all = loss_s + loss_open
log_string = 'Train {}/{} \t ' \
'Loss Source: {:.4f} ' \
'Loss Open: {:.4f} ' \
'Loss Open Source Positive: {:.4f} ' \
'Loss Open Source Negative: {:.4f} '
log_values = [
step, conf.train.min_step,
loss_s.item(),
loss_open.item(),
open_loss_pos.item(),
open_loss_neg.item()
]
if not args.no_adapt:
feat_t = G(img_t)
out_open_t = C2(feat_t)
out_open_t = out_open_t.view(img_t.size(0), 2, -1)
ent_open = open_entropy(out_open_t)
all += args.multi * ent_open
log_values.append(ent_open.item())
log_string += "Loss Open Target: {:.6f} "
# zhaoxin add
lr = opt_c.param_groups[0]["lr"]
log_string += "learning rate: {:.4f}"
log_values.append(lr)
with amp.scale_loss(all, [opt_g, opt_c]) as scaled_loss:
scaled_loss.backward()
opt_g.step()
opt_c.step()
opt_g.zero_grad()
opt_c.zero_grad()
if step % conf.train.log_interval == 0:
print(log_string.format(*log_values))
if step > 0 and step % conf.test.test_interval == 0:
acc_o, h_score = test(step,
test_loader,
logname,
n_share,
G, [C1, C2],
open=open)
print("acc all %s h_score %s " % (acc_o, h_score))
G.train()
C1.train()
if args.save_model:
save_path = "%s_%s.pth" % (args.save_path, step)
save_model(G, C1, C2, save_path)
train()
| [] | [] | [
"CUDA_VISIBLE_DEVICES"
] | [] | ["CUDA_VISIBLE_DEVICES"] | python | 1 | 0 | |
src/download_stories.py | import instaloader
import os
class InstaStories():
def __init__(self):
self.obj = instaloader.Instaloader(save_metadata=False,
filename_pattern="{owner_username}_{date_utc}", download_video_thumbnails='')
self.obj.load_session_from_file(os.getenv('SESSION_NAME'))
def update(self):
self.obj.download_stories(None, True, 'stories') | [] | [] | [
"SESSION_NAME"
] | [] | ["SESSION_NAME"] | python | 1 | 0 | |
tests/__init__.py | """Retrieve test functions from submodules."""
from setuptools import find_packages
import pathlib
import importlib
import sys
import os
import re
import json
ROOT = pathlib.Path(__file__).parent.parent
# Filched from nose.config.Config().testMatch
TESTMATCH = re.compile(
os.environ.get('NOSE_TESTMATCH', r'(?:^|[\b_\.%s-])[Tt]est' % os.sep))
# Add ROOT to sys.path if it doesn't exist
for path in sys.path:
if ROOT.resolve() == pathlib.Path(path):
break
else:
sys.path.insert(1, str(ROOT.resolve()))
print(f'inserted {ROOT.resolve()} in sys.path')
# Grab all the tests from subpackages and put them in this module. When
# tests from different modules have matching names (like test_str_base), an
# exception is raise and the conflicting tests are called out.
testmap = {}
failures = {}
fail = False
for subpackage in find_packages(str(pathlib.Path(__file__).parent.resolve())):
module = importlib.import_module(f'tests.{subpackage}')
try:
symbols = module.__dict__['__all__']
except KeyError:
symbols = [x for x in module.__dict__ if not x.startswith('_')]
for symbol in symbols:
func = getattr(module, symbol)
if TESTMATCH.search(symbol) and callable(func):
if symbol in testmap:
fail = True
if symbol in failures:
failures[symbol].append(subpackage)
else:
failures[symbol] = [subpackage]
if not isinstance(testmap[symbol], list):
testmap[symbol] = [testmap[symbol]]
testmap[symbol].append(subpackage)
else:
testmap[symbol] = subpackage
# Import the symbol to this module.
setattr(sys.modules[__name__], symbol, func)
if fail:
failures = {x: y for x, y in testmap.items() if isinstance(y, list)}
raise Exception("Conflicting test names (test name: [modules...]) "
f"{json.dumps(failures, indent=4, sort_keys=True)}")
| [] | [] | [
"NOSE_TESTMATCH"
] | [] | ["NOSE_TESTMATCH"] | python | 1 | 0 | |
vendor/github.com/buildpack/packs/cf/fixtures/go-app/main.go | package main
import (
"fmt"
"html"
"log"
"net/http"
"os"
"strings"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Path: %s", html.EscapeString(r.URL.Path))
})
http.HandleFunc("/env", func(w http.ResponseWriter, _ *http.Request) {
fmt.Fprintln(w, strings.Join(os.Environ(), "\n"))
})
http.HandleFunc("/exit", func(w http.ResponseWriter, _ *http.Request) {
os.Exit(0)
})
fmt.Println("Fixture app about to listen on:", os.Getenv("PORT"))
log.Fatal(http.ListenAndServe(":"+os.Getenv("PORT"), nil))
}
| [
"\"PORT\"",
"\"PORT\""
] | [] | [
"PORT"
] | [] | ["PORT"] | go | 1 | 0 | |
chain/stmgr/utils.go | package stmgr
import (
"bytes"
"context"
"fmt"
"os"
"reflect"
"runtime"
"strings"
"github.com/filecoin-project/go-state-types/big"
"github.com/filecoin-project/go-state-types/network"
cid "github.com/ipfs/go-cid"
cbg "github.com/whyrusleeping/cbor-gen"
"golang.org/x/xerrors"
"github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-bitfield"
"github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/go-state-types/crypto"
"github.com/filecoin-project/go-state-types/rt"
exported0 "github.com/filecoin-project/specs-actors/actors/builtin/exported"
exported2 "github.com/filecoin-project/specs-actors/v2/actors/builtin/exported"
exported3 "github.com/filecoin-project/specs-actors/v3/actors/builtin/exported"
"github.com/filecoin-project/lotus/api"
"github.com/filecoin-project/lotus/chain/actors/builtin"
init_ "github.com/filecoin-project/lotus/chain/actors/builtin/init"
"github.com/filecoin-project/lotus/chain/actors/builtin/market"
"github.com/filecoin-project/lotus/chain/actors/builtin/miner"
"github.com/filecoin-project/lotus/chain/actors/builtin/power"
"github.com/filecoin-project/lotus/chain/actors/policy"
"github.com/filecoin-project/lotus/chain/beacon"
"github.com/filecoin-project/lotus/chain/state"
"github.com/filecoin-project/lotus/chain/store"
"github.com/filecoin-project/lotus/chain/types"
"github.com/filecoin-project/lotus/chain/vm"
"github.com/filecoin-project/lotus/extern/sector-storage/ffiwrapper"
"github.com/filecoin-project/lotus/node/modules/dtypes"
)
func GetNetworkName(ctx context.Context, sm *StateManager, st cid.Cid) (dtypes.NetworkName, error) {
act, err := sm.LoadActorRaw(ctx, init_.Address, st)
if err != nil {
return "", err
}
ias, err := init_.Load(sm.cs.Store(ctx), act)
if err != nil {
return "", err
}
return ias.NetworkName()
}
func GetMinerWorkerRaw(ctx context.Context, sm *StateManager, st cid.Cid, maddr address.Address) (address.Address, error) {
state, err := sm.StateTree(st)
if err != nil {
return address.Undef, xerrors.Errorf("(get sset) failed to load state tree: %w", err)
}
act, err := state.GetActor(maddr)
if err != nil {
return address.Undef, xerrors.Errorf("(get sset) failed to load miner actor: %w", err)
}
mas, err := miner.Load(sm.cs.Store(ctx), act)
if err != nil {
return address.Undef, xerrors.Errorf("(get sset) failed to load miner actor state: %w", err)
}
info, err := mas.Info()
if err != nil {
return address.Undef, xerrors.Errorf("failed to load actor info: %w", err)
}
return vm.ResolveToKeyAddr(state, sm.cs.Store(ctx), info.Worker)
}
func GetPower(ctx context.Context, sm *StateManager, ts *types.TipSet, maddr address.Address) (power.Claim, power.Claim, bool, error) {
return GetPowerRaw(ctx, sm, ts.ParentState(), maddr)
}
func GetPowerRaw(ctx context.Context, sm *StateManager, st cid.Cid, maddr address.Address) (power.Claim, power.Claim, bool, error) {
act, err := sm.LoadActorRaw(ctx, power.Address, st)
if err != nil {
return power.Claim{}, power.Claim{}, false, xerrors.Errorf("(get sset) failed to load power actor state: %w", err)
}
pas, err := power.Load(sm.cs.Store(ctx), act)
if err != nil {
return power.Claim{}, power.Claim{}, false, err
}
tpow, err := pas.TotalPower()
if err != nil {
return power.Claim{}, power.Claim{}, false, err
}
var mpow power.Claim
var minpow bool
if maddr != address.Undef {
var found bool
mpow, found, err = pas.MinerPower(maddr)
if err != nil || !found {
// TODO: return an error when not found?
return power.Claim{}, power.Claim{}, false, err
}
minpow, err = pas.MinerNominalPowerMeetsConsensusMinimum(maddr)
if err != nil {
return power.Claim{}, power.Claim{}, false, err
}
}
return mpow, tpow, minpow, nil
}
func PreCommitInfo(ctx context.Context, sm *StateManager, maddr address.Address, sid abi.SectorNumber, ts *types.TipSet) (*miner.SectorPreCommitOnChainInfo, error) {
act, err := sm.LoadActor(ctx, maddr, ts)
if err != nil {
return nil, xerrors.Errorf("(get sset) failed to load miner actor: %w", err)
}
mas, err := miner.Load(sm.cs.Store(ctx), act)
if err != nil {
return nil, xerrors.Errorf("(get sset) failed to load miner actor state: %w", err)
}
return mas.GetPrecommittedSector(sid)
}
func MinerSectorInfo(ctx context.Context, sm *StateManager, maddr address.Address, sid abi.SectorNumber, ts *types.TipSet) (*miner.SectorOnChainInfo, error) {
act, err := sm.LoadActor(ctx, maddr, ts)
if err != nil {
return nil, xerrors.Errorf("(get sset) failed to load miner actor: %w", err)
}
mas, err := miner.Load(sm.cs.Store(ctx), act)
if err != nil {
return nil, xerrors.Errorf("(get sset) failed to load miner actor state: %w", err)
}
return mas.GetSector(sid)
}
func GetMinerSectorSet(ctx context.Context, sm *StateManager, ts *types.TipSet, maddr address.Address, snos *bitfield.BitField) ([]*miner.SectorOnChainInfo, error) {
act, err := sm.LoadActor(ctx, maddr, ts)
if err != nil {
return nil, xerrors.Errorf("(get sset) failed to load miner actor: %w", err)
}
mas, err := miner.Load(sm.cs.Store(ctx), act)
if err != nil {
return nil, xerrors.Errorf("(get sset) failed to load miner actor state: %w", err)
}
return mas.LoadSectors(snos)
}
func GetSectorsForWinningPoSt(ctx context.Context, nv network.Version, pv ffiwrapper.Verifier, sm *StateManager, st cid.Cid, maddr address.Address, rand abi.PoStRandomness) ([]builtin.SectorInfo, error) {
act, err := sm.LoadActorRaw(ctx, maddr, st)
if err != nil {
return nil, xerrors.Errorf("failed to load miner actor: %w", err)
}
mas, err := miner.Load(sm.cs.Store(ctx), act)
if err != nil {
return nil, xerrors.Errorf("failed to load miner actor state: %w", err)
}
var provingSectors bitfield.BitField
if nv < network.Version7 {
allSectors, err := miner.AllPartSectors(mas, miner.Partition.AllSectors)
if err != nil {
return nil, xerrors.Errorf("get all sectors: %w", err)
}
faultySectors, err := miner.AllPartSectors(mas, miner.Partition.FaultySectors)
if err != nil {
return nil, xerrors.Errorf("get faulty sectors: %w", err)
}
provingSectors, err = bitfield.SubtractBitField(allSectors, faultySectors)
if err != nil {
return nil, xerrors.Errorf("calc proving sectors: %w", err)
}
} else {
provingSectors, err = miner.AllPartSectors(mas, miner.Partition.ActiveSectors)
if err != nil {
return nil, xerrors.Errorf("get active sectors sectors: %w", err)
}
}
numProvSect, err := provingSectors.Count()
if err != nil {
return nil, xerrors.Errorf("failed to count bits: %w", err)
}
// TODO(review): is this right? feels fishy to me
if numProvSect == 0 {
return nil, nil
}
info, err := mas.Info()
if err != nil {
return nil, xerrors.Errorf("getting miner info: %w", err)
}
mid, err := address.IDFromAddress(maddr)
if err != nil {
return nil, xerrors.Errorf("getting miner ID: %w", err)
}
proofType, err := miner.WinningPoStProofTypeFromWindowPoStProofType(nv, info.WindowPoStProofType)
if err != nil {
return nil, xerrors.Errorf("determining winning post proof type: %w", err)
}
ids, err := pv.GenerateWinningPoStSectorChallenge(ctx, proofType, abi.ActorID(mid), rand, numProvSect)
if err != nil {
return nil, xerrors.Errorf("generating winning post challenges: %w", err)
}
iter, err := provingSectors.BitIterator()
if err != nil {
return nil, xerrors.Errorf("iterating over proving sectors: %w", err)
}
// Select winning sectors by _index_ in the all-sectors bitfield.
selectedSectors := bitfield.New()
prev := uint64(0)
for _, n := range ids {
sno, err := iter.Nth(n - prev)
if err != nil {
return nil, xerrors.Errorf("iterating over proving sectors: %w", err)
}
selectedSectors.Set(sno)
prev = n
}
sectors, err := mas.LoadSectors(&selectedSectors)
if err != nil {
return nil, xerrors.Errorf("loading proving sectors: %w", err)
}
out := make([]builtin.SectorInfo, len(sectors))
for i, sinfo := range sectors {
out[i] = builtin.SectorInfo{
SealProof: sinfo.SealProof,
SectorNumber: sinfo.SectorNumber,
SealedCID: sinfo.SealedCID,
}
}
return out, nil
}
func GetMinerSlashed(ctx context.Context, sm *StateManager, ts *types.TipSet, maddr address.Address) (bool, error) {
act, err := sm.LoadActor(ctx, power.Address, ts)
if err != nil {
return false, xerrors.Errorf("failed to load power actor: %w", err)
}
spas, err := power.Load(sm.cs.Store(ctx), act)
if err != nil {
return false, xerrors.Errorf("failed to load power actor state: %w", err)
}
_, ok, err := spas.MinerPower(maddr)
if err != nil {
return false, xerrors.Errorf("getting miner power: %w", err)
}
if !ok {
return true, nil
}
return false, nil
}
func GetStorageDeal(ctx context.Context, sm *StateManager, dealID abi.DealID, ts *types.TipSet) (*api.MarketDeal, error) {
act, err := sm.LoadActor(ctx, market.Address, ts)
if err != nil {
return nil, xerrors.Errorf("failed to load market actor: %w", err)
}
state, err := market.Load(sm.cs.Store(ctx), act)
if err != nil {
return nil, xerrors.Errorf("failed to load market actor state: %w", err)
}
proposals, err := state.Proposals()
if err != nil {
return nil, err
}
proposal, found, err := proposals.Get(dealID)
if err != nil {
return nil, err
} else if !found {
return nil, xerrors.Errorf(
"deal %d not found "+
"- deal may not have completed sealing before deal proposal "+
"start epoch, or deal may have been slashed",
dealID)
}
states, err := state.States()
if err != nil {
return nil, err
}
st, found, err := states.Get(dealID)
if err != nil {
return nil, err
}
if !found {
st = market.EmptyDealState()
}
return &api.MarketDeal{
Proposal: *proposal,
State: *st,
}, nil
}
func ListMinerActors(ctx context.Context, sm *StateManager, ts *types.TipSet) ([]address.Address, error) {
act, err := sm.LoadActor(ctx, power.Address, ts)
if err != nil {
return nil, xerrors.Errorf("failed to load power actor: %w", err)
}
powState, err := power.Load(sm.cs.Store(ctx), act)
if err != nil {
return nil, xerrors.Errorf("failed to load power actor state: %w", err)
}
return powState.ListAllMiners()
}
func ComputeState(ctx context.Context, sm *StateManager, height abi.ChainEpoch, msgs []*types.Message, ts *types.TipSet) (cid.Cid, []*api.InvocResult, error) {
if ts == nil {
ts = sm.cs.GetHeaviestTipSet()
}
base, trace, err := sm.ExecutionTrace(ctx, ts)
if err != nil {
return cid.Undef, nil, err
}
for i := ts.Height(); i < height; i++ {
// handle state forks
base, err = sm.handleStateForks(ctx, base, i, traceFunc(&trace), ts)
if err != nil {
return cid.Undef, nil, xerrors.Errorf("error handling state forks: %w", err)
}
// TODO: should we also run cron here?
}
r := store.NewChainRand(sm.cs, ts.Cids())
vmopt := &vm.VMOpts{
StateBase: base,
Epoch: height,
Rand: r,
Bstore: sm.cs.Blockstore(),
Syscalls: sm.cs.VMSys(),
CircSupplyCalc: sm.GetVMCirculatingSupply,
NtwkVersion: sm.GetNtwkVersion,
BaseFee: ts.Blocks()[0].ParentBaseFee,
LookbackState: LookbackStateGetterForTipset(sm, ts),
}
vmi, err := sm.newVM(ctx, vmopt)
if err != nil {
return cid.Undef, nil, err
}
for i, msg := range msgs {
// TODO: Use the signed message length for secp messages
ret, err := vmi.ApplyMessage(ctx, msg)
if err != nil {
return cid.Undef, nil, xerrors.Errorf("applying message %s: %w", msg.Cid(), err)
}
if ret.ExitCode != 0 {
log.Infof("compute state apply message %d failed (exit: %d): %s", i, ret.ExitCode, ret.ActorErr)
}
}
root, err := vmi.Flush(ctx)
if err != nil {
return cid.Undef, nil, err
}
return root, trace, nil
}
func LookbackStateGetterForTipset(sm *StateManager, ts *types.TipSet) vm.LookbackStateGetter {
return func(ctx context.Context, round abi.ChainEpoch) (*state.StateTree, error) {
_, st, err := GetLookbackTipSetForRound(ctx, sm, ts, round)
if err != nil {
return nil, err
}
return sm.StateTree(st)
}
}
func GetLookbackTipSetForRound(ctx context.Context, sm *StateManager, ts *types.TipSet, round abi.ChainEpoch) (*types.TipSet, cid.Cid, error) {
var lbr abi.ChainEpoch
lb := policy.GetWinningPoStSectorSetLookback(sm.GetNtwkVersion(ctx, round))
if round > lb {
lbr = round - lb
}
// more null blocks than our lookback
if lbr >= ts.Height() {
// This should never happen at this point, but may happen before
// network version 3 (where the lookback was only 10 blocks).
st, _, err := sm.TipSetState(ctx, ts)
if err != nil {
return nil, cid.Undef, err
}
return ts, st, nil
}
// Get the tipset after the lookback tipset, or the next non-null one.
nextTs, err := sm.ChainStore().GetTipsetByHeight(ctx, lbr+1, ts, false)
if err != nil {
return nil, cid.Undef, xerrors.Errorf("failed to get lookback tipset+1: %w", err)
}
if lbr > nextTs.Height() {
return nil, cid.Undef, xerrors.Errorf("failed to find non-null tipset %s (%d) which is known to exist, found %s (%d)", ts.Key(), ts.Height(), nextTs.Key(), nextTs.Height())
}
lbts, err := sm.ChainStore().GetTipSetFromKey(nextTs.Parents())
if err != nil {
return nil, cid.Undef, xerrors.Errorf("failed to resolve lookback tipset: %w", err)
}
return lbts, nextTs.ParentState(), nil
}
func MinerGetBaseInfo(ctx context.Context, sm *StateManager, bcs beacon.Schedule, tsk types.TipSetKey, round abi.ChainEpoch, maddr address.Address, pv ffiwrapper.Verifier) (*api.MiningBaseInfo, error) {
ts, err := sm.ChainStore().LoadTipSet(tsk)
if err != nil {
return nil, xerrors.Errorf("failed to load tipset for mining base: %w", err)
}
prev, err := sm.ChainStore().GetLatestBeaconEntry(ts)
if err != nil {
if os.Getenv("LOTUS_IGNORE_DRAND") != "_yes_" {
return nil, xerrors.Errorf("failed to get latest beacon entry: %w", err)
}
prev = &types.BeaconEntry{}
}
entries, err := beacon.BeaconEntriesForBlock(ctx, bcs, round, ts.Height(), *prev)
if err != nil {
return nil, err
}
rbase := *prev
if len(entries) > 0 {
rbase = entries[len(entries)-1]
}
lbts, lbst, err := GetLookbackTipSetForRound(ctx, sm, ts, round)
if err != nil {
return nil, xerrors.Errorf("getting lookback miner actor state: %w", err)
}
act, err := sm.LoadActorRaw(ctx, maddr, lbst)
if xerrors.Is(err, types.ErrActorNotFound) {
_, err := sm.LoadActor(ctx, maddr, ts)
if err != nil {
return nil, xerrors.Errorf("loading miner in current state: %w", err)
}
return nil, nil
}
if err != nil {
return nil, xerrors.Errorf("failed to load miner actor: %w", err)
}
mas, err := miner.Load(sm.cs.Store(ctx), act)
if err != nil {
return nil, xerrors.Errorf("failed to load miner actor state: %w", err)
}
buf := new(bytes.Buffer)
if err := maddr.MarshalCBOR(buf); err != nil {
return nil, xerrors.Errorf("failed to marshal miner address: %w", err)
}
prand, err := store.DrawRandomness(rbase.Data, crypto.DomainSeparationTag_WinningPoStChallengeSeed, round, buf.Bytes())
if err != nil {
return nil, xerrors.Errorf("failed to get randomness for winning post: %w", err)
}
nv := sm.GetNtwkVersion(ctx, ts.Height())
sectors, err := GetSectorsForWinningPoSt(ctx, nv, pv, sm, lbst, maddr, prand)
if err != nil {
return nil, xerrors.Errorf("getting winning post proving set: %w", err)
}
if len(sectors) == 0 {
return nil, nil
}
mpow, tpow, _, err := GetPowerRaw(ctx, sm, lbst, maddr)
if err != nil {
return nil, xerrors.Errorf("failed to get power: %w", err)
}
info, err := mas.Info()
if err != nil {
return nil, err
}
worker, err := sm.ResolveToKeyAddress(ctx, info.Worker, ts)
if err != nil {
return nil, xerrors.Errorf("resolving worker address: %w", err)
}
// TODO: Not ideal performance...This method reloads miner and power state (already looked up here and in GetPowerRaw)
eligible, err := MinerEligibleToMine(ctx, sm, maddr, ts, lbts)
if err != nil {
return nil, xerrors.Errorf("determining miner eligibility: %w", err)
}
return &api.MiningBaseInfo{
MinerPower: mpow.QualityAdjPower,
NetworkPower: tpow.QualityAdjPower,
Sectors: sectors,
WorkerKey: worker,
SectorSize: info.SectorSize,
PrevBeaconEntry: *prev,
BeaconEntries: entries,
EligibleForMining: eligible,
}, nil
}
type MethodMeta struct {
Name string
Params reflect.Type
Ret reflect.Type
}
var MethodsMap = map[cid.Cid]map[abi.MethodNum]MethodMeta{}
func init() {
// TODO: combine with the runtime actor registry.
var actors []rt.VMActor
actors = append(actors, exported0.BuiltinActors()...)
actors = append(actors, exported2.BuiltinActors()...)
actors = append(actors, exported3.BuiltinActors()...)
for _, actor := range actors {
exports := actor.Exports()
methods := make(map[abi.MethodNum]MethodMeta, len(exports))
// Explicitly add send, it's special.
methods[builtin.MethodSend] = MethodMeta{
Name: "Send",
Params: reflect.TypeOf(new(abi.EmptyValue)),
Ret: reflect.TypeOf(new(abi.EmptyValue)),
}
// Iterate over exported methods. Some of these _may_ be nil and
// must be skipped.
for number, export := range exports {
if export == nil {
continue
}
ev := reflect.ValueOf(export)
et := ev.Type()
// Extract the method names using reflection. These
// method names always match the field names in the
// `builtin.Method*` structs (tested in the specs-actors
// tests).
fnName := runtime.FuncForPC(ev.Pointer()).Name()
fnName = strings.TrimSuffix(fnName[strings.LastIndexByte(fnName, '.')+1:], "-fm")
switch abi.MethodNum(number) {
case builtin.MethodSend:
panic("method 0 is reserved for Send")
case builtin.MethodConstructor:
if fnName != "Constructor" {
panic("method 1 is reserved for Constructor")
}
}
methods[abi.MethodNum(number)] = MethodMeta{
Name: fnName,
Params: et.In(1),
Ret: et.Out(0),
}
}
MethodsMap[actor.Code()] = methods
}
}
func GetReturnType(ctx context.Context, sm *StateManager, to address.Address, method abi.MethodNum, ts *types.TipSet) (cbg.CBORUnmarshaler, error) {
act, err := sm.LoadActor(ctx, to, ts)
if err != nil {
return nil, xerrors.Errorf("(get sset) failed to load miner actor: %w", err)
}
m, found := MethodsMap[act.Code][method]
if !found {
return nil, fmt.Errorf("unknown method %d for actor %s", method, act.Code)
}
return reflect.New(m.Ret.Elem()).Interface().(cbg.CBORUnmarshaler), nil
}
func GetParamType(actCode cid.Cid, method abi.MethodNum) (cbg.CBORUnmarshaler, error) {
m, found := MethodsMap[actCode][method]
if !found {
return nil, fmt.Errorf("unknown method %d for actor %s", method, actCode)
}
return reflect.New(m.Params.Elem()).Interface().(cbg.CBORUnmarshaler), nil
}
func minerHasMinPower(ctx context.Context, sm *StateManager, addr address.Address, ts *types.TipSet) (bool, error) {
pact, err := sm.LoadActor(ctx, power.Address, ts)
if err != nil {
return false, xerrors.Errorf("loading power actor state: %w", err)
}
ps, err := power.Load(sm.cs.Store(ctx), pact)
if err != nil {
return false, err
}
return ps.MinerNominalPowerMeetsConsensusMinimum(addr)
}
func MinerEligibleToMine(ctx context.Context, sm *StateManager, addr address.Address, baseTs *types.TipSet, lookbackTs *types.TipSet) (bool, error) {
hmp, err := minerHasMinPower(ctx, sm, addr, lookbackTs)
// TODO: We're blurring the lines between a "runtime network version" and a "Lotus upgrade epoch", is that unavoidable?
if sm.GetNtwkVersion(ctx, baseTs.Height()) <= network.Version3 {
return hmp, err
}
if err != nil {
return false, err
}
if !hmp {
return false, nil
}
// Post actors v2, also check MinerEligibleForElection with base ts
pact, err := sm.LoadActor(ctx, power.Address, baseTs)
if err != nil {
return false, xerrors.Errorf("loading power actor state: %w", err)
}
pstate, err := power.Load(sm.cs.Store(ctx), pact)
if err != nil {
return false, err
}
mact, err := sm.LoadActor(ctx, addr, baseTs)
if err != nil {
return false, xerrors.Errorf("loading miner actor state: %w", err)
}
mstate, err := miner.Load(sm.cs.Store(ctx), mact)
if err != nil {
return false, err
}
// Non-empty power claim.
if claim, found, err := pstate.MinerPower(addr); err != nil {
return false, err
} else if !found {
return false, err
} else if claim.QualityAdjPower.LessThanEqual(big.Zero()) {
return false, err
}
// No fee debt.
if debt, err := mstate.FeeDebt(); err != nil {
return false, err
} else if !debt.IsZero() {
return false, err
}
// No active consensus faults.
if mInfo, err := mstate.Info(); err != nil {
return false, err
} else if baseTs.Height() <= mInfo.ConsensusFaultElapsed {
return false, nil
}
return true, nil
}
func CheckTotalFIL(ctx context.Context, sm *StateManager, ts *types.TipSet) (abi.TokenAmount, error) {
str, err := state.LoadStateTree(sm.ChainStore().Store(ctx), ts.ParentState())
if err != nil {
return abi.TokenAmount{}, err
}
sum := types.NewInt(0)
err = str.ForEach(func(a address.Address, act *types.Actor) error {
sum = types.BigAdd(sum, act.Balance)
return nil
})
if err != nil {
return abi.TokenAmount{}, err
}
return sum, nil
}
func MakeMsgGasCost(msg *types.Message, ret *vm.ApplyRet) api.MsgGasCost {
return api.MsgGasCost{
Message: msg.Cid(),
GasUsed: big.NewInt(ret.GasUsed),
BaseFeeBurn: ret.GasCosts.BaseFeeBurn,
OverEstimationBurn: ret.GasCosts.OverEstimationBurn,
MinerPenalty: ret.GasCosts.MinerPenalty,
MinerTip: ret.GasCosts.MinerTip,
Refund: ret.GasCosts.Refund,
TotalCost: big.Sub(msg.RequiredFunds(), ret.GasCosts.Refund),
}
}
| [
"\"LOTUS_IGNORE_DRAND\""
] | [] | [
"LOTUS_IGNORE_DRAND"
] | [] | ["LOTUS_IGNORE_DRAND"] | go | 1 | 0 | |
src/runtime/runtime-gdb_test.go | // Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package runtime_test
import (
"bytes"
"fmt"
"internal/testenv"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"strconv"
"strings"
"testing"
)
func checkGdbEnvironment(t *testing.T) {
testenv.MustHaveGoBuild(t)
switch runtime.GOOS {
case "darwin":
t.Skip("gdb does not work on darwin")
case "netbsd":
t.Skip("gdb does not work with threads on NetBSD; see https://golang.org/issue/22893 and https://gnats.netbsd.org/52548")
case "windows":
t.Skip("gdb tests fail on Windows: https://golang.org/issue/22687")
case "linux":
if runtime.GOARCH == "ppc64" {
t.Skip("skipping gdb tests on linux/ppc64; see https://golang.org/issue/17366")
}
if runtime.GOARCH == "mips" {
t.Skip("skipping gdb tests on linux/mips; see https://golang.org/issue/25939")
}
case "freebsd":
t.Skip("skipping gdb tests on FreeBSD; see https://golang.org/issue/29508")
case "aix":
if testing.Short() {
t.Skip("skipping gdb tests on AIX; see https://golang.org/issue/35710")
}
}
if final := os.Getenv("GOROOT_FINAL"); final != "" && runtime.GOROOT() != final {
t.Skip("gdb test can fail with GOROOT_FINAL pending")
}
}
func checkGdbVersion(t *testing.T) {
// Issue 11214 reports various failures with older versions of gdb.
out, err := exec.Command("gdb", "--version").CombinedOutput()
if err != nil {
t.Skipf("skipping: error executing gdb: %v", err)
}
re := regexp.MustCompile(`([0-9]+)\.([0-9]+)`)
matches := re.FindSubmatch(out)
if len(matches) < 3 {
t.Skipf("skipping: can't determine gdb version from\n%s\n", out)
}
major, err1 := strconv.Atoi(string(matches[1]))
minor, err2 := strconv.Atoi(string(matches[2]))
if err1 != nil || err2 != nil {
t.Skipf("skipping: can't determine gdb version: %v, %v", err1, err2)
}
if major < 7 || (major == 7 && minor < 7) {
t.Skipf("skipping: gdb version %d.%d too old", major, minor)
}
t.Logf("gdb version %d.%d", major, minor)
}
func checkGdbPython(t *testing.T) {
if runtime.GOOS == "solaris" || runtime.GOOS == "illumos" {
t.Skip("skipping gdb python tests on illumos and solaris; see golang.org/issue/20821")
}
cmd := exec.Command("gdb", "-nx", "-q", "--batch", "-iex", "python import sys; print('go gdb python support')")
out, err := cmd.CombinedOutput()
if err != nil {
t.Skipf("skipping due to issue running gdb: %v", err)
}
if strings.TrimSpace(string(out)) != "go gdb python support" {
t.Skipf("skipping due to lack of python gdb support: %s", out)
}
}
// checkCleanBacktrace checks that the given backtrace is well formed and does
// not contain any error messages from GDB.
func checkCleanBacktrace(t *testing.T, backtrace string) {
backtrace = strings.TrimSpace(backtrace)
lines := strings.Split(backtrace, "\n")
if len(lines) == 0 {
t.Fatalf("empty backtrace")
}
for i, l := range lines {
if !strings.HasPrefix(l, fmt.Sprintf("#%v ", i)) {
t.Fatalf("malformed backtrace at line %v: %v", i, l)
}
}
// TODO(mundaym): check for unknown frames (e.g. "??").
}
const helloSource = `
import "fmt"
import "runtime"
var gslice []string
func main() {
mapvar := make(map[string]string, 13)
mapvar["abc"] = "def"
mapvar["ghi"] = "jkl"
strvar := "abc"
ptrvar := &strvar
slicevar := make([]string, 0, 16)
slicevar = append(slicevar, mapvar["abc"])
fmt.Println("hi")
runtime.KeepAlive(ptrvar)
_ = ptrvar
gslice = slicevar
runtime.KeepAlive(mapvar)
} // END_OF_PROGRAM
`
func lastLine(src []byte) int {
eop := []byte("END_OF_PROGRAM")
for i, l := range bytes.Split(src, []byte("\n")) {
if bytes.Contains(l, eop) {
return i
}
}
return 0
}
func TestGdbPython(t *testing.T) {
testGdbPython(t, false)
}
func TestGdbPythonCgo(t *testing.T) {
if runtime.GOARCH == "mips" || runtime.GOARCH == "mipsle" || runtime.GOARCH == "mips64" {
testenv.SkipFlaky(t, 18784)
}
testGdbPython(t, true)
}
func testGdbPython(t *testing.T, cgo bool) {
if cgo {
testenv.MustHaveCGO(t)
}
checkGdbEnvironment(t)
t.Parallel()
checkGdbVersion(t)
checkGdbPython(t)
dir, err := ioutil.TempDir("", "go-build")
if err != nil {
t.Fatalf("failed to create temp directory: %v", err)
}
defer os.RemoveAll(dir)
var buf bytes.Buffer
buf.WriteString("package main\n")
if cgo {
buf.WriteString(`import "C"` + "\n")
}
buf.WriteString(helloSource)
src := buf.Bytes()
err = ioutil.WriteFile(filepath.Join(dir, "main.go"), src, 0644)
if err != nil {
t.Fatalf("failed to create file: %v", err)
}
nLines := lastLine(src)
cmd := exec.Command(testenv.GoToolPath(t), "build", "-o", "a.exe", "main.go")
cmd.Dir = dir
out, err := testenv.CleanCmdEnv(cmd).CombinedOutput()
if err != nil {
t.Fatalf("building source %v\n%s", err, out)
}
args := []string{"-nx", "-q", "--batch",
"-iex", "add-auto-load-safe-path " + filepath.Join(runtime.GOROOT(), "src", "runtime"),
"-ex", "set startup-with-shell off",
"-ex", "set print thread-events off",
}
if cgo {
// When we build the cgo version of the program, the system's
// linker is used. Some external linkers, like GNU gold,
// compress the .debug_gdb_scripts into .zdebug_gdb_scripts.
// Until gold and gdb can work together, temporarily load the
// python script directly.
args = append(args,
"-ex", "source "+filepath.Join(runtime.GOROOT(), "src", "runtime", "runtime-gdb.py"),
)
} else {
args = append(args,
"-ex", "info auto-load python-scripts",
)
}
args = append(args,
"-ex", "set python print-stack full",
"-ex", "br main.go:15",
"-ex", "run",
"-ex", "echo BEGIN info goroutines\n",
"-ex", "info goroutines",
"-ex", "echo END\n",
"-ex", "echo BEGIN print mapvar\n",
"-ex", "print mapvar",
"-ex", "echo END\n",
"-ex", "echo BEGIN print strvar\n",
"-ex", "print strvar",
"-ex", "echo END\n",
"-ex", "echo BEGIN info locals\n",
"-ex", "info locals",
"-ex", "echo END\n",
"-ex", "echo BEGIN goroutine 1 bt\n",
"-ex", "goroutine 1 bt",
"-ex", "echo END\n",
"-ex", "echo BEGIN goroutine 2 bt\n",
"-ex", "goroutine 2 bt",
"-ex", "echo END\n",
"-ex", "echo BEGIN goroutine all bt\n",
"-ex", "goroutine all bt",
"-ex", "echo END\n",
"-ex", "clear main.go:15", // clear the previous break point
"-ex", fmt.Sprintf("br main.go:%d", nLines), // new break point at the end of main
"-ex", "c",
"-ex", "echo BEGIN goroutine 1 bt at the end\n",
"-ex", "goroutine 1 bt",
"-ex", "echo END\n",
filepath.Join(dir, "a.exe"),
)
got, _ := exec.Command("gdb", args...).CombinedOutput()
t.Logf("gdb output: %s\n", got)
firstLine := bytes.SplitN(got, []byte("\n"), 2)[0]
if string(firstLine) != "Loading Go Runtime support." {
// This can happen when using all.bash with
// GOROOT_FINAL set, because the tests are run before
// the final installation of the files.
cmd := exec.Command(testenv.GoToolPath(t), "env", "GOROOT")
cmd.Env = []string{}
out, err := cmd.CombinedOutput()
if err != nil && bytes.Contains(out, []byte("cannot find GOROOT")) {
t.Skipf("skipping because GOROOT=%s does not exist", runtime.GOROOT())
}
_, file, _, _ := runtime.Caller(1)
t.Logf("package testing source file: %s", file)
t.Fatalf("failed to load Go runtime support: %s\n%s", firstLine, got)
}
// Extract named BEGIN...END blocks from output
partRe := regexp.MustCompile(`(?ms)^BEGIN ([^\n]*)\n(.*?)\nEND`)
blocks := map[string]string{}
for _, subs := range partRe.FindAllSubmatch(got, -1) {
blocks[string(subs[1])] = string(subs[2])
}
infoGoroutinesRe := regexp.MustCompile(`\*\s+\d+\s+running\s+`)
if bl := blocks["info goroutines"]; !infoGoroutinesRe.MatchString(bl) {
t.Fatalf("info goroutines failed: %s", bl)
}
printMapvarRe1 := regexp.MustCompile(`^\$[0-9]+ = map\[string\]string = {\[(0x[0-9a-f]+\s+)?"abc"\] = (0x[0-9a-f]+\s+)?"def", \[(0x[0-9a-f]+\s+)?"ghi"\] = (0x[0-9a-f]+\s+)?"jkl"}$`)
printMapvarRe2 := regexp.MustCompile(`^\$[0-9]+ = map\[string\]string = {\[(0x[0-9a-f]+\s+)?"ghi"\] = (0x[0-9a-f]+\s+)?"jkl", \[(0x[0-9a-f]+\s+)?"abc"\] = (0x[0-9a-f]+\s+)?"def"}$`)
if bl := blocks["print mapvar"]; !printMapvarRe1.MatchString(bl) &&
!printMapvarRe2.MatchString(bl) {
t.Fatalf("print mapvar failed: %s", bl)
}
strVarRe := regexp.MustCompile(`^\$[0-9]+ = (0x[0-9a-f]+\s+)?"abc"$`)
if bl := blocks["print strvar"]; !strVarRe.MatchString(bl) {
t.Fatalf("print strvar failed: %s", bl)
}
// The exact format of composite values has changed over time.
// For issue 16338: ssa decompose phase split a slice into
// a collection of scalar vars holding its fields. In such cases
// the DWARF variable location expression should be of the
// form "var.field" and not just "field".
// However, the newer dwarf location list code reconstituted
// aggregates from their fields and reverted their printing
// back to its original form.
// Only test that all variables are listed in 'info locals' since
// different versions of gdb print variables in different
// order and with differing amount of information and formats.
if bl := blocks["info locals"]; !strings.Contains(bl, "slicevar") ||
!strings.Contains(bl, "mapvar") ||
!strings.Contains(bl, "strvar") {
t.Fatalf("info locals failed: %s", bl)
}
// Check that the backtraces are well formed.
checkCleanBacktrace(t, blocks["goroutine 1 bt"])
checkCleanBacktrace(t, blocks["goroutine 2 bt"])
checkCleanBacktrace(t, blocks["goroutine 1 bt at the end"])
btGoroutine1Re := regexp.MustCompile(`(?m)^#0\s+(0x[0-9a-f]+\s+in\s+)?main\.main.+at`)
if bl := blocks["goroutine 1 bt"]; !btGoroutine1Re.MatchString(bl) {
t.Fatalf("goroutine 1 bt failed: %s", bl)
}
btGoroutine2Re := regexp.MustCompile(`(?m)^#0\s+(0x[0-9a-f]+\s+in\s+)?runtime.+at`)
if bl := blocks["goroutine 2 bt"]; !btGoroutine2Re.MatchString(bl) {
t.Fatalf("goroutine 2 bt failed: %s", bl)
}
if bl := blocks["goroutine all bt"]; !btGoroutine1Re.MatchString(bl) || !btGoroutine2Re.MatchString(bl) {
t.Fatalf("goroutine all bt failed: %s", bl)
}
btGoroutine1AtTheEndRe := regexp.MustCompile(`(?m)^#0\s+(0x[0-9a-f]+\s+in\s+)?main\.main.+at`)
if bl := blocks["goroutine 1 bt at the end"]; !btGoroutine1AtTheEndRe.MatchString(bl) {
t.Fatalf("goroutine 1 bt at the end failed: %s", bl)
}
}
const backtraceSource = `
package main
//go:noinline
func aaa() bool { return bbb() }
//go:noinline
func bbb() bool { return ccc() }
//go:noinline
func ccc() bool { return ddd() }
//go:noinline
func ddd() bool { return f() }
//go:noinline
func eee() bool { return true }
var f = eee
func main() {
_ = aaa()
}
`
// TestGdbBacktrace tests that gdb can unwind the stack correctly
// using only the DWARF debug info.
func TestGdbBacktrace(t *testing.T) {
if runtime.GOOS == "netbsd" {
testenv.SkipFlaky(t, 15603)
}
checkGdbEnvironment(t)
t.Parallel()
checkGdbVersion(t)
dir, err := ioutil.TempDir("", "go-build")
if err != nil {
t.Fatalf("failed to create temp directory: %v", err)
}
defer os.RemoveAll(dir)
// Build the source code.
src := filepath.Join(dir, "main.go")
err = ioutil.WriteFile(src, []byte(backtraceSource), 0644)
if err != nil {
t.Fatalf("failed to create file: %v", err)
}
cmd := exec.Command(testenv.GoToolPath(t), "build", "-o", "a.exe", "main.go")
cmd.Dir = dir
out, err := testenv.CleanCmdEnv(cmd).CombinedOutput()
if err != nil {
t.Fatalf("building source %v\n%s", err, out)
}
// Execute gdb commands.
args := []string{"-nx", "-batch",
"-iex", "add-auto-load-safe-path " + filepath.Join(runtime.GOROOT(), "src", "runtime"),
"-ex", "set startup-with-shell off",
"-ex", "break main.eee",
"-ex", "run",
"-ex", "backtrace",
"-ex", "continue",
filepath.Join(dir, "a.exe"),
}
got, _ := exec.Command("gdb", args...).CombinedOutput()
// Check that the backtrace matches the source code.
bt := []string{
"eee",
"ddd",
"ccc",
"bbb",
"aaa",
"main",
}
for i, name := range bt {
s := fmt.Sprintf("#%v.*main\\.%v", i, name)
re := regexp.MustCompile(s)
if found := re.Find(got) != nil; !found {
t.Errorf("could not find '%v' in backtrace", s)
t.Fatalf("gdb output:\n%v", string(got))
}
}
}
const autotmpTypeSource = `
package main
type astruct struct {
a, b int
}
func main() {
var iface interface{} = map[string]astruct{}
var iface2 interface{} = []astruct{}
println(iface, iface2)
}
`
// TestGdbAutotmpTypes ensures that types of autotmp variables appear in .debug_info
// See bug #17830.
func TestGdbAutotmpTypes(t *testing.T) {
checkGdbEnvironment(t)
t.Parallel()
checkGdbVersion(t)
if runtime.GOOS == "aix" && testing.Short() {
t.Skip("TestGdbAutotmpTypes is too slow on aix/ppc64")
}
dir, err := ioutil.TempDir("", "go-build")
if err != nil {
t.Fatalf("failed to create temp directory: %v", err)
}
defer os.RemoveAll(dir)
// Build the source code.
src := filepath.Join(dir, "main.go")
err = ioutil.WriteFile(src, []byte(autotmpTypeSource), 0644)
if err != nil {
t.Fatalf("failed to create file: %v", err)
}
cmd := exec.Command(testenv.GoToolPath(t), "build", "-gcflags=all=-N -l", "-o", "a.exe", "main.go")
cmd.Dir = dir
out, err := testenv.CleanCmdEnv(cmd).CombinedOutput()
if err != nil {
t.Fatalf("building source %v\n%s", err, out)
}
// Execute gdb commands.
args := []string{"-nx", "-batch",
"-iex", "add-auto-load-safe-path " + filepath.Join(runtime.GOROOT(), "src", "runtime"),
"-ex", "set startup-with-shell off",
"-ex", "break main.main",
"-ex", "run",
"-ex", "step",
"-ex", "info types astruct",
filepath.Join(dir, "a.exe"),
}
got, _ := exec.Command("gdb", args...).CombinedOutput()
sgot := string(got)
// Check that the backtrace matches the source code.
types := []string{
"[]main.astruct;",
"bucket<string,main.astruct>;",
"hash<string,main.astruct>;",
"main.astruct;",
"hash<string,main.astruct> * map[string]main.astruct;",
}
for _, name := range types {
if !strings.Contains(sgot, name) {
t.Errorf("could not find %s in 'info typrs astruct' output", name)
t.Fatalf("gdb output:\n%v", sgot)
}
}
}
const constsSource = `
package main
const aConstant int = 42
const largeConstant uint64 = ^uint64(0)
const minusOne int64 = -1
func main() {
println("hello world")
}
`
func TestGdbConst(t *testing.T) {
checkGdbEnvironment(t)
t.Parallel()
checkGdbVersion(t)
dir, err := ioutil.TempDir("", "go-build")
if err != nil {
t.Fatalf("failed to create temp directory: %v", err)
}
defer os.RemoveAll(dir)
// Build the source code.
src := filepath.Join(dir, "main.go")
err = ioutil.WriteFile(src, []byte(constsSource), 0644)
if err != nil {
t.Fatalf("failed to create file: %v", err)
}
cmd := exec.Command(testenv.GoToolPath(t), "build", "-gcflags=all=-N -l", "-o", "a.exe", "main.go")
cmd.Dir = dir
out, err := testenv.CleanCmdEnv(cmd).CombinedOutput()
if err != nil {
t.Fatalf("building source %v\n%s", err, out)
}
// Execute gdb commands.
args := []string{"-nx", "-batch",
"-iex", "add-auto-load-safe-path " + filepath.Join(runtime.GOROOT(), "src", "runtime"),
"-ex", "set startup-with-shell off",
"-ex", "break main.main",
"-ex", "run",
"-ex", "print main.aConstant",
"-ex", "print main.largeConstant",
"-ex", "print main.minusOne",
"-ex", "print 'runtime.mSpanInUse'",
"-ex", "print 'runtime._PageSize'",
filepath.Join(dir, "a.exe"),
}
got, _ := exec.Command("gdb", args...).CombinedOutput()
sgot := strings.ReplaceAll(string(got), "\r\n", "\n")
t.Logf("output %q", sgot)
if !strings.Contains(sgot, "\n$1 = 42\n$2 = 18446744073709551615\n$3 = -1\n$4 = 1 '\\001'\n$5 = 8192") {
t.Fatalf("output mismatch")
}
}
const panicSource = `
package main
import "runtime/debug"
func main() {
debug.SetTraceback("crash")
crash()
}
func crash() {
panic("panic!")
}
`
// TestGdbPanic tests that gdb can unwind the stack correctly
// from SIGABRTs from Go panics.
func TestGdbPanic(t *testing.T) {
checkGdbEnvironment(t)
t.Parallel()
checkGdbVersion(t)
dir, err := ioutil.TempDir("", "go-build")
if err != nil {
t.Fatalf("failed to create temp directory: %v", err)
}
defer os.RemoveAll(dir)
// Build the source code.
src := filepath.Join(dir, "main.go")
err = ioutil.WriteFile(src, []byte(panicSource), 0644)
if err != nil {
t.Fatalf("failed to create file: %v", err)
}
cmd := exec.Command(testenv.GoToolPath(t), "build", "-o", "a.exe", "main.go")
cmd.Dir = dir
out, err := testenv.CleanCmdEnv(cmd).CombinedOutput()
if err != nil {
t.Fatalf("building source %v\n%s", err, out)
}
// Execute gdb commands.
args := []string{"-nx", "-batch",
"-iex", "add-auto-load-safe-path " + filepath.Join(runtime.GOROOT(), "src", "runtime"),
"-ex", "set startup-with-shell off",
"-ex", "run",
"-ex", "backtrace",
filepath.Join(dir, "a.exe"),
}
got, _ := exec.Command("gdb", args...).CombinedOutput()
// Check that the backtrace matches the source code.
bt := []string{
`crash`,
`main`,
}
for _, name := range bt {
s := fmt.Sprintf("(#.* .* in )?main\\.%v", name)
re := regexp.MustCompile(s)
if found := re.Find(got) != nil; !found {
t.Errorf("could not find '%v' in backtrace", s)
t.Fatalf("gdb output:\n%v", string(got))
}
}
}
| [
"\"GOROOT_FINAL\""
] | [] | [
"GOROOT_FINAL"
] | [] | ["GOROOT_FINAL"] | go | 1 | 0 | |
mmdet/models/roi_heads/mask_heads/fcn_mask_head.py | import os
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import ConvModule, build_conv_layer, build_upsample_layer
from mmcv.ops.carafe import CARAFEPack
from mmcv.runner import BaseModule, ModuleList, auto_fp16, force_fp32
from torch.nn.modules.utils import _pair
from mmdet.core import mask_target
from mmdet.models.builder import HEADS, build_loss
BYTES_PER_FLOAT = 4
# TODO: This memory limit may be too much or too little. It would be better to
# determine it based on available resources.
GPU_MEM_LIMIT = 1024**3 # 1 GB memory limit
@HEADS.register_module()
class FCNMaskHead(BaseModule):
def __init__(self,
num_convs=4,
roi_feat_size=14,
in_channels=256,
conv_kernel_size=3,
conv_out_channels=256,
num_classes=80,
class_agnostic=False,
upsample_cfg=dict(type='deconv', scale_factor=2),
conv_cfg=None,
norm_cfg=None,
predictor_cfg=dict(type='Conv'),
loss_mask=dict(
type='CrossEntropyLoss', use_mask=True, loss_weight=1.0),
init_cfg=None):
assert init_cfg is None, 'To prevent abnormal initialization ' \
'behavior, init_cfg is not allowed to be set'
super(FCNMaskHead, self).__init__(init_cfg)
self.upsample_cfg = upsample_cfg.copy()
if self.upsample_cfg['type'] not in [
None, 'deconv', 'nearest', 'bilinear', 'carafe'
]:
raise ValueError(
f'Invalid upsample method {self.upsample_cfg["type"]}, '
'accepted methods are "deconv", "nearest", "bilinear", '
'"carafe"')
self.num_convs = num_convs
# WARN: roi_feat_size is reserved and not used
self.roi_feat_size = _pair(roi_feat_size)
self.in_channels = in_channels
self.conv_kernel_size = conv_kernel_size
self.conv_out_channels = conv_out_channels
self.upsample_method = self.upsample_cfg.get('type')
self.scale_factor = self.upsample_cfg.pop('scale_factor', None)
self.num_classes = num_classes
self.class_agnostic = class_agnostic
self.conv_cfg = conv_cfg
self.norm_cfg = norm_cfg
self.predictor_cfg = predictor_cfg
self.fp16_enabled = False
self.loss_mask = build_loss(loss_mask)
self.convs = ModuleList()
for i in range(self.num_convs):
in_channels = (
self.in_channels if i == 0 else self.conv_out_channels)
padding = (self.conv_kernel_size - 1) // 2
self.convs.append(
ConvModule(
in_channels,
self.conv_out_channels,
self.conv_kernel_size,
padding=padding,
conv_cfg=conv_cfg,
norm_cfg=norm_cfg))
upsample_in_channels = (
self.conv_out_channels if self.num_convs > 0 else in_channels)
upsample_cfg_ = self.upsample_cfg.copy()
if self.upsample_method is None:
self.upsample = None
elif self.upsample_method == 'deconv':
upsample_cfg_.update(
in_channels=upsample_in_channels,
out_channels=self.conv_out_channels,
kernel_size=self.scale_factor,
stride=self.scale_factor)
self.upsample = build_upsample_layer(upsample_cfg_)
elif self.upsample_method == 'carafe':
upsample_cfg_.update(
channels=upsample_in_channels, scale_factor=self.scale_factor)
self.upsample = build_upsample_layer(upsample_cfg_)
else:
# suppress warnings
align_corners = (None
if self.upsample_method == 'nearest' else False)
upsample_cfg_.update(
scale_factor=self.scale_factor,
mode=self.upsample_method,
align_corners=align_corners)
self.upsample = build_upsample_layer(upsample_cfg_)
out_channels = 1 if self.class_agnostic else self.num_classes
logits_in_channel = (
self.conv_out_channels
if self.upsample_method == 'deconv' else upsample_in_channels)
self.conv_logits = build_conv_layer(self.predictor_cfg,
logits_in_channel, out_channels, 1)
self.relu = nn.ReLU(inplace=True)
self.debug_imgs = None
def init_weights(self):
super(FCNMaskHead, self).init_weights()
for m in [self.upsample, self.conv_logits]:
if m is None:
continue
elif isinstance(m, CARAFEPack):
m.init_weights()
else:
nn.init.kaiming_normal_(
m.weight, mode='fan_out', nonlinearity='relu')
nn.init.constant_(m.bias, 0)
@auto_fp16()
def forward(self, x):
for conv in self.convs:
x = conv(x)
if self.upsample is not None:
x = self.upsample(x)
if self.upsample_method == 'deconv':
x = self.relu(x)
mask_pred = self.conv_logits(x)
return mask_pred
def get_targets(self, sampling_results, gt_masks, rcnn_train_cfg):
pos_proposals = [res.pos_bboxes for res in sampling_results]
pos_assigned_gt_inds = [
res.pos_assigned_gt_inds for res in sampling_results
]
mask_targets = mask_target(pos_proposals, pos_assigned_gt_inds,
gt_masks, rcnn_train_cfg)
return mask_targets
@force_fp32(apply_to=('mask_pred', ))
def loss(self, mask_pred, mask_targets, labels):
"""
Example:
>>> from mmdet.models.roi_heads.mask_heads.fcn_mask_head import * # NOQA
>>> N = 7 # N = number of extracted ROIs
>>> C, H, W = 11, 32, 32
>>> # Create example instance of FCN Mask Head.
>>> # There are lots of variations depending on the configuration
>>> self = FCNMaskHead(num_classes=C, num_convs=1)
>>> inputs = torch.rand(N, self.in_channels, H, W)
>>> mask_pred = self.forward(inputs)
>>> sf = self.scale_factor
>>> labels = torch.randint(0, C, size=(N,))
>>> # With the default properties the mask targets should indicate
>>> # a (potentially soft) single-class label
>>> mask_targets = torch.rand(N, H * sf, W * sf)
>>> loss = self.loss(mask_pred, mask_targets, labels)
>>> print('loss = {!r}'.format(loss))
"""
loss = dict()
if mask_pred.size(0) == 0:
loss_mask = mask_pred.sum()
else:
if self.class_agnostic:
loss_mask = self.loss_mask(mask_pred, mask_targets,
torch.zeros_like(labels))
else:
loss_mask = self.loss_mask(mask_pred, mask_targets, labels)
loss['loss_mask'] = loss_mask
return loss
def get_seg_masks(self, mask_pred, det_bboxes, det_labels, rcnn_test_cfg,
ori_shape, scale_factor, rescale):
"""Get segmentation masks from mask_pred and bboxes.
Args:
mask_pred (Tensor or ndarray): shape (n, #class, h, w).
For single-scale testing, mask_pred is the direct output of
model, whose type is Tensor, while for multi-scale testing,
it will be converted to numpy array outside of this method.
det_bboxes (Tensor): shape (n, 4/5)
det_labels (Tensor): shape (n, )
rcnn_test_cfg (dict): rcnn testing config
ori_shape (Tuple): original image height and width, shape (2,)
scale_factor(float | Tensor): If ``rescale is True``, box
coordinates are divided by this scale factor to fit
``ori_shape``.
rescale (bool): If True, the resulting masks will be rescaled to
``ori_shape``.
Returns:
list[list]: encoded masks. The c-th item in the outer list
corresponds to the c-th class. Given the c-th outer list, the
i-th item in that inner list is the mask for the i-th box with
class label c.
Example:
>>> import mmcv
>>> from mmdet.models.roi_heads.mask_heads.fcn_mask_head import * # NOQA
>>> N = 7 # N = number of extracted ROIs
>>> C, H, W = 11, 32, 32
>>> # Create example instance of FCN Mask Head.
>>> self = FCNMaskHead(num_classes=C, num_convs=0)
>>> inputs = torch.rand(N, self.in_channels, H, W)
>>> mask_pred = self.forward(inputs)
>>> # Each input is associated with some bounding box
>>> det_bboxes = torch.Tensor([[1, 1, 42, 42 ]] * N)
>>> det_labels = torch.randint(0, C, size=(N,))
>>> rcnn_test_cfg = mmcv.Config({'mask_thr_binary': 0, })
>>> ori_shape = (H * 4, W * 4)
>>> scale_factor = torch.FloatTensor((1, 1))
>>> rescale = False
>>> # Encoded masks are a list for each category.
>>> encoded_masks = self.get_seg_masks(
>>> mask_pred, det_bboxes, det_labels, rcnn_test_cfg, ori_shape,
>>> scale_factor, rescale
>>> )
>>> assert len(encoded_masks) == C
>>> assert sum(list(map(len, encoded_masks))) == N
"""
if not isinstance(mask_pred, torch.Tensor):
mask_pred = det_bboxes.new_tensor(mask_pred)
device = mask_pred.device
cls_segms = [[] for _ in range(self.num_classes)
] # BG is not included in num_classes
bboxes = det_bboxes[:, :4]
labels = det_labels
# No need to consider rescale and scale_factor while exporting to ONNX
if torch.onnx.is_in_onnx_export():
img_h, img_w = ori_shape[:2]
else:
if rescale:
img_h, img_w = ori_shape[:2]
else:
if isinstance(scale_factor, float):
img_h = np.round(ori_shape[0] * scale_factor).astype(
np.int32)
img_w = np.round(ori_shape[1] * scale_factor).astype(
np.int32)
else:
w_scale, h_scale = scale_factor[0], scale_factor[1]
img_h = np.round(ori_shape[0] * h_scale.item()).astype(
np.int32)
img_w = np.round(ori_shape[1] * w_scale.item()).astype(
np.int32)
scale_factor = 1.0
if not isinstance(scale_factor, (float, torch.Tensor)):
scale_factor = bboxes.new_tensor(scale_factor)
bboxes = bboxes / scale_factor
# support exporting to ONNX
if torch.onnx.is_in_onnx_export():
threshold = rcnn_test_cfg.mask_thr_binary
if not self.class_agnostic:
box_inds = torch.arange(mask_pred.shape[0])
mask_pred = mask_pred[box_inds, labels][:, None]
masks, _ = _do_paste_mask(
mask_pred, bboxes, img_h, img_w, skip_empty=False)
if threshold >= 0:
masks = (masks >= threshold).to(dtype=torch.bool)
else:
# TensorRT backend does not have data type of uint8
is_trt_backend = os.environ.get(
'ONNX_BACKEND') == 'MMCVTensorRT'
target_dtype = torch.int32 if is_trt_backend else torch.uint8
masks = (masks * 255).to(dtype=target_dtype)
return masks
N = len(mask_pred)
# The actual implementation split the input into chunks,
# and paste them chunk by chunk.
if device.type == 'cpu':
# CPU is most efficient when they are pasted one by one with
# skip_empty=True, so that it performs minimal number of
# operations.
num_chunks = N
else:
# GPU benefits from parallelism for larger chunks,
# but may have memory issue
num_chunks = int(
np.ceil(N * img_h * img_w * BYTES_PER_FLOAT / GPU_MEM_LIMIT))
assert (num_chunks <=
N), 'Default GPU_MEM_LIMIT is too small; try increasing it'
chunks = torch.chunk(torch.arange(N, device=device), num_chunks)
threshold = rcnn_test_cfg.mask_thr_binary
im_mask = torch.zeros(
N,
img_h,
img_w,
device=device,
dtype=torch.bool if threshold >= 0 else torch.uint8)
if not self.class_agnostic:
mask_pred = mask_pred[range(N), labels][:, None]
for inds in chunks:
masks_chunk, spatial_inds = _do_paste_mask(
mask_pred[inds],
bboxes[inds],
img_h,
img_w,
skip_empty=device.type == 'cpu')
if threshold >= 0:
masks_chunk = (masks_chunk >= threshold).to(dtype=torch.bool)
else:
# for visualization and debugging
masks_chunk = (masks_chunk * 255).to(dtype=torch.uint8)
im_mask[(inds, ) + spatial_inds] = masks_chunk
if torch.jit.is_tracing():
return im_mask.detach().int()
for i in range(N):
cls_segms[labels[i]].append(im_mask[i].detach().cpu().numpy())
return cls_segms
def _do_paste_mask(masks, boxes, img_h, img_w, skip_empty=True):
"""Paste instance masks according to boxes.
This implementation is modified from
https://github.com/facebookresearch/detectron2/
Args:
masks (Tensor): N, 1, H, W
boxes (Tensor): N, 4
img_h (int): Height of the image to be pasted.
img_w (int): Width of the image to be pasted.
skip_empty (bool): Only paste masks within the region that
tightly bound all boxes, and returns the results this region only.
An important optimization for CPU.
Returns:
tuple: (Tensor, tuple). The first item is mask tensor, the second one
is the slice object.
If skip_empty == False, the whole image will be pasted. It will
return a mask of shape (N, img_h, img_w) and an empty tuple.
If skip_empty == True, only area around the mask will be pasted.
A mask of shape (N, h', w') and its start and end coordinates
in the original image will be returned.
"""
# On GPU, paste all masks together (up to chunk size)
# by using the entire image to sample the masks
# Compared to pasting them one by one,
# this has more operations but is faster on COCO-scale dataset.
device = masks.device
if skip_empty:
x0_int, y0_int = torch.clamp(
boxes.min(dim=0).values.floor()[:2] - 1,
min=0).to(dtype=torch.int32)
x1_int = torch.clamp(
boxes[:, 2].max().ceil() + 1, max=img_w).to(dtype=torch.int32)
y1_int = torch.clamp(
boxes[:, 3].max().ceil() + 1, max=img_h).to(dtype=torch.int32)
else:
x0_int, y0_int = 0, 0
x1_int, y1_int = img_w, img_h
x0, y0, x1, y1 = torch.split(boxes, 1, dim=1) # each is Nx1
N = masks.shape[0]
img_y = torch.arange(y0_int, y1_int, device=device).to(torch.float32) + 0.5
img_x = torch.arange(x0_int, x1_int, device=device).to(torch.float32) + 0.5
img_y = (img_y - y0) / (y1 - y0) * 2 - 1
img_x = (img_x - x0) / (x1 - x0) * 2 - 1
# img_x, img_y have shapes (N, w), (N, h)
# IsInf op is not supported with ONNX<=1.7.0
if not torch.onnx.is_in_onnx_export():
if torch.isinf(img_x).any():
inds = torch.where(torch.isinf(img_x))
img_x[inds] = 0
if torch.isinf(img_y).any():
inds = torch.where(torch.isinf(img_y))
img_y[inds] = 0
gx = img_x[:, None, :].expand(N, img_y.size(1), img_x.size(1))
gy = img_y[:, :, None].expand(N, img_y.size(1), img_x.size(1))
grid = torch.stack([gx, gy], dim=3)
img_masks = F.grid_sample(
masks.to(dtype=torch.float32), grid, align_corners=False)
if skip_empty:
return img_masks[:, 0], (slice(y0_int, y1_int), slice(x0_int, x1_int))
else:
return img_masks[:, 0], ()
| [] | [] | [
"ONNX_BACKEND"
] | [] | ["ONNX_BACKEND"] | python | 1 | 0 | |
adversarial_defense/model/feature_defense_model.py | import glob
import os
import pretrainedmodels
import torch
from torch import nn
from torchvision import models as torch_models
import cifar_models as models
from adversarial_defense.model.denoise_resnet import DenoiseResNet50, DenoiseResNet101, DenoiseResNet152
from adversarial_defense.model.pcl_resnet import PrototypeConformityLossResNet
from cifar_models_myself import Conv3, DenseNet121, DenseNet169, DenseNet201, GoogLeNet, MobileNet, MobileNetV2, \
ResNet18, \
ResNet34, ResNet50, ResNet101, ResNet152, PNASNetA, PNASNetB, EfficientNetB0, DPN26, DPN92, ResNeXt29_2x64d, \
ResNeXt29_4x64d, ResNeXt29_8x64d, ResNeXt29_32x4d, SENet18, ShuffleNetG2, ShuffleNetG3, vgg11, vgg13, vgg16, vgg19, \
PreActResNet18, PreActResNet34, PreActResNet50, PreActResNet101, PreActResNet152, wideresnet28, wideresnet34, \
wideresnet40, carlinet, wideresnet28drop, wideresnet34drop, wideresnet40drop
from cifar_models_myself.miscellaneous import Identity
from config import pretrained_cifar_model_conf, IN_CHANNELS, IMAGE_SIZE, CLASS_NUM, PROJECT_PATH
from cifar_models_myself.efficient_densenet import EfficientDenseNet
from cifar_models_myself.ghostnet import ghost_net
from tiny_imagenet_models.densenet import densenet161, densenet121, densenet169, densenet201
from tiny_imagenet_models.resnext import resnext101_32x4d, resnext101_64x4d
import torchvision.models as vision_models
from tiny_imagenet_models.inception import inception_v3
from tiny_imagenet_models.wrn import tiny_imagenet_wrn
class FeatureDefenseModel(nn.Module):
"""
A StandardModel object wraps a cnn model.
This model always accept standard image: in [0, 1] range, RGB order, un-normalized, NCHW format
"""
def __init__(self, dataset, arch, no_grad=True):
super(FeatureDefenseModel, self).__init__()
# init cnn model
self.in_channels = IN_CHANNELS[dataset]
self.dataset = dataset
if "denoise" in arch.lower():
# CIFAR-100@ResNet50_with_denoise_NonLocal_Filter_3.pth.tar
trained_model_path = "{root}/train_pytorch_model/adversarial_train/feature_denoise/{dataset}@{arch}_NonLocal_Filter_3.pth.tar".format(root=PROJECT_PATH, dataset=dataset, arch=arch)
assert os.path.exists(trained_model_path), "{} does not exist!".format(trained_model_path)
elif dataset.startswith("CIFAR"):
trained_model_path = "{root}/train_pytorch_model/real_image_model/{dataset}-pretrained/{arch}/checkpoint.pth.tar".format(root=PROJECT_PATH, dataset=dataset, arch=arch)
assert os.path.exists(trained_model_path), "{} does not exist!".format(trained_model_path)
elif dataset == "TinyImageNet":
arch = arch.replace("resnet-", "resnet")
trained_model_path = "{root}/train_pytorch_model/real_image_model/{dataset}@{arch}@*.pth.tar".format(root=PROJECT_PATH, dataset=dataset, arch=arch)
trained_model_path_list = list(glob.glob(trained_model_path))
assert len(trained_model_path_list)>0, "{} does not exist!".format(trained_model_path)
trained_model_path = trained_model_path_list[0]
else:
trained_model_path = "{root}/train_pytorch_model/real_image_model/{dataset}-pretrained/checkpoints/{arch}*.pth".format(
root=PROJECT_PATH, dataset=dataset, arch=arch)
trained_model_path_ls = list(glob.glob(trained_model_path))
assert trained_model_path_ls, "{} does not exist!".format(trained_model_path)
trained_model_path = trained_model_path_ls[0]
self.cnn = self.make_model(dataset, arch, self.in_channels, CLASS_NUM[dataset], trained_model_path=trained_model_path)
# init cnn model meta-information
self.mean = torch.FloatTensor(self.cnn.mean).view(1, self.in_channels, 1, 1).cuda()
self.mean.requires_grad =True
self.std = torch.FloatTensor(self.cnn.std).view(1, self.in_channels, 1, 1).cuda()
self.std.requires_grad = True
self.input_space = self.cnn.input_space # 'RGB' or 'GBR'
self.input_range = self.cnn.input_range # [0, 1] or [0, 255]
self.input_size = self.cnn.input_size
self.no_grad = no_grad
self.arch = arch
@staticmethod
def check_arch(arch, dataset):
if dataset == "ImageNet":
return arch in pretrainedmodels.__dict__
elif dataset == "TinyImageNet":
trained_model_path = "{root}/train_pytorch_model/real_image_model/{dataset}@{arch}@*.pth.tar".format(
root=PROJECT_PATH, dataset=dataset, arch=arch)
trained_model_path_list = list(glob.glob(trained_model_path))
return len(trained_model_path_list) > 0
else:
trained_model_path = "{root}/train_pytorch_model/real_image_model/{dataset}-pretrained/{arch}*".format(
root=PROJECT_PATH, dataset=dataset, arch=arch)
trained_model_path = glob.glob(trained_model_path)
if len(trained_model_path) > 0:
return os.path.exists(trained_model_path[0] + "/checkpoint.pth.tar")
else:
return False
def forward(self, x):
# assign dropout probability
# if hasattr(self, 'drop'):
# self.cnn.drop = self.drop
# channel order
if self.input_space == 'BGR':
x = x[:, [2, 1, 0], :, :] # pytorch does not support negative stride index (::-1) yet
# input range
if max(self.input_range) == 255:
x = x * 255
# normalization
x = (x - self.mean.type(x.dtype).to(x.device)) / self.std.type(x.dtype).to(x.device)
if self.no_grad:
with torch.no_grad():
if "pcl" in self.arch:
feats128, feats256, feats1024, x = self.cnn(x)
else:
x = self.cnn(x)
else:
if "pcl" in self.arch:
feats128, feats256, feats1024, x = self.cnn(x)
else:
x = self.cnn(x)
x = x.view(x.size(0), -1)
if "pcl" in self.arch:
return feats128, feats256, feats1024, x
return x
def load_weight_from_pth_checkpoint(self, model, fname):
raw_state_dict = torch.load(fname, map_location='cpu')
if "state_dict" in raw_state_dict:
raw_state_dict = raw_state_dict["state_dict"]
state_dict = dict()
for key, val in raw_state_dict.items():
new_key = key.replace('module.', '')
state_dict[new_key] = val
model.load_state_dict(state_dict)
def construct_cifar_model(self, arch, dataset, num_classes):
if "denoise" not in arch.lower():
conf = pretrained_cifar_model_conf[dataset][arch]
arch = arch.split("-")[0]
if arch.startswith('resnext'):
model = models.__dict__[arch](
cardinality=conf["cardinality"],
num_classes=num_classes,
depth=conf["depth"],
widen_factor=conf["widen_factor"],
dropRate=conf["drop"],
)
elif arch.startswith('densenet'):
model = models.__dict__[arch](
num_classes=num_classes,
depth=conf["depth"],
growthRate=conf["growthRate"],
compressionRate=conf["compressionRate"],
dropRate=conf["drop"],
)
elif arch.startswith('wrn'):
model = models.__dict__[arch](
num_classes=num_classes,
depth=conf["depth"],
widen_factor=conf["widen_factor"],
dropRate=conf["drop"],
)
elif arch.endswith('resnet') and "pcl_" not in arch and "denoise" not in arch:
model = models.__dict__[arch](
num_classes=num_classes,
depth=conf["depth"],
block_name=conf["block_name"],
)
elif "pcl_resnet" in arch:
model = PrototypeConformityLossResNet(in_channels=IN_CHANNELS[dataset], depth=conf["depth"], num_classes=CLASS_NUM[dataset])
elif arch == "DenoiseResNet50":
model = DenoiseResNet50(in_channels=IN_CHANNELS[dataset], num_classes=CLASS_NUM[dataset], whether_denoising=True)
elif arch == "DenoiseResNet101":
model = DenoiseResNet101(in_channels=IN_CHANNELS[dataset], num_classes=CLASS_NUM[dataset], whether_denoising=True)
elif arch == "DenoiseResNet152":
model = DenoiseResNet152(in_channels=IN_CHANNELS[dataset], num_classes=CLASS_NUM[dataset], whether_denoising=True)
else:
model = models.__dict__[arch](num_classes=num_classes)
return model
def make_model(self, dataset, arch, in_channel, num_classes, trained_model_path=None):
"""
Make model, and load pre-trained weights.
:param dataset: cifar10 or imagenet
:param arch: arch name, e.g., alexnet_bn
:return: model (in cpu and training mode)
"""
if dataset in ['CIFAR-10',"CIFAR-100", "MNIST","FashionMNIST"]:
assert trained_model_path is not None and os.path.exists(trained_model_path), "Pretrained weight model file {} does not exist!".format(trained_model_path)
if arch == 'gdas':
model = models.gdas(in_channel, num_classes)
model.mean = [125.3 / 255, 123.0 / 255, 113.9 / 255]
model.std = [63.0 / 255, 62.1 / 255, 66.7 / 255]
model.input_space = 'RGB'
model.input_range = [0, 1]
model.input_size = [in_channel, IMAGE_SIZE[dataset][0], IMAGE_SIZE[dataset][1]]
elif arch == 'pyramidnet272':
model = models.pyramidnet272(in_channel, num_classes)
model.mean = [0.49139968, 0.48215841, 0.44653091]
model.std = [0.24703223, 0.24348513, 0.26158784]
model.input_space = 'RGB'
model.input_range = [0, 1]
model.input_size = [in_channel, IMAGE_SIZE[dataset][0], IMAGE_SIZE[dataset][1]]
else:
model = self.construct_cifar_model(arch, dataset, num_classes) #
model.mean = [0.4914, 0.4822, 0.4465]
model.std = [0.2023, 0.1994, 0.2010]
model.input_space = 'RGB'
model.input_range = [0, 1]
model.input_size = [in_channel, IMAGE_SIZE[dataset][0], IMAGE_SIZE[dataset][1]]
# self.load_weight_from_pth_checkpoint(model, trained_model_path)
elif dataset == "TinyImageNet":
model = MetaLearnerModelBuilder.construct_tiny_imagenet_model(arch, dataset)
model.input_space = 'RGB'
model.input_range = [0, 1]
model.mean = [0.4914, 0.4822, 0.4465] # if "defense_resnet" not in arch and "denoise" not in arch: [0,0,0] . [1,1,1]
model.std = [0.2023, 0.1994, 0.2010]
model.input_size = [in_channel,IMAGE_SIZE[dataset][0], IMAGE_SIZE[dataset][1]]
# model.load_state_dict(torch.load(trained_model_path, map_location=lambda storage, location: storage)["state_dict"])
elif dataset == 'ImageNet':
os.environ["TORCH_HOME"] = "{}/train_pytorch_model/real_image_model/ImageNet-pretrained".format(PROJECT_PATH)
model = pretrainedmodels.__dict__[arch](num_classes=1000, pretrained="imagenet")
return model
class MetaLearnerModelBuilder(object):
@staticmethod
def construct_cifar_model(arch, dataset):
if arch == "conv3":
network = Conv3(IN_CHANNELS[dataset], IMAGE_SIZE[dataset], CLASS_NUM[dataset])
elif arch == "densenet121":
network = DenseNet121(IN_CHANNELS[dataset], CLASS_NUM[dataset])
elif arch == "densenet169":
network = DenseNet169(IN_CHANNELS[dataset], CLASS_NUM[dataset])
elif arch == "densenet201":
network = DenseNet201(IN_CHANNELS[dataset], CLASS_NUM[dataset])
elif arch == "googlenet":
network = GoogLeNet(IN_CHANNELS[dataset], CLASS_NUM[dataset])
elif arch == "mobilenet":
network = MobileNet(IN_CHANNELS[dataset], CLASS_NUM[dataset])
elif arch == "mobilenet_v2":
network = MobileNetV2(IN_CHANNELS[dataset], CLASS_NUM[dataset])
elif arch == "ghost_net":
network = ghost_net(IN_CHANNELS[dataset], CLASS_NUM[dataset])
elif arch == "resnet18":
network = ResNet18(IN_CHANNELS[dataset], CLASS_NUM[dataset])
elif arch == "resnet34":
network = ResNet34(IN_CHANNELS[dataset], CLASS_NUM[dataset])
elif arch == "resnet50":
network = ResNet50(IN_CHANNELS[dataset], CLASS_NUM[dataset])
elif arch == "resnet101":
network = ResNet101(IN_CHANNELS[dataset], CLASS_NUM[dataset])
elif arch == "resnet152":
network = ResNet152(IN_CHANNELS[dataset], CLASS_NUM[dataset])
elif arch == "pnasnetA":
network = PNASNetA(IN_CHANNELS[dataset], CLASS_NUM[dataset])
elif arch == "pnasnetB":
network = PNASNetB(IN_CHANNELS[dataset], CLASS_NUM[dataset])
elif arch == "efficientnet":
network = EfficientNetB0(IN_CHANNELS[dataset], CLASS_NUM[dataset])
elif arch == "dpn26":
network = DPN26(IN_CHANNELS[dataset], CLASS_NUM[dataset])
elif arch == "dpn92":
network = DPN92(IN_CHANNELS[dataset], CLASS_NUM[dataset])
elif arch == "resnext29_2":
network = ResNeXt29_2x64d(IN_CHANNELS[dataset], CLASS_NUM[dataset])
elif arch == "resnext29_4":
network = ResNeXt29_4x64d(IN_CHANNELS[dataset], CLASS_NUM[dataset])
elif arch == "resnext29_8":
network = ResNeXt29_8x64d(IN_CHANNELS[dataset], CLASS_NUM[dataset])
elif arch == "resnext29_32":
network = ResNeXt29_32x4d(IN_CHANNELS[dataset], CLASS_NUM[dataset])
elif arch == "senet18":
network = SENet18(IN_CHANNELS[dataset], CLASS_NUM[dataset])
elif arch == "shufflenet_G2":
network = ShuffleNetG2(IN_CHANNELS[dataset], CLASS_NUM[dataset])
elif arch == "shufflenet_G3":
network = ShuffleNetG3(IN_CHANNELS[dataset], CLASS_NUM[dataset])
elif arch == "vgg11":
network = vgg11(IN_CHANNELS[dataset], CLASS_NUM[dataset])
elif arch == "vgg13":
network = vgg13(IN_CHANNELS[dataset], CLASS_NUM[dataset])
elif arch == "vgg16":
network = vgg16(IN_CHANNELS[dataset], CLASS_NUM[dataset])
elif arch == "vgg19":
network = vgg19(IN_CHANNELS[dataset], CLASS_NUM[dataset])
elif arch == "preactresnet18":
network = PreActResNet18(IN_CHANNELS[dataset], CLASS_NUM[dataset])
elif arch == "preactresnet34":
network = PreActResNet34(IN_CHANNELS[dataset], CLASS_NUM[dataset])
elif arch == "preactresnet50":
network = PreActResNet50(IN_CHANNELS[dataset], CLASS_NUM[dataset])
elif arch == "preactresnet101":
network = PreActResNet101(IN_CHANNELS[dataset], CLASS_NUM[dataset])
elif arch == "preactresnet152":
network = PreActResNet152(IN_CHANNELS[dataset], CLASS_NUM[dataset])
elif arch == "wideresnet28":
network = wideresnet28(IN_CHANNELS[dataset], CLASS_NUM[dataset])
elif arch == "wideresnet28drop":
network = wideresnet28drop(IN_CHANNELS[dataset], CLASS_NUM[dataset])
elif arch == "wideresnet34":
network = wideresnet34(IN_CHANNELS[dataset], CLASS_NUM[dataset])
elif arch == "wideresnet34drop":
network = wideresnet34drop(IN_CHANNELS[dataset], CLASS_NUM[dataset])
elif arch == "wideresnet40":
network = wideresnet40(IN_CHANNELS[dataset], CLASS_NUM[dataset])
elif arch == "wideresnet40drop":
network = wideresnet40drop(IN_CHANNELS[dataset], CLASS_NUM[dataset])
elif arch == "carlinet":
network = carlinet(IN_CHANNELS[dataset], CLASS_NUM[dataset])
elif arch == 'efficient_densenet':
depth = 40
block_config = [(depth - 4) // 6 for _ in range(3)]
network = EfficientDenseNet(IN_CHANNELS[dataset], block_config=block_config,
num_classes=CLASS_NUM[dataset], small_inputs=dataset != "ImageNet", efficient=False)
return network
@staticmethod
def construct_imagenet_model(arch, dataset):
os.environ["TORCH_HOME"] = "{}/train_pytorch_model/real_image_model/ImageNet-pretrained".format(PROJECT_PATH)
if arch == 'efficient_densenet':
depth = 40
block_config = [(depth - 4) // 6 for _ in range(3)]
return EfficientDenseNet(IN_CHANNELS[dataset],block_config=block_config, num_classes=CLASS_NUM[dataset], small_inputs=False, efficient=False)
elif arch == "ghost_net":
network = ghost_net(IN_CHANNELS[dataset], CLASS_NUM[dataset])
return network
model = vision_models.__dict__[arch](pretrained=False)
return model
@staticmethod
def construct_tiny_imagenet_model(arch, dataset):
if not arch.startswith("densenet") and not arch.startswith("resnext") and arch in torch_models.__dict__:
network = torch_models.__dict__[arch](pretrained=False)
num_classes = CLASS_NUM[dataset]
if arch.startswith("resnet"):
num_ftrs = network.fc.in_features
network.fc = nn.Linear(num_ftrs, num_classes)
elif arch.startswith("densenet"):
if arch == "densenet161":
network = densenet161(pretrained=False)
elif arch == "densenet121":
network = densenet121(pretrained=False)
elif arch == "densenet169":
network = densenet169(pretrained=False)
elif arch == "densenet201":
network = densenet201(pretrained=False)
elif arch == "resnext32_4":
network = resnext101_32x4d(pretrained=None)
elif arch == "resnext64_4":
network = resnext101_64x4d(pretrained=None)
elif arch == "ghost_net":
network = ghost_net(IN_CHANNELS[dataset], CLASS_NUM[dataset])
elif arch.startswith("inception"):
network = inception_v3(pretrained=False)
elif arch == "WRN-28-10-drop":
network = tiny_imagenet_wrn(in_channels=IN_CHANNELS[dataset],depth=28,num_classes=CLASS_NUM[dataset],widen_factor=10, dropRate=0.3)
elif arch == "WRN-40-10-drop":
network = tiny_imagenet_wrn(in_channels=IN_CHANNELS[dataset], depth=40, num_classes=CLASS_NUM[dataset],
widen_factor=10, dropRate=0.3)
elif arch.startswith("vgg"):
network.avgpool = Identity()
network.classifier[0] = nn.Linear(512 * 2 * 2, 4096) # 64 /2**5 = 2
network.classifier[-1] = nn.Linear(4096, num_classes)
elif "pcl_resnet" in arch:
network = PrototypeConformityLossResNet(in_channels=IN_CHANNELS[dataset], depth=pretrained_cifar_model_conf[dataset][arch]["depth"], num_classes=CLASS_NUM[dataset])
elif arch == "DenoiseResNet50":
network = DenoiseResNet50(in_channels=IN_CHANNELS[dataset], num_classes=CLASS_NUM[dataset], whether_denoising=True)
elif arch == "DenoiseResNet101":
network = DenoiseResNet101(in_channels=IN_CHANNELS[dataset], num_classes=CLASS_NUM[dataset], whether_denoising=True)
elif arch == "DenoiseResNet152":
network = DenoiseResNet152(in_channels=IN_CHANNELS[dataset], num_classes=CLASS_NUM[dataset], whether_denoising=True)
return network
| [] | [] | [
"TORCH_HOME"
] | [] | ["TORCH_HOME"] | python | 1 | 0 | |
core/src/test/python/custom_folder_helper_test.py | """
Copyright (c) 2019, Oracle Corporation and/or its affiliates. All rights reserved.
The Universal Permissive License (UPL), Version 1.0
"""
import unittest
from org.python.modules import jarray
from java.lang import Boolean
from java.util import HashMap
from java.lang import String
from java.io import ByteArrayOutputStream
from java.io import DataOutputStream
from java.io import IOException
from java.util import Properties
from oracle.weblogic.deploy.util import PyOrderedDict
import wlsdeploy.aliases.alias_constants as alias_constants
import wlsdeploy.logging.platform_logger as platform_logger
from wlsdeploy.aliases.aliases import Aliases
from wlsdeploy.aliases.wlst_modes import WlstModes
from wlsdeploy.exception.expection_types import ExceptionType
from wlsdeploy.tool.discover.custom_folder_helper import CustomFolderHelper
from wlsdeploy.util.cla_utils import CommandLineArgUtil as CLA
from wlsdeploy.util.model_context import ModelContext
class CustomFolderHelperTestCase(unittest.TestCase):
"""
Test the Custom MBean attribute conversion routines which convert from WLST value to Model value.
Test comparison of converted model value to default value.
"""
_custom_helper = None
_logger = platform_logger.PlatformLogger('wlsdeploy.unittest')
_aliases = None
_model_context = None
_wls_version = '12.2.1.3'
def setUp(self):
arg_map = dict()
arg_map[CLA.ORACLE_HOME_SWITCH] = '/my/path/to/oracle'
arg_map[CLA.TARGET_MODE_SWITCH] = 'offline'
self._model_context = ModelContext("test", arg_map)
self._aliases = Aliases(model_context=self._model_context, wlst_mode=WlstModes.OFFLINE,
wls_version=self._wls_version)
self._custom_helper = CustomFolderHelper(self._aliases, self._logger, self._model_context,
ExceptionType.DISCOVER)
return
def testEncryptedPassword(self):
credential_string = 'AES}0vlIcO+I+VWV9aQ1wzQUa1qtByh4D9d0I1dJHa7HsdE='
try:
bos = ByteArrayOutputStream()
dos = DataOutputStream(bos)
dos.writeBytes(credential_string)
byte_array = bos.toByteArray()
dos.close()
except IOException, ioe:
self.fail('Unexpected exception writing out credential : ', str(ioe))
converted_type, converted_value = self._custom_helper.convert(byte_array, '[B')
self.common_test_converted(alias_constants.PASSWORD_TOKEN, alias_constants.PASSWORD,
converted_value, converted_type)
def testListEqualsDefault(self):
list_value = ['foo', 'bar']
list_default = list(list_value)
converted_type, converted_value = self._custom_helper.convert(list_value, 'list')
self.common_test_converted(list_value, alias_constants.LIST, converted_value, converted_type)
self.common_test_default(list_default, 'list', converted_value, converted_type, True)
def testListNotDefaultLengthDiff(self):
list_value = ['foo', 'bar']
list_default = ['bar']
converted_type, converted_value = self._custom_helper.convert(list_value, 'list')
self.common_test_converted(list_value, alias_constants.LIST, converted_value, converted_type)
self.common_test_default(list_default, 'list', converted_value, converted_type, False)
def testListNotDefaultElementsDiff(self):
list_value = ['abc', 'xyz']
list_default = ['bar', 'foo']
converted_type, converted_value = self._custom_helper.convert(list_value, 'list')
self.common_test_converted(list_value, alias_constants.LIST, converted_value, converted_type)
self.common_test_default(list_default, 'list', converted_value, converted_type, False)
def testJarrayEqualsDefault(self):
jarray_value = jarray.array(['Idcs_user_assertion', 'idcs_user_assertion'], String)
expected_value = ['Idcs_user_assertion', 'idcs_user_assertion']
jarray_default = ['idcs_user_assertion', 'Idcs_user_assertion']
converted_type, converted_value = self._custom_helper.convert(jarray_value, '[L')
self.common_test_converted(expected_value, alias_constants.JARRAY, converted_value, converted_type)
self.common_test_default(jarray_default, str(type(jarray_default)), converted_value, converted_type, True)
def testJarryDoesNotEqualDefaultDiffLength(self):
jarray_value = jarray.array(['idcs_user_assertion'], String)
expected_value = ['idcs_user_assertion']
jarray_default = ['idcs_user_assertion', 'Idcs_user_assertion']
converted_type, converted_value = self._custom_helper.convert(jarray_value, 'PyArray')
self.common_test_converted(expected_value, alias_constants.JARRAY, converted_value, converted_type)
self.common_test_default(jarray_default, 'PyArray', converted_value, converted_type, False)
def testJarryDoesNotEqualDefaultDiffValue(self):
jarray_value = jarray.array(['nonmatch', 'idcs_user_assertion'], String)
expected_value = ['nomatch', 'idcs_user_assertion']
jarray_default = ['idcs_user_assertion', 'Idcs_user_assertion']
converted_type, converted_value = self._custom_helper.convert(jarray_value, 'PyArray')
self.common_test_converted(expected_value, alias_constants.JARRAY, converted_value, converted_type)
self.common_test_default(jarray_default, str(type(jarray_default)), converted_value, converted_type, False)
def testMatchesEmptyJarray(self):
jarray_value = None
expected_value = []
jarray_default = jarray.array([], String)
converted_type, converted_value = self._custom_helper.convert(jarray_value, '[L')
self.common_test_converted(expected_value, alias_constants.JARRAY, converted_value, converted_type)
self.common_test_default(jarray_default, 'PyArray', converted_value, converted_type, True)
def testBooleanDefault(self):
bool_value = Boolean(False)
expected_value = 'false'
expected_default = expected_value
converted_type, converted_value = self._custom_helper.convert(bool_value, 'java.lang.Boolean')
self.common_test_converted(expected_value, alias_constants.BOOLEAN, converted_value, converted_type)
self.common_test_default(expected_default, 'bool', converted_value, converted_type, True)
def testBooleanNotDefault(self):
bool_value = False
expected_value = 'false'
expected_default = True
converted_type, converted_value = self._custom_helper.convert(bool_value, 'bool')
self.common_test_converted(expected_value, alias_constants.BOOLEAN, converted_value, converted_type)
self.common_test_default(expected_default, 'bool', converted_value, converted_type, False)
def testDictionaryDefault(self):
dict_value = {'integer1': 111, 'integer2': 112}
dict_default = {'integer2': 112, 'integer1': 111}
converted_type, converted_value = self._custom_helper.convert(dict_value, 'dict')
self.common_test_converted(dict_value, alias_constants.PROPERTIES, converted_value, converted_type)
self.assertEquals(PyOrderedDict, type(converted_value))
self.common_test_default(dict_default, 'dict', converted_value, converted_type, True)
def testDictionaryNotDefault(self):
dict_value = {'integer1': 111, 'integer2': 112}
dict_default = dict()
converted_type, converted_value = self._custom_helper.convert(dict_value, 'dict')
self.common_test_converted(dict_value, alias_constants.PROPERTIES, converted_value, converted_type)
self.assertEquals(PyOrderedDict, type(converted_value))
self.common_test_default(dict_default, 'dict', converted_value, converted_type, False)
def testPropertiesDefault(self):
prop_value = Properties()
prop_value.setProperty('value1', 'foo')
prop_value.setProperty('value2', 'bar')
prop_value.setProperty('value3', 'equal')
prop_default = Properties(prop_value)
expected_value = {'value3': 'equal', 'value1': 'foo', 'value2': 'bar'}
converted_type, converted_value = self._custom_helper.convert(prop_value, 'java.util.Properties')
self.common_test_converted(expected_value, alias_constants.PROPERTIES, converted_value, converted_type)
self.common_test_default(prop_default, 'java.util.Properties', converted_value, converted_type, True)
def testPropertiesNotDefault(self):
prop_value = Properties()
prop_value.setProperty('value1', 'foo')
prop_value.setProperty('value2', 'bar')
prop_value.setProperty('value3', 'equal')
expected_value = {'value1': 'foo', 'value2': 'bar', 'value3': 'equal'}
prop_default = {'value2': 'foo', 'value1': 'bar', 'value3': 'equal'}
converted_type, converted_value = self._custom_helper.convert(prop_value, 'java.util.Properties')
self.common_test_converted(expected_value, alias_constants.PROPERTIES, converted_value, converted_type)
self.assertEquals(PyOrderedDict, type(converted_value))
self.common_test_default(prop_default, 'dict', converted_value, converted_type, False)
def testMapDefault(self):
map_value = HashMap()
map_value.put('value1', 'foo')
map_value.put('value2', 'bar')
map_value.put('value3', 'equal')
expected_value = {'value1': 'foo', 'value2': 'bar', 'value3': 'equal'}
map_default = HashMap()
map_default.put('value1', 'foo')
map_default.put('value2', 'bar')
map_default.put('value3', 'equal')
converted_type, converted_value = self._custom_helper.convert(map_value, 'java.util.Map')
self.common_test_converted(expected_value, alias_constants.PROPERTIES, converted_value, converted_type)
self.assertEquals(PyOrderedDict, type(converted_value))
self.common_test_default(map_default, 'java.util.Map', converted_value, converted_type, True)
def testMapNotDefault(self):
map_value = HashMap()
map_value.put('value1', 'foo')
map_value.put('value2', 'bar')
map_value.put('value3', 'equal')
expected_value = {'value1': 'foo', 'value2': 'bar', 'value3': 'equal'}
map_default = dict()
map_default['value1'] = 'eightball'
map_default['value2'] = 'bar'
map_default['value3'] = 'equal'
converted_type, converted_value = self._custom_helper.convert(map_value, 'java.util.Map')
self.common_test_converted(expected_value, alias_constants.PROPERTIES, converted_value, converted_type)
self.assertEquals(alias_constants.PROPERTIES, converted_type)
self.common_test_default(map_default, 'dict', converted_value, converted_type, False)
def testIntegerDefault(self):
port_value = '0'
expected_value = 0
default_value = expected_value
converted_type, converted_value = self._custom_helper.convert(port_value, 'java.lang.Integer')
self.common_test_converted(expected_value, alias_constants.INTEGER, converted_value, converted_type)
self.common_test_default(default_value, 'int', converted_value, converted_type, True)
def testIntegerNotDefault(self):
port_value = 1443
expected_value = port_value
default_value = 0
converted_type, converted_value = self._custom_helper.convert(port_value, 'int')
self.common_test_converted(expected_value, alias_constants.INTEGER, converted_value, converted_type)
self.common_test_default(default_value, 'int', converted_value, converted_type, False)
def testBigIntegerConvert(self):
big_value = '67999'
expected_value = 67999L
default_value = 0
converted_type, converted_value = self._custom_helper.convert(big_value, 'java.math.BigInteger')
self.common_test_converted(expected_value, alias_constants.LONG, converted_value, converted_type)
self.common_test_default(default_value, 'long', converted_value, converted_type, False)
def testDoubleConvert(self):
double_value = '67999'
expected_value = 67999
default_value = expected_value
converted_type, converted_value = self._custom_helper.convert(double_value, 'java.lang.Double')
self.common_test_converted(expected_value, alias_constants.DOUBLE, converted_value, converted_type)
self.common_test_default(default_value, 'double', converted_value, converted_type, True)
def testFloatConvert(self):
float_value = 4.2e-4
expected_value = None
converted_type, converted_value = self._custom_helper.convert(float_value, 'float')
self.common_test_converted(expected_value, None, converted_value, converted_type)
def common_test_default(self, default_value, default_type, model_value, model_type, expected):
converted_type, converted_default = self._custom_helper.convert(default_value, default_type)
return_result = self._custom_helper.is_default(model_value, model_type, converted_default)
self.assertEquals(expected, return_result)
def common_test_converted(self, expected_value, expected_type, model_value, model_type):
self.assertEquals(expected_type, model_type)
if expected_type == alias_constants.LIST:
self.is_expected_list(expected_value, model_value)
elif expected_type == alias_constants.PROPERTIES:
self.is_expected_dict(expected_value, model_value)
else:
self.is_expected(expected_value, model_value)
def is_expected(self, expected_value, model_value):
return expected_value is not None and model_value is not None and expected_value == model_value
def is_expected_list(self, expected_list, converted_list):
return expected_list is not None and converted_list is not None and \
self.roll_list(expected_list, converted_list) and self.roll_list(converted_list, expected_list)
def roll_list(self, list1, list2):
for item in list1:
if item not in list2:
return False
return True
def is_expected_dict(self, expected_dict, converted_dict):
return expected_dict is not None and converted_dict is not None and \
self.roll_dict(expected_dict, converted_dict) and self.roll_dict(converted_dict, expected_dict)
def roll_dict(self, dict1, dict2):
dict1_keys = dict1.keys()
for key in dict2.keys():
if key not in dict1_keys or dict2[key] != dict1[key]:
return False
return True
if __name__ == '__main__':
unittest.main()
| [] | [] | [] | [] | [] | python | null | null | null |
example_test.go | package darksky_test
import (
"context"
"fmt"
"os"
"time"
"github.com/trende-jp/go-darksky"
)
func ExampleClient_Forecast() {
c, err := darksky.NewClient(
darksky.WithKey(os.Getenv("DARKSKY_KEY")),
)
if err != nil {
fmt.Println(err)
return
}
ctx := context.Background()
forecast, err := c.Forecast(ctx, 42.3601, -71.0589, nil, nil)
if err != nil {
fmt.Println(err)
return
}
// This example requests the current forecast, which varies from day to day.
// Output only that which is constant.
fmt.Println(forecast.Latitude)
fmt.Println(forecast.Longitude)
fmt.Println(forecast.Timezone)
fmt.Println(forecast.Flags.Units)
// Output:
// 42.3601
// -71.0589
// America/New_York
// us
}
func ExampleClient_Forecast_minimal() {
c, err := darksky.NewClient(
darksky.WithKey(os.Getenv("DARKSKY_KEY")),
)
if err != nil {
fmt.Println(err)
return
}
ctx := context.Background()
forecast, err := c.Forecast(ctx, 42.3601, -71.0589, nil, &darksky.ForecastOptions{
Units: darksky.UnitsSI,
})
if err != nil {
fmt.Println(err)
return
}
// The forecast varies from day to day. Print something stable.
fmt.Println(forecast.Timezone)
// Output:
// America/New_York
}
func ExampleClient_Forecast_timeMachine() {
c, err := darksky.NewClient(
darksky.WithKey(os.Getenv("DARKSKY_KEY")),
)
if err != nil {
fmt.Println(err)
return
}
ctx := context.Background()
t := &darksky.Time{
Time: time.Date(2019, 1, 1, 0, 0, 0, 0, time.UTC),
}
forecast, err := c.Forecast(ctx, 42.3601, -71.0589, t, nil)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(forecast.Currently.Icon)
// Output: cloudy
}
| [
"\"DARKSKY_KEY\"",
"\"DARKSKY_KEY\"",
"\"DARKSKY_KEY\""
] | [] | [
"DARKSKY_KEY"
] | [] | ["DARKSKY_KEY"] | go | 1 | 0 | |
squad_game/squad_game/asgi.py | """
ASGI config for squad_game project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'squad_game.settings')
application = get_asgi_application()
| [] | [] | [] | [] | [] | python | 0 | 0 | |
examples/suppression/GetAllSpamReports.java | import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sendgrid.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
//////////////////////////////////////////////////////////////////
// Retrieve all spam reports
// GET /suppression/spam_reports
public class GetAllSpamReports {
public static void main(String[] args) throws IOException {
try {
SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY"));
Request request = new Request();
request.setMethod(Method.GET);
request.setEndpoint("suppression/spam_reports");
request.addQueryParam("start_time", "1");
request.addQueryParam("limit", "1");
request.addQueryParam("end_time", "1");
request.addQueryParam("offset", "1");
Response response = sg.api(request);
System.out.println(response.getStatusCode());
System.out.println(response.getBody());
System.out.println(response.getHeaders());
} catch (IOException ex) {
throw ex;
}
}
} | [
"\"SENDGRID_API_KEY\""
] | [] | [
"SENDGRID_API_KEY"
] | [] | ["SENDGRID_API_KEY"] | java | 1 | 0 | |
test/e2e/operator/validate/validate.go | /*
Copyright 2019 Intel Corporation.
SPDX-License-Identifier: Apache-2.0
*/
// Package validate contains code to check objects deployed by the operator
// as part of an E2E test.
package validate
import (
"context"
"errors"
"fmt"
"os"
"reflect"
"sort"
"strings"
"time"
api "github.com/intel/pmem-csi/pkg/apis/pmemcsi/v1beta1"
"github.com/intel/pmem-csi/pkg/deployments"
operatordeployment "github.com/intel/pmem-csi/pkg/pmem-csi-operator/controller/deployment"
"github.com/intel/pmem-csi/pkg/pmem-csi-operator/metrics"
"github.com/intel/pmem-csi/pkg/version"
"github.com/intel/pmem-csi/test/e2e/deploy"
apierrs "k8s.io/apimachinery/pkg/api/errors"
cm "github.com/prometheus/client_model/go"
"gopkg.in/yaml.v2"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"sigs.k8s.io/controller-runtime/pkg/client"
)
// DriverDeployment compares all objects as deployed by the operator against the expected
// objects for a certain deployment spec. deploymentSpec should only have those fields
// set which are not the defaults. This call will wait for the expected objects until
// the context times out.
func DriverDeploymentEventually(ctx context.Context, c *deploy.Cluster, client client.Client, k8sver version.Version, metricsURL, namespace string, deployment api.PmemCSIDeployment, lastCount float64) (float64, error) {
if deployment.GetUID() == "" {
return 0, errors.New("deployment not an object that was stored in the API server, no UID")
}
endCount, err := WaitForDeploymentReconciled(ctx, c, metricsURL, deployment, lastCount)
if err != nil {
return 0, err
}
// As the reconcile is done, check if the deployed driver is valid ...
if err := DriverDeployment(ctx, client, k8sver, namespace, deployment); err != nil {
return 0, err
}
return endCount, nil
}
// WaitForDeploymentReconciled waits and checks till the context timedout
// that if given deployment got reconciled by the operator.
// It checks in the operator metrics for a new 'pmem_csi_deployment_reconcile'
// metric count is greater that the lastCount. If found it returns the new reconcile count.
func WaitForDeploymentReconciled(ctx context.Context, c *deploy.Cluster, metricsURL string, deployment api.PmemCSIDeployment, lastCount float64) (float64, error) {
deploymentMap := map[string]string{
"name": deployment.Name,
"uid": string(deployment.UID),
}
lblPairToMap := func(lbls []*cm.LabelPair) map[string]string {
res := map[string]string{}
for _, lbl := range lbls {
res[lbl.GetName()] = lbl.GetValue()
}
return res
}
ready := func() (float64, error) {
name := "pmem_csi_deployment_reconcile"
mf, err := deploy.GetMetrics(ctx, c, metricsURL)
if err != nil {
return 0, err
}
metric, ok := mf[name]
if !ok {
return 0, fmt.Errorf("expected '%s' metric not found:\n %v", name, mf)
}
for _, m := range metric.GetMetric() {
if c := m.Counter.GetValue(); c > lastCount {
if reflect.DeepEqual(deploymentMap, lblPairToMap(m.GetLabel())) {
return c, nil
}
}
}
return 0, fmt.Errorf("'%s' metric not found with with count higher than %f", name, lastCount)
}
if endCount, err := ready(); err == nil {
return endCount, nil
}
ticker := time.NewTicker(1 * time.Second)
defer ticker.Stop()
var lastErr error
for {
select {
case <-ticker.C:
endCount, err := ready()
if err == nil {
return endCount, nil
}
lastErr = err
case <-ctx.Done():
return 0, fmt.Errorf("timed out waiting for deployment metric, last error: %v", lastErr)
}
}
}
// CheckForObjectUpdates wait and checks for deployed driver components
// in consistent state. That means no unnecessary updates occurred and all
// expected object updates passed in expectedUpdates have occurred.
// It uses the 'pmem_csi_deployment_sub_resource_updated_at' metric.
//
// Beware that this check only works if a test calling it uses a new
// deployment with a unique UID. Otherwise object updates from a
// previous test may get picked up.
//
// When the CR just got created, the operator should
// immediately create objects with the right content and then
// not update them again unless it is an expected update from the
// caller.
func CheckForObjectUpdates(ctx context.Context, c *deploy.Cluster, metricsURL string, expectedUpdates []client.Object, deployment api.PmemCSIDeployment) error {
type updateInfo struct {
expectedObjectLabels []map[string]string
isFound []bool
}
info := updateInfo{}
for _, o := range expectedUpdates {
info.expectedObjectLabels = append(info.expectedObjectLabels, metrics.GetSubResourceLabels(o))
info.isFound = append(info.isFound, false)
}
// isUpdateExpected check if the given object labels match with the
// expectedObjectLabels,
isUpdateExpected := func(labels map[string]string) bool {
for i, ol := range info.expectedObjectLabels {
if reflect.DeepEqual(ol, labels) {
info.isFound[i] = true
return true
}
}
return false
}
checkObjectUpdates := func() error {
mf, err := deploy.GetMetrics(ctx, c, metricsURL)
if err != nil {
return err
}
updates, ok := mf["pmem_csi_deployment_sub_resource_updated_at"]
if !ok {
return nil
}
unExpectedList := []string{}
for _, m := range updates.GetMetric() {
lblMap := labelPairToMap(m.GetLabel())
if strings.Contains(lblMap["ownedBy"], string(deployment.UID)) && !isUpdateExpected(lblMap) {
unExpectedList = append(unExpectedList, fmt.Sprintf("%+v", lblMap))
}
}
if len(unExpectedList) != 0 {
return fmt.Errorf("unexpected sub-object updates by the operator:\n%s", strings.Join(unExpectedList, "\n"))
}
return nil
}
deadline, cancel := context.WithTimeout(ctx, 10*time.Second)
ticker := time.NewTicker(1 * time.Second)
defer cancel()
for {
select {
case <-ticker.C:
// check if any updates recorded after last end of reconcile.
if err := checkObjectUpdates(); err != nil {
return err
}
case <-deadline.Done():
strList := []string{}
for i, l := range info.expectedObjectLabels {
if !info.isFound[i] {
strList = append(strList, fmt.Sprintf("%+v", l))
}
}
if len(strList) != 0 {
return fmt.Errorf("expected sub-object were not updated by the operator: %s", strings.Join(strList, "\n"))
}
return nil
}
}
}
// DriverDeployment compares all objects as deployed by the operator against the expected
// objects for a certain deployment spec. deploymentSpec should only have those fields
// set which are not the defaults. The caller must ensure that the operator is done
// with creating objects.
//
// A final error is returned when observing a problem that is not going to go away,
// like an unexpected update of an object.
func DriverDeployment(ctx context.Context, c client.Client, k8sver version.Version, namespace string, deployment api.PmemCSIDeployment) error {
if deployment.GetUID() == "" {
return errors.New("deployment not an object that was stored in the API server, no UID")
}
// The operator currently always uses the production image. We
// can only find that indirectly.
driverImage := strings.Replace(os.Getenv("PMEM_CSI_IMAGE"), "-test", "", 1)
if err := (&deployment).EnsureDefaults(driverImage); err != nil {
return err
}
// Validate sub-objects. A sub-object is anything that has the deployment object as owner.
objects, err := listAllDeployedObjects(ctx, c, deployment, namespace)
if err != nil {
return err
}
// Load secret if it exists. If it doesn't, we validate without it.
var controllerCABundle []byte
if deployment.Spec.ControllerTLSSecret != "" {
secret := &corev1.Secret{
TypeMeta: metav1.TypeMeta{
APIVersion: "v1",
Kind: "Secret",
},
}
objKey := client.ObjectKey{
Namespace: namespace,
Name: deployment.Spec.ControllerTLSSecret,
}
if err := c.Get(ctx, objKey, secret); err != nil {
if !apierrs.IsNotFound(err) {
return err
}
} else {
if ca, ok := secret.Data[api.TLSSecretCA]; ok {
controllerCABundle = ca
}
}
}
expectedObjects, err := deployments.LoadAndCustomizeObjects(k8sver, deployment.Spec.DeviceMode, namespace, deployment, controllerCABundle)
if err != nil {
return fmt.Errorf("customize expected objects: %v", err)
}
var diffs []string
for _, actual := range objects {
expected := findObject(expectedObjects, actual)
if expected == nil {
diffs = append(diffs, fmt.Sprintf("unexpected object was deployed: %s", prettyPrintObjectID(actual)))
continue
}
// Of the meta data, we have already compared type,
// name and namespace. In addition to that we only
// care about labels.
expectedLabels := expected.GetLabels()
actualLabels := actual.GetLabels()
for key, value := range expectedLabels {
if key == "pmem-csi.intel.com/deployment" &&
(deployment.Labels == nil || deployment.Labels["pmem-csi.intel.com/deployment"] == "") {
// This particular label is part of
// the reference YAMLs but not
// currently added by the operator
// unless specifically requested.
// Ignore it...
continue
}
actualValue, found := actualLabels[key]
if !found {
diffs = append(diffs, fmt.Sprintf("label %s missing for %s", key, prettyPrintObjectID(*expected)))
} else if actualValue != value {
diffs = append(diffs, fmt.Sprintf("label %s of %s is wrong: expected %q, got %q", key, prettyPrintObjectID(*expected), value, actualValue))
}
}
// Certain top-level fields must be identical.
fields := map[string]bool{}
for field := range expected.Object {
fields[field] = true
}
for field := range actual.Object {
fields[field] = true
}
for field := range fields {
switch field {
case "metadata", "status":
// Verified above or may vary.
continue
}
expectedField := expected.Object[field]
actualField := actual.Object[field]
diff := compare(expected.GetKind(), field, expectedField, actualField)
if diff != nil {
diffs = append(diffs, fmt.Sprintf("%s content for %s does not match:\n %s", field, prettyPrintObjectID(*expected), strings.Join(diff, "\n ")))
}
}
}
for _, expected := range expectedObjects {
if findObject(objects, expected) == nil {
diffs = append(diffs, fmt.Sprintf("expected object was not deployed: %v", prettyPrintObjectID(expected)))
}
}
if diffs != nil {
return fmt.Errorf("deployed driver different from expected deployment:\n%s", strings.Join(diffs, "\n"))
}
return nil
}
// When we get an object back from the apiserver, some fields get populated with generated
// or fixed default values. defaultSpecValues contains a hierarchy of maps that stores those
// defaults:
// Kind -> field -> field -> ... -> value
//
// Those defaults are used when the original object didn't have a field value.
// "ignore" is a special value which let's the comparison skip the field.
var defaultValues = parseDefaultValues()
func parseDefaultValues() map[string]interface{} {
var defaults map[string]interface{}
defaultsApps := `
spec:
revisionHistoryLimit: 10
podManagementPolicy: OrderedReady
selector:
matchLabels:
pmem-csi.intel.com/deployment: ignore # labels are tested separately
template:
metadata:
labels:
pmem-csi.intel.com/deployment: ignore # labels are tested separately
spec:
dnsPolicy: ClusterFirst
restartPolicy: Always
serviceAccount: ignore # redundant field, always returned by apiserver in addition to serviceAccountName
schedulerName: default-scheduler
terminationGracePeriodSeconds: 30
containers:
terminationMessagePath: /dev/termination-log
terminationMessagePolicy: File
imagePullPolicy: IfNotPresent
ports:
protocol: TCP
env:
valueFrom:
fieldRef:
apiVersion: v1
volumes:
secret:
defaultMode: 420`
defaultsYAML := `
Service:
spec:
clusterIP: ignore
clusterIPs: ignore # since k8s v1.20
externalTrafficPolicy: Cluster
ipFamilies:
- IPv4
ipFamilyPolicy: SingleStack
ports:
protocol: TCP
nodePort: ignore
selector:
pmem-csi.intel.com/deployment: ignore # labels are tested separately
sessionAffinity: None
type: ClusterIP
internalTrafficPolicy: Cluster
ServiceAccount:
secrets: ignore
imagePullSecrets: ignore # injected on OpenShift
DaemonSet:` + defaultsApps + `
updateStrategy: ignore
Deployment:` + defaultsApps + `
progressDeadlineSeconds: ignore
strategy: ignore
StatefulSet:` + defaultsApps + `
updateStrategy: ignore
CSIDriver:
spec:
storageCapacity: false
fsGroupPolicy: ignore # currently PMEM-CSI driver does not support fsGroupPolicy
requiresRepublish: false
MutatingWebhookConfiguration:
webhooks:
clientConfig:
caBundle: ignore # Can change, in particular when generated by OpenShift.
service:
port: 443
admissionReviewVersions:
- v1beta1
matchPolicy: Equivalent # default policy in v1
reinvocationPolicy: Never
rules:
scope: "*"
sideEffects: Unknown
timeoutSeconds: 10 # default timeout in v1
`
err := yaml.UnmarshalStrict([]byte(defaultsYAML), &defaults)
if err != nil {
panic(err)
}
return defaults
}
// compare is like reflect.DeepEqual, except that it reports back all changes
// in a diff-like format, with one entry per added, removed or different field.
// In addition, it fills in default values in the expected spec if they are missing
// before comparing against the actual value. This makes it possible to
// compare the on-disk YAML files which are typically not complete against
// objects from the apiserver which have all defaults filled in.
func compare(kind string, field string, expected, actual interface{}) []string {
defaults := defaultValues[kind]
if defaultsMap, ok := defaults.(map[interface{}]interface{}); ok {
defaults = defaultsMap[field]
}
return compareSpecRecursive(field, defaults, expected, actual)
}
func compareSpecRecursive(path string, defaults, expected, actual interface{}) (diffs []string) {
if expected == nil && actual == nil {
return nil
}
// Some paths do not need to be compared.
if ignore, ok := defaults.(string); ok && ignore == "ignore" {
return nil
}
// Inject defaults?
if actual != nil && expected == nil {
expected = defaults
}
// Missing value.
if actual == nil && expected != nil {
return []string{fmt.Sprintf("- %s = %v", path, expected)}
}
// Extra value.
if actual != nil && expected == nil {
// We cannot express an empty map in the YAML defaults, but do get
// it from the apiserver for fields like securityContext or emptyDir.
// Can be ignored.
if value, ok := actual.(map[string]interface{}); ok && len(value) == 0 {
return nil
}
return []string{fmt.Sprintf("+ %s = %v", path, actual)}
}
// Different types?
expectedValue := reflect.ValueOf(expected)
actualValue := reflect.ValueOf(actual)
if expectedValue.Kind() != actualValue.Kind() {
// This might just be a int vs. int64 mismatch, which
// can happen because decoding doesn't know the size.
if (expectedValue.Kind() == reflect.Int && actualValue.Kind() == reflect.Int64 ||
expectedValue.Kind() == reflect.Int64 && actualValue.Kind() == reflect.Int) &&
expectedValue.Int() == actualValue.Int() {
return nil
}
return []string{fmt.Sprintf("! %s mismatched type, expected %v (%T), got %v (%T)", path, expected, expected, actual, actual)}
}
// For lists and maps we need to recurse, everything else
// can be compare as-is.
switch expectedValue.Kind() {
case reflect.Map:
expectedMap := toMap(expected)
actualMap := toMap(actual)
defaultsMap := map[string]interface{}{}
if defaults != nil {
defaultsMap = toMap(defaults)
}
// Gather and sort all keys before iterating over them to make
// the result deterministic.
keys := map[string]bool{}
for key := range actualMap {
keys[key] = true
}
for key := range expectedMap {
keys[key] = true
}
var sortedKeys []string
for key := range keys {
sortedKeys = append(sortedKeys, key)
}
sort.Strings(sortedKeys)
for _, key := range sortedKeys {
diffs = append(diffs, compareSpecRecursive(path+"."+key, defaultsMap[key], expectedMap[key], actualMap[key])...)
}
case reflect.Slice:
// The order in lists is expected to match. The defaults are the same for all entries.
expectedList := expected.([]interface{})
actualList := actual.([]interface{})
i := 0
for ; i < len(expectedList) || i < len(actualList); i++ {
var expectedEntry, actualEntry interface{}
if i < len(expectedList) {
expectedEntry = expectedList[i]
}
if i < len(actualList) {
actualEntry = actualList[i]
}
diffs = append(diffs, compareSpecRecursive(fmt.Sprintf("%s.#%d", path, i), defaults, expectedEntry, actualEntry)...)
}
default:
if !reflect.DeepEqual(expected, actual) {
return []string{fmt.Sprintf("! %s expected %v, got %v", path, expected, actual)}
}
}
return
}
func toMap(value interface{}) map[string]interface{} {
switch m := value.(type) {
case map[string]interface{}:
return m
case map[interface{}]interface{}:
// We get this after decoding YAML.
m2 := map[string]interface{}{}
for key, value := range m {
m2[fmt.Sprintf("%v", key)] = value
}
return m2
default:
panic(fmt.Errorf("unexpected map type %T for %v", value, value))
}
}
func findObject(hay []unstructured.Unstructured, needle unstructured.Unstructured) *unstructured.Unstructured {
gvk := needle.GetObjectKind().GroupVersionKind()
name := needle.GetName()
namespace := needle.GetNamespace()
for _, obj := range hay {
if obj.GetObjectKind().GroupVersionKind() == gvk &&
obj.GetName() == name &&
obj.GetNamespace() == namespace {
return &obj
}
}
return nil
}
func prettyPrintObjectID(object unstructured.Unstructured) string {
return fmt.Sprintf("%q of type %q in namespace %q",
object.GetName(),
object.GetObjectKind().GroupVersionKind(),
object.GetNamespace())
}
func listAllDeployedObjects(ctx context.Context, c client.Client, deployment api.PmemCSIDeployment, namespace string) ([]unstructured.Unstructured, error) {
objects := []unstructured.Unstructured{}
for _, list := range operatordeployment.AllObjectLists() {
opts := &client.ListOptions{
Namespace: namespace,
}
// Test client does not support differentiating cluster-scoped objects
// and the query fails when fetch those object by setting the namespace-
switch list.GetKind() {
case "CSIDriverList", "ClusterRoleList", "ClusterRoleBindingList", "MutatingWebhookConfigurationList":
opts = &client.ListOptions{}
}
// Filtering by owner doesn't work, so we have to use brute-force and look at all
// objects.
if err := c.List(ctx, list, opts); err != nil {
return objects, fmt.Errorf("list %s: %v", list.GetObjectKind(), err)
}
outer:
for _, object := range list.Items {
owners := object.GetOwnerReferences()
for _, owner := range owners {
if owner.UID == deployment.UID {
objects = append(objects, object)
continue outer
}
}
}
}
return objects, nil
}
func labelPairToMap(pairs []*cm.LabelPair) map[string]string {
labels := map[string]string{}
for _, lbl := range pairs {
labels[lbl.GetName()] = lbl.GetValue()
}
return labels
}
| [
"\"PMEM_CSI_IMAGE\""
] | [] | [
"PMEM_CSI_IMAGE"
] | [] | ["PMEM_CSI_IMAGE"] | go | 1 | 0 | |
test/toolset-mock/src/MockProgram.py | # Copyright 2017 Steven Watanabe
#
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
from __future__ import print_function
import sys
import os
import re
import fnmatch
# Represents a sequence of arguments that must appear
# in a fixed order.
class ordered:
def __init__(self, *args):
self.args = args
def match(self, command_line, pos, outputs):
for p in self.args:
res = try_match(command_line, pos, p, outputs)
if res is None:
return
pos = res
return pos
# Represents a sequence of arguments that can appear
# in any order.
class unordered:
def __init__(self, *args):
self.args = list(args)
def match(self, command_line, pos, outputs):
unmatched = self.args[:]
while len(unmatched) > 0:
res = try_match_one(command_line, pos, unmatched, outputs)
if res is None:
return
pos = res
return pos
# Represents a single input file.
# If id is set, then the file must have been created
# by a prior use of output_file.
# If source is set, then the file must be that source file.
class input_file:
def __init__(self, id=None, source=None):
assert((id is None) ^ (source is None))
self.id = id
self.source = source
def check(self, path):
if path.startswith("-"):
return
if self.id is not None:
try:
with open(path, "r") as f:
data = f.read()
if data == make_file_contents(self.id):
return True
else:
return
except:
return
elif self.source is not None:
if self.source == path:
return True
else:
return
assert(False)
def match(self, command_line, pos, outputs):
if self.check(command_line[pos]):
return pos + 1
# Matches an output file.
# If the full pattern is matched, The
# file will be created.
class output_file:
def __init__(self, id):
self.id = id
def match(self, command_line, pos, outputs):
if command_line[pos].startswith("-"):
return
outputs.append((command_line[pos], self.id))
return pos + 1
class arg_file:
def __init__(self, id):
self.id = id
def match(self, command_line, pos, outputs):
if command_line[pos].startswith("-"):
return
if fnmatch.fnmatch(command_line[pos], self.id):
return pos + 1
else:
return
# Matches the directory containing an input_file
class target_path(object):
def __init__(self, id):
self.tester = input_file(id=id)
def match(self, command_line, pos, outputs):
arg = command_line[pos]
if arg.startswith("-"):
return
try:
for path in os.listdir(arg):
if self.tester.check(os.path.join(arg, path)):
return pos + 1
except:
return
# Matches a single argument, which is composed of a prefix and a path
# for example arguments of the form -ofilename.
class arg(object):
def __init__(self, prefix, a):
# The prefix should be a string, a should be target_path or input_file.
self.prefix = prefix
self.a = a
def match(self, command_line, pos, outputs):
s = command_line[pos]
if s.startswith(self.prefix) and try_match([s[len(self.prefix):]], 0, self.a, outputs) == 1:
return pos + 1
# Given a file id, returns a string that will be
# written to the file to allow it to be recognized.
def make_file_contents(id):
return id
# Matches a single pattern from a list.
# If it succeeds, the matching pattern
# is removed from the list.
# Returns the index after the end of the match
def try_match_one(command_line, pos, patterns, outputs):
for p in patterns:
tmp = outputs[:]
res = try_match(command_line, pos, p, tmp)
if res is not None:
outputs[:] = tmp
patterns.remove(p)
return res
# returns the end of the match if any
def try_match(command_line, pos, pattern, outputs):
if pos == len(command_line):
return
elif type(pattern) is str:
if pattern == command_line[pos]:
return pos + 1
else:
return pattern.match(command_line, pos, outputs)
known_patterns = []
program_name = None
# Registers a command
# The arguments should be a sequence of:
# str, ordered, unordered, arg, input_file, output_file, target_path
# kwarg: stdout is text that will be printed on success.
def command(*args, **kwargs):
global known_patterns
global program_name
stdout = kwargs.get("stdout", None)
pattern = ordered(*args)
known_patterns += [(pattern, stdout)]
if program_name is None:
program_name = args[0]
else:
assert(program_name == args[0])
# Use this to filter the recognized commands, based on the properties
# passed to b2.
def allow_properties(*args):
try:
return all(a in os.environ["B2_PROPERTIES"].split(" ") for a in args)
except KeyError:
return True
# Use this in the stdout argument of command to print the command
# for running another script.
def script(name):
return os.path.join(os.path.dirname(__file__), "bin", re.sub('\.py$', '', name))
def match(command_line):
for (p, stdout) in known_patterns:
outputs = []
if try_match(command_line, 0, p, outputs) == len(command_line):
return (stdout, outputs)
# Every mock program should call this after setting up all the commands.
def main():
command_line = [program_name] + sys.argv[1:]
result = match(command_line)
if result is not None:
(stdout, outputs) = result
if stdout is not None:
print(stdout)
for (file,id) in outputs:
with open(file, "w") as f:
f.write(make_file_contents(id))
exit(0)
else:
print("ERROR on command: %s"%(" ".join(command_line)))
exit(1)
# file should be the name of a file in the same directory
# as this. Must be called after verify_setup
def verify_file(filename):
global known_files
if filename not in known_files:
known_files.add(filename)
srcdir = os.path.dirname(__file__)
execfile(os.path.join(srcdir, filename), {})
def verify_setup():
"""Override the behavior of most module components
in order to detect whether they are being used correctly."""
global main
global allow_properties
global output_file
global input_file
global target_path
global script
global command
global verify_errors
global output_ids
global input_ids
global known_files
def allow_properties(*args):
return True
def main():
pass
def output_file(id):
global output_ids
global verify_error
if id in output_ids:
verify_error("duplicate output_file: %s" % id)
output_ids.add(id)
def input_file(id=None, source=None):
if id is not None:
input_ids.add(id)
def target_path(id):
input_ids.add(id)
def script(filename):
verify_file(filename)
def command(*args, **kwargs):
pass
verify_errors = []
output_ids = set()
input_ids = set()
known_files = set()
def verify_error(message):
global verify_errors
verify_errors += [message]
def verify_finalize():
for id in input_ids:
if not id in output_ids:
verify_error("Input file does not exist: %s" % id)
for error in verify_errors:
print("error: %s" % error)
if len(verify_errors) != 0:
return 1
else:
return 0
def verify():
srcdir = os.path.dirname(__file__)
if srcdir == '':
srcdir = '.'
verify_setup()
for f in os.listdir(srcdir):
if re.match(r"(gcc|clang|darwin|intel)-.*\.py", f):
verify_file(f)
exit(verify_finalize())
| [] | [] | [
"B2_PROPERTIES"
] | [] | ["B2_PROPERTIES"] | python | 1 | 0 | |
release/.buildkite/build_pipeline.py | import copy
import logging
import os
import sys
import yaml
# Env variables:
# RAY_REPO Repo to use for finding the wheel
# RAY_BRANCH Branch to find the wheel
# RAY_VERSION Version to find the wheel
# RAY_WHEELS Direct Ray wheel URL
# RAY_TEST_REPO Repo to use for test scripts
# RAY_TEST_BRANCH Branch for test scripts
# FILTER_FILE File filter
# FILTER_TEST Test name filter
# RELEASE_TEST_SUITE Release test suite (e.g. manual, nightly)
class ReleaseTest:
def __init__(self, name: str, smoke_test: bool = False, retry: int = 0):
self.name = name
self.smoke_test = smoke_test
self.retry = retry
def __str__(self):
return self.name
def __repr__(self):
return self.name
def __contains__(self, item):
return self.name.__contains__(item)
def __iter__(self):
return iter(self.name)
def __len__(self):
return len(self.name)
class SmokeTest(ReleaseTest):
def __init__(self, name: str, retry: int = 0):
super(SmokeTest, self).__init__(
name=name, smoke_test=True, retry=retry)
CORE_NIGHTLY_TESTS = {
"~/ray/release/nightly_tests/nightly_tests.yaml": [
"shuffle_10gb",
"shuffle_50gb",
"shuffle_50gb_large_partition",
"shuffle_100gb",
"non_streaming_shuffle_100gb",
"non_streaming_shuffle_50gb_large_partition",
"non_streaming_shuffle_50gb",
"dask_on_ray_10gb_sort",
"dask_on_ray_100gb_sort",
SmokeTest("dask_on_ray_large_scale_test_no_spilling"),
SmokeTest("dask_on_ray_large_scale_test_spilling"),
"stress_test_placement_group",
"shuffle_1tb_1000_partition",
"non_streaming_shuffle_1tb_1000_partition",
"shuffle_1tb_5000_partitions",
# TODO(sang): It doesn't even work without spilling
# as it hits the scalability limit.
# "non_streaming_shuffle_1tb_5000_partitions",
"decision_tree_autoscaling",
"decision_tree_autoscaling_20_runs",
"grpc_decision_tree_autoscaling_20_runs",
"autoscaling_shuffle_1tb_1000_partitions",
SmokeTest("stress_test_many_tasks"),
SmokeTest("stress_test_dead_actors"),
"shuffle_data_loader",
"dask_on_ray_1tb_sort",
"many_nodes_actor_test",
],
"~/ray/benchmarks/benchmark_tests.yaml": [
"single_node",
"object_store",
"many_actors_smoke_test",
"many_tasks_smoke_test",
"many_pgs_smoke_test",
],
"~/ray/release/nightly_tests/dataset/dataset_test.yaml": [
"inference",
"shuffle_data_loader",
"pipelined_training_50_gb",
"pipelined_ingestion_1500_gb_15_windows",
],
}
NIGHTLY_TESTS = {
# "~/ray/release/horovod_tests/horovod_tests.yaml": [
# SmokeTest("horovod_test"),
# ], # Should we enable this?
"~/ray/release/golden_notebook_tests/golden_notebook_tests.yaml": [
"dask_xgboost_test",
"modin_xgboost_test",
"torch_tune_serve_test",
],
"~/ray/release/nightly_tests/nightly_tests.yaml": [
"dask_on_ray_large_scale_test_no_spilling",
"dask_on_ray_large_scale_test_spilling",
"pg_autoscaling_regression_test",
],
"~/ray/release/long_running_tests/long_running_tests.yaml": [
SmokeTest("actor_deaths"),
SmokeTest("apex"),
SmokeTest("impala"),
SmokeTest("many_actor_tasks"),
SmokeTest("many_drivers"),
SmokeTest("many_ppo"),
SmokeTest("many_tasks"),
SmokeTest("many_tasks_serialized_ids"),
SmokeTest("node_failures"),
SmokeTest("pbt"),
# SmokeTest("serve"),
# SmokeTest("serve_failure"),
],
"~/ray/release/microbenchmark/microbenchmark.yaml": [
"microbenchmark",
],
"~/ray/release/sgd_tests/sgd_tests.yaml": [
"sgd_gpu",
],
"~/ray/release/tune_tests/scalability_tests/tune_tests.yaml": [
"bookkeeping_overhead",
"durable_trainable",
SmokeTest("long_running_large_checkpoints"),
SmokeTest("network_overhead"),
"result_throughput_cluster",
"result_throughput_single_node",
"xgboost_sweep",
],
"~/ray/release/xgboost_tests/xgboost_tests.yaml": [
"train_small",
"train_moderate",
"train_gpu",
"tune_small",
"tune_4x32",
"tune_32x4",
"ft_small_elastic",
"ft_small_non_elastic",
"distributed_api_test",
],
"~/ray/release/rllib_tests/rllib_tests.yaml": [
SmokeTest("learning_tests"),
SmokeTest("stress_tests"),
"multi_gpu_learning_tests",
"multi_gpu_with_lstm_learning_tests",
"multi_gpu_with_attention_learning_tests",
# We'll have these as per-PR tests soon.
# "example_scripts_on_gpu_tests",
],
"~/ray/release/serve_tests/serve_tests.yaml": [
"single_deployment_1k_noop_replica",
"multi_deployment_1k_noop_replica",
"serve_micro_benchmark",
"serve_cluster_fault_tolerance",
],
"~/ray/release/runtime_env_tests/runtime_env_tests.yaml": [
"rte_many_tasks_actors",
"wheel_urls",
],
}
WEEKLY_TESTS = {
"~/ray/benchmarks/benchmark_tests.yaml": [
"many_actors",
"many_tasks",
"many_pgs",
"many_nodes",
],
"~/ray/release/nightly_tests/nightly_tests.yaml": [
"stress_test_many_tasks",
"stress_test_dead_actors",
],
"~/ray/release/horovod_tests/horovod_tests.yaml": [
"horovod_test",
],
"~/ray/release/long_running_distributed_tests"
"/long_running_distributed.yaml": [
"pytorch_pbt_failure",
],
# Full long running tests (1 day runtime)
"~/ray/release/long_running_tests/long_running_tests.yaml": [
"actor_deaths",
"apex",
"impala",
"many_actor_tasks",
"many_drivers",
"many_ppo",
"many_tasks",
"many_tasks_serialized_ids",
"node_failures",
"pbt",
"serve",
"serve_failure",
],
"~/ray/release/tune_tests/scalability_tests/tune_tests.yaml": [
"network_overhead",
"long_running_large_checkpoints",
],
"~/ray/release/rllib_tests/rllib_tests.yaml": [
"learning_tests",
"stress_tests",
],
}
MANUAL_TESTS = {
"~/ray/release/long_running_tests/long_running_tests.yaml": [
SmokeTest("serve"),
SmokeTest("serve_failure"),
]
}
SUITES = {
"core-nightly": CORE_NIGHTLY_TESTS,
"nightly": NIGHTLY_TESTS,
"weekly": WEEKLY_TESTS,
"manual": MANUAL_TESTS,
}
DEFAULT_STEP_TEMPLATE = {
"env": {
"ANYSCALE_CLOUD_ID": "cld_4F7k8814aZzGG8TNUGPKnc",
"ANYSCALE_PROJECT": "prj_2xR6uT6t7jJuu1aCwWMsle",
"RELEASE_AWS_BUCKET": "ray-release-automation-results",
"RELEASE_AWS_LOCATION": "dev",
"RELEASE_AWS_DB_NAME": "ray_ci",
"RELEASE_AWS_DB_TABLE": "release_test_result",
"AWS_REGION": "us-west-2"
},
"agents": {
"queue": "runner_queue_branch"
},
"plugins": [{
"docker#v3.8.0": {
"image": "rayproject/ray",
"propagate-environment": True,
"volumes": [
"/tmp/ray_release_test_artifacts:"
"/tmp/ray_release_test_artifacts"
],
}
}],
"commands": [],
"artifact_paths": ["/tmp/ray_release_test_artifacts/**/*"],
}
def ask_configuration():
RAY_BRANCH = os.environ.get("RAY_BRANCH", "master")
RAY_REPO = os.environ.get("RAY_REPO",
"https://github.com/ray-project/ray.git")
RAY_VERSION = os.environ.get("RAY_VERSION", "")
RAY_WHEELS = os.environ.get("RAY_WHEELS", "")
RAY_TEST_BRANCH = os.environ.get("RAY_TEST_BRANCH", RAY_BRANCH)
RAY_TEST_REPO = os.environ.get("RAY_TEST_REPO", RAY_REPO)
RELEASE_TEST_SUITE = os.environ.get("RELEASE_TEST_SUITE", "nightly")
FILTER_FILE = os.environ.get("FILTER_FILE", "")
FILTER_TEST = os.environ.get("FILTER_TEST", "")
input_ask_step = {
"input": "Input required: Please specify tests to run",
"fields": [
{
"text": ("RAY_REPO: Please specify the Ray repository used "
"to find the wheel."),
"hint": ("Repository from which to fetch the latest "
"commits to find the Ray wheels. Usually you don't "
"need to change this."),
"default": RAY_REPO,
"key": "ray_repo"
},
{
"text": ("RAY_BRANCH: Please specify the Ray branch used "
"to find the wheel."),
"hint": "For releases, this will be e.g. `releases/1.x.0`",
"default": RAY_BRANCH,
"key": "ray_branch"
},
{
"text": ("RAY_VERSION: Please specify the Ray version used "
"to find the wheel."),
"hint": ("Leave empty for latest master. For releases, "
"specify the release version."),
"required": False,
"default": RAY_VERSION,
"key": "ray_version"
},
{
"text": "RAY_WHEELS: Please specify the Ray wheel URL.",
"hint": ("ATTENTION: If you provide this, RAY_REPO, "
"RAY_BRANCH and RAY_VERSION will be ignored! "
"Please also make sure to provide the wheels URL "
"for Python 3.7 on Linux.\n"
"You can also insert a commit hash here instead "
"of a full URL.\n"
"NOTE: You can specify multiple commits or URLs "
"for easy bisection (one per line) - this will "
"run each test on each of the specified wheels."),
"required": False,
"default": RAY_WHEELS,
"key": "ray_wheels"
},
{
"text": ("RAY_TEST_REPO: Please specify the Ray repository "
"used to find the tests you would like to run."),
"hint": ("If you're developing a new release test, this "
"will most likely be your GitHub fork."),
"default": RAY_TEST_REPO,
"key": "ray_test_repo"
},
{
"text": ("RAY_TEST_BRANCH: Please specify the Ray branch used "
"to find the tests you would like to run."),
"hint": ("If you're developing a new release test, this "
"will most likely be a branch living on your "
"GitHub fork."),
"default": RAY_TEST_BRANCH,
"key": "ray_test_branch"
},
{
"select": ("RELEASE_TEST_SUITE: Please specify the release "
"test suite containing the tests you would like "
"to run."),
"hint": ("Check in the `build_pipeline.py` if you're "
"unsure which suite contains your tests."),
"required": True,
"options": sorted(SUITES.keys()),
"default": RELEASE_TEST_SUITE,
"key": "release_test_suite"
},
{
"text": ("FILTER_FILE: Please specify a filter for the "
"test files that should be included in this build."),
"hint": ("Only test files (e.g. xgboost_tests.yml) that "
"match this string will be included in the test"),
"default": FILTER_FILE,
"required": False,
"key": "filter_file"
},
{
"text": ("FILTER_TEST: Please specify a filter for the "
"test names that should be included in this build."),
"hint": ("Only test names (e.g. tune_4x32) that match "
"this string will be included in the test"),
"default": FILTER_TEST,
"required": False,
"key": "filter_test"
},
],
"key": "input_ask_step",
}
run_again_step = {
"commands": [
f"export {v}=$(buildkite-agent meta-data get \"{k}\")"
for k, v in {
"ray_branch": "RAY_BRANCH",
"ray_repo": "RAY_REPO",
"ray_version": "RAY_VERSION",
"ray_wheels": "RAY_WHEELS",
"ray_test_branch": "RAY_TEST_BRANCH",
"ray_test_repo": "RAY_TEST_REPO",
"release_test_suite": "RELEASE_TEST_SUITE",
"filter_file": "FILTER_FILE",
"filter_test": "FILTER_TEST",
}.items()
] + [
"export AUTOMATIC=1",
"python3 -m pip install --user pyyaml",
"rm -rf ~/ray || true",
"git clone -b $${RAY_TEST_BRANCH} $${RAY_TEST_REPO} ~/ray",
("python3 ~/ray/release/.buildkite/build_pipeline.py "
"| buildkite-agent pipeline upload"),
],
"label": ":pipeline: Again",
"agents": {
"queue": "runner_queue_branch"
},
"depends_on": "input_ask_step",
"key": "run_again_step",
}
return [
input_ask_step,
run_again_step,
]
def create_test_step(
ray_repo: str,
ray_branch: str,
ray_version: str,
ray_wheels: str,
ray_test_repo: str,
ray_test_branch: str,
test_file: str,
test_name: ReleaseTest,
):
ray_wheels_str = f" ({ray_wheels}) " if ray_wheels else ""
logging.info(f"Creating step for {test_file}/{test_name}{ray_wheels_str}")
cmd = str(f"RAY_REPO=\"{ray_repo}\" "
f"RAY_BRANCH=\"{ray_branch}\" "
f"RAY_VERSION=\"{ray_version}\" "
f"RAY_WHEELS=\"{ray_wheels}\" "
f"RELEASE_RESULTS_DIR=/tmp/artifacts "
f"python release/e2e.py "
f"--category {ray_branch} "
f"--test-config {test_file} "
f"--test-name {test_name} "
f"--keep-results-dir")
if test_name.smoke_test:
logging.info("This test will run as a smoke test.")
cmd += " --smoke-test"
step_conf = copy.deepcopy(DEFAULT_STEP_TEMPLATE)
if test_name.retry:
logging.info(f"This test will be retried up to "
f"{test_name.retry} times.")
step_conf["retry"] = {
"automatic": [{
"exit_status": "*",
"limit": test_name.retry
}]
}
step_conf["commands"] = [
"pip install -q -r release/requirements.txt",
"pip install -U boto3 botocore",
f"git clone -b {ray_test_branch} {ray_test_repo} ~/ray", cmd,
"sudo cp -rf /tmp/artifacts/* /tmp/ray_release_test_artifacts "
"|| true"
]
step_conf["label"] = f"{ray_wheels_str}{test_name} ({ray_branch}) - " \
f"{ray_test_branch}/{ray_test_repo}"
return step_conf
def build_pipeline(steps):
all_steps = []
RAY_BRANCH = os.environ.get("RAY_BRANCH", "master")
RAY_REPO = os.environ.get("RAY_REPO",
"https://github.com/ray-project/ray.git")
RAY_VERSION = os.environ.get("RAY_VERSION", "")
RAY_WHEELS = os.environ.get("RAY_WHEELS", "")
RAY_TEST_BRANCH = os.environ.get("RAY_TEST_BRANCH", RAY_BRANCH)
RAY_TEST_REPO = os.environ.get("RAY_TEST_REPO", RAY_REPO)
FILTER_FILE = os.environ.get("FILTER_FILE", "")
FILTER_TEST = os.environ.get("FILTER_TEST", "")
ray_wheels_list = [""]
if RAY_WHEELS:
ray_wheels_list = RAY_WHEELS.split("\n")
if len(ray_wheels_list) > 1:
logging.info(f"This will run a bisec on the following URLs/commits: "
f"{ray_wheels_list}")
logging.info(
f"Building pipeline \n"
f"Ray repo/branch to test:\n"
f" RAY_REPO = {RAY_REPO}\n"
f" RAY_BRANCH = {RAY_BRANCH}\n\n"
f" RAY_VERSION = {RAY_VERSION}\n\n"
f" RAY_WHEELS = {RAY_WHEELS}\n\n"
f"Ray repo/branch containing the test configurations and scripts:"
f" RAY_TEST_REPO = {RAY_TEST_REPO}\n"
f" RAY_TEST_BRANCH = {RAY_TEST_BRANCH}\n\n"
f"Filtering for these tests:\n"
f" FILTER_FILE = {FILTER_FILE}\n"
f" FILTER_TEST = {FILTER_TEST}\n\n")
for test_file, test_names in steps.items():
if FILTER_FILE and FILTER_FILE not in test_file:
continue
test_base = os.path.basename(test_file)
for test_name in test_names:
if FILTER_TEST and FILTER_TEST not in test_name:
continue
if not isinstance(test_name, ReleaseTest):
test_name = ReleaseTest(name=test_name)
logging.info(f"Adding test: {test_base}/{test_name}")
for ray_wheels in ray_wheels_list:
step_conf = create_test_step(
ray_repo=RAY_REPO,
ray_branch=RAY_BRANCH,
ray_version=RAY_VERSION,
ray_wheels=ray_wheels,
ray_test_repo=RAY_TEST_REPO,
ray_test_branch=RAY_TEST_BRANCH,
test_file=test_file,
test_name=test_name)
all_steps.append(step_conf)
return all_steps
def alert_pipeline(stats: bool = False):
step_conf = copy.deepcopy(DEFAULT_STEP_TEMPLATE)
cmd = "python release/alert.py"
if stats:
cmd += " --stats"
step_conf["commands"] = [
"pip install -q -r release/requirements.txt",
"pip install -U boto3 botocore",
cmd,
]
step_conf["label"] = f"Send periodic alert (stats_only = {stats})"
return [step_conf]
if __name__ == "__main__":
alert = os.environ.get("RELEASE_ALERT", "0")
ask_for_config = not bool(int(os.environ.get("AUTOMATIC", "0")))
if alert in ["1", "stats"]:
steps = alert_pipeline(alert == "stats")
elif ask_for_config:
steps = ask_configuration()
else:
TEST_SUITE = os.environ.get("RELEASE_TEST_SUITE", "nightly")
PIPELINE_SPEC = SUITES[TEST_SUITE]
steps = build_pipeline(PIPELINE_SPEC)
yaml.dump({"steps": steps}, sys.stdout)
| [] | [] | [
"RAY_WHEELS",
"RAY_REPO",
"FILTER_FILE",
"RAY_BRANCH",
"FILTER_TEST",
"RAY_VERSION",
"RELEASE_TEST_SUITE",
"RAY_TEST_BRANCH",
"RAY_TEST_REPO",
"RELEASE_ALERT",
"AUTOMATIC"
] | [] | ["RAY_WHEELS", "RAY_REPO", "FILTER_FILE", "RAY_BRANCH", "FILTER_TEST", "RAY_VERSION", "RELEASE_TEST_SUITE", "RAY_TEST_BRANCH", "RAY_TEST_REPO", "RELEASE_ALERT", "AUTOMATIC"] | python | 11 | 0 | |
Python/String/Capatilize.py | """
You are asked to ensure that the first and last names of people begin with a capital letter in their passports.
For example, alison heck should be capitalised correctly as Alison Heck.
Given a full name, your task is to capitalize the name appropriately.
Input Format
A single line of input containing the full name, S.
Output Format
Print the capitalized string, S.
Constraints
The string consists of alphanumeric characters and spaces.
Note: in a word only the first character is capitalized. Example 12abc when capitalized remains 12abc.
Sample Input
chris alan
Sample Output
Chris Alan
Sample Input
1 w 2 r 3g
Sample Output
1 W 2 R 3g
"""
1.
def solve(s):
for i in s.split():
s = s.replace(i,i.capitalize())
return s
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w'
s = input()
result = solve(s)
fptr.write(result + '\n')
fptr.close()
2.
!/bin/python3
import math
import os
import random
import re
import sys
# Complete the solve function below.
def solve(s):
return ' '.join([word.capitalize() for word in s.split(' ')])
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
s = input()
result = solve(s)
fptr.write(result + '\n')
fptr.close()
| [] | [] | [
"OUTPUT_PATH"
] | [] | ["OUTPUT_PATH"] | python | 1 | 0 | |
tests/grpc/grpc_test.go | // Copyright 2021 ChainSafe Systems
// SPDX-License-Identifier: MIT
package grpc
import (
"context"
"errors"
"os"
"path/filepath"
"testing"
"time"
"github.com/ChainSafe/chainlink-cosmos/app"
testnet "github.com/ChainSafe/chainlink-cosmos/testutil/network"
"github.com/ChainSafe/chainlink-cosmos/x/chainlink/types"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/config"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
"github.com/cosmos/cosmos-sdk/simapp"
"github.com/cosmos/cosmos-sdk/testutil/testdata"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/tx"
"github.com/cosmos/cosmos-sdk/types/tx/signing"
signing2 "github.com/cosmos/cosmos-sdk/x/auth/signing"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
rpcclient "github.com/tendermint/tendermint/rpc/client"
"google.golang.org/grpc"
)
type testAccount struct {
Name string
Priv cryptotypes.PrivKey
Pub cryptotypes.PubKey
Addr sdk.AccAddress
Cosmos string
}
var (
//alice = generateKeyPair("alice")
//bob = generateKeyPair("bob")
//cerlo = generateKeyPair("cerlo")
alice *testAccount
bob *testAccount
cerlo *testAccount
)
//func generateKeyPair(name string) *testAccount {
// priv, pub, addr := testdata.KeyTestPubAddr()
// cosmosPubKey, err := sdk.Bech32ifyPubKey(sdk.Bech32PubKeyTypeAccPub, pub)
// if err != nil {
// panic(err)
// }
// return &testAccount{name, priv, priv.PubKey(), addr, cosmosPubKey}
//}
//func formatKeyPair(info keyring.Info) *testAccount {
// cosmosPubKey, err := sdk.Bech32ifyPubKey(sdk.Bech32PubKeyTypeAccPub, info.GetPubKey())
// if err != nil {
// panic(err)
// }
// return &testAccount{
// Name: info.GetName(),
// Pub: info.GetPubKey(),
// Addr: info.GetAddress(),
// Cosmos: cosmosPubKey,
// }
//}
func importKeyPair(t testing.TB, clientCtx client.Context, name string) *testAccount {
info, err := clientCtx.Keyring.Key(name)
require.NoError(t, err)
cosmosPubKey, err := sdk.Bech32ifyPubKey(sdk.Bech32PubKeyTypeAccPub, info.GetPubKey())
require.NoError(t, err)
return &testAccount{
Name: info.GetName(),
Pub: info.GetPubKey(),
Addr: info.GetAddress(),
Cosmos: cosmosPubKey,
}
}
func TestGRPCTestSuite(t *testing.T) {
running := os.Getenv("GRPC_INTEGRATION_TEST")
if running != "true" {
t.SkipNow()
}
suite.Run(t, new(GRPCTestSuite))
}
type GRPCTestSuite struct {
suite.Suite
clientCtx client.Context
rpcClient rpcclient.Client
config testnet.Config
network *testnet.Network
grpcConn *grpc.ClientConn
}
// SetupTest directly connected to daemon on port 9090
// fresh `scripts/start.sh` need to be run before each execution
func (s *GRPCTestSuite) SetupTest() {
s.T().Log("setup test suite")
userHomeDir, err := os.UserHomeDir()
require.NoError(s.T(), err)
home := filepath.Join(userHomeDir, ".chainlinkd")
encodingConfig := app.MakeEncodingConfig()
clientCtx := client.Context{}.
WithHomeDir(home).
WithViper("").
WithAccountRetriever(authtypes.AccountRetriever{}).
WithInterfaceRegistry(encodingConfig.InterfaceRegistry)
clientCtx, err = config.ReadFromClientConfig(clientCtx)
require.NoError(s.T(), err)
backendKeyring, err := client.NewKeyringFromBackend(clientCtx, "test")
require.NoError(s.T(), err)
clientCtx = clientCtx.WithKeyring(backendKeyring)
alice = importKeyPair(s.T(), clientCtx, "alice")
bob = importKeyPair(s.T(), clientCtx, "bob")
cerlo = importKeyPair(s.T(), clientCtx, "cerlo")
s.clientCtx = clientCtx
s.rpcClient, err = client.NewClientFromNode("tcp://127.0.0.1:26657")
require.NoError(s.T(), err)
s.grpcConn, err = grpc.Dial(
"127.0.0.1:9090",
grpc.WithInsecure(),
)
require.NoError(s.T(), err)
}
// SetupTest using testnet package
// TODO find a way to have the auth and bank genesis state not overwritten by testnet
// generateKeyPair and formatKeyPair can be used to generate or format existing key
func (s *GRPCTestSuite) SetupTestTMP() {
s.T().Log("setup test suite")
s.config = testnet.DefaultConfig()
s.config.NumValidators = 1
//configure genesis data for auth module
var authGenState authtypes.GenesisState
s.config.Codec.MustUnmarshalJSON(s.config.GenesisState[authtypes.ModuleName], &authGenState)
genAccounts, err := authtypes.UnpackAccounts(authGenState.Accounts)
s.Require().NoError(err)
genAccounts = append(genAccounts, &authtypes.BaseAccount{
Address: alice.Addr.String(),
AccountNumber: 1,
Sequence: 0,
})
genAccounts = append(genAccounts, &authtypes.BaseAccount{
Address: bob.Addr.String(),
AccountNumber: 2,
Sequence: 0,
})
genAccounts = append(genAccounts, &authtypes.BaseAccount{
Address: cerlo.Addr.String(),
AccountNumber: 3,
Sequence: 0,
})
accounts, err := authtypes.PackAccounts(genAccounts)
s.Require().NoError(err)
authGenState.Accounts = accounts
s.config.GenesisState[authtypes.ModuleName] = s.config.Codec.MustMarshalJSON(&authGenState)
// configure genesis data for bank module
balances := sdk.NewCoins(
sdk.NewCoin("link", s.config.AccountTokens),
sdk.NewCoin(s.config.BondDenom, s.config.StakingTokens),
)
var bankGenState banktypes.GenesisState
s.config.Codec.MustUnmarshalJSON(s.config.GenesisState[banktypes.ModuleName], &bankGenState)
bankGenState.Balances = append(bankGenState.Balances, banktypes.Balance{
Address: alice.Addr.String(),
Coins: balances.Sort(),
})
bankGenState.Balances = append(bankGenState.Balances, banktypes.Balance{
Address: bob.Addr.String(),
Coins: balances.Sort(),
})
bankGenState.Balances = append(bankGenState.Balances, banktypes.Balance{
Address: cerlo.Addr.String(),
Coins: balances.Sort(),
})
s.config.GenesisState[banktypes.ModuleName] = s.config.Codec.MustMarshalJSON(&bankGenState)
// configure genesis data for chainlink module
var chainlinkGenState types.GenesisState
chainlinkGenState.ModuleOwners = []*types.MsgModuleOwner{{Address: alice.Addr, PubKey: []byte(alice.Cosmos), AssignerAddress: nil}}
s.config.GenesisState[types.ModuleName] = s.config.Codec.MustMarshalJSON(&chainlinkGenState)
s.network = testnet.New(s.T(), s.config)
_, err = s.network.WaitForHeight(1)
s.Require().NoError(err)
s.grpcConn, err = grpc.Dial(
s.network.Validators[0].AppConfig.GRPC.Address,
grpc.WithInsecure(),
)
require.NoError(s.T(), err)
}
// TODO can use BuildTX from TxFactory
func (s *GRPCTestSuite) BroadcastTx(ctx context.Context, submitter *testAccount, msgs ...sdk.Msg) *tx.BroadcastTxResponse {
txClient := tx.NewServiceClient(s.grpcConn)
encCfg := simapp.MakeTestEncodingConfig()
txBuilder := encCfg.TxConfig.NewTxBuilder()
err := txBuilder.SetMsgs(msgs...)
s.Require().NoError(err)
txBuilder.SetGasLimit(testdata.NewTestGasLimit())
txBuilder.SetFeeAmount(sdk.NewCoins(sdk.NewInt64Coin("link", 3)))
//txBuilder.SetMemo(...)
//txBuilder.SetTimeoutHeight(...)
s.Require().NoError(s.Sign(submitter, txBuilder))
txBytes, err := encCfg.TxConfig.TxEncoder()(txBuilder.GetTx())
s.Require().NoError(err)
res, err := txClient.BroadcastTx(ctx, &tx.BroadcastTxRequest{
Mode: tx.BroadcastMode_BROADCAST_MODE_BLOCK,
TxBytes: txBytes,
})
s.Require().NoError(err)
return res
}
// TODO can use BuildTX from TxFactory
func (s *GRPCTestSuite) Sign(signer *testAccount, txBuilder client.TxBuilder) error {
accNum, accSeq, err := s.clientCtx.AccountRetriever.GetAccountNumberSequence(s.clientCtx, signer.Addr)
s.Require().NoError(err)
//_, accSeq := uint64(1), uint64(0)
encCfg := simapp.MakeTestEncodingConfig()
signerData := signing2.SignerData{
ChainID: "testchain",
AccountNumber: accNum,
Sequence: accSeq,
}
signMode := encCfg.TxConfig.SignModeHandler().DefaultMode()
sigData := signing.SingleSignatureData{
SignMode: signMode,
Signature: nil,
}
sig := signing.SignatureV2{
PubKey: signer.Pub,
Data: &sigData,
Sequence: accSeq,
}
err = txBuilder.SetSignatures(sig)
s.Require().NoError(err)
bytesToSign, err := encCfg.TxConfig.SignModeHandler().GetSignBytes(signMode, signerData, txBuilder.GetTx())
s.Require().NoError(err)
sigBytes, _, err := s.clientCtx.Keyring.Sign(signer.Name, bytesToSign) // FIXME
s.Require().NoError(err)
sigData = signing.SingleSignatureData{
SignMode: signMode,
Signature: sigBytes,
//Signature: nil,
}
sig = signing.SignatureV2{
PubKey: signer.Pub,
Data: &sigData,
Sequence: accSeq,
}
return txBuilder.SetSignatures(sig)
}
func (s *GRPCTestSuite) TestIntegration() {
ctx := context.Background()
queryClient := types.NewQueryClient(s.grpcConn)
_, _ = s.waitForBlock(1)
s.T().Log("1 - Check initial module owner")
getModuleOwnerResponse, err := queryClient.GetAllModuleOwner(ctx, &types.GetModuleOwnerRequest{})
s.Require().NoError(err)
moduleOwner := getModuleOwnerResponse.GetModuleOwner()
s.Require().Equal(1, len(moduleOwner))
s.Require().Equal(alice.Addr, moduleOwner[0].GetAddress())
s.Require().Equal(alice.Cosmos, string(moduleOwner[0].GetPubKey()))
s.T().Log("2 - Add new module owner by alice")
addModuleOwnerTx := &types.MsgModuleOwner{
Address: bob.Addr,
PubKey: []byte(bob.Cosmos),
AssignerAddress: alice.Addr,
}
s.Require().NoError(addModuleOwnerTx.ValidateBasic())
addModuleOwnerResponse := s.BroadcastTx(ctx, alice, addModuleOwnerTx)
s.Require().EqualValues(0, addModuleOwnerResponse.TxResponse.Code)
getModuleOwnerResponse, err = queryClient.GetAllModuleOwner(ctx, &types.GetModuleOwnerRequest{})
s.Require().NoError(err)
moduleOwner = getModuleOwnerResponse.GetModuleOwner()
s.Require().Equal(2, len(moduleOwner))
s.T().Log("3 - Module ownership transfer by bob to alice")
moduleOwnershipTransferTx := &types.MsgModuleOwnershipTransfer{
NewModuleOwnerAddress: alice.Addr,
NewModuleOwnerPubKey: []byte(alice.Cosmos),
AssignerAddress: bob.Addr,
}
s.Require().NoError(addModuleOwnerTx.ValidateBasic())
moduleOwnershipTransferResponse := s.BroadcastTx(ctx, bob, moduleOwnershipTransferTx)
s.Require().EqualValues(0, moduleOwnershipTransferResponse.TxResponse.Code)
s.T().Log("4 - Add new feed by alice")
feedId := "testfeed1"
addFeedTx := &types.MsgFeed{
FeedId: feedId,
FeedOwner: cerlo.Addr,
DataProviders: []*types.DataProvider{
{
Address: cerlo.Addr,
PubKey: []byte(cerlo.Cosmos),
},
},
SubmissionCount: 10,
HeartbeatTrigger: 2,
DeviationThresholdTrigger: 3,
FeedReward: &types.FeedRewardSchema{
Amount: 100,
Strategy: "",
},
ModuleOwnerAddress: alice.Addr,
}
s.Require().NoError(addFeedTx.ValidateBasic())
addFeedResponse := s.BroadcastTx(ctx, alice, addFeedTx)
s.Require().EqualValues(0, addFeedResponse.TxResponse.Code)
getFeedByFeedIdResponse, err := queryClient.GetFeedByFeedId(ctx, &types.GetFeedByIdRequest{FeedId: feedId})
s.Require().NoError(err)
feed := getFeedByFeedIdResponse.GetFeed()
s.Require().Equal(feedId, feed.GetFeedId())
s.Require().EqualValues(cerlo.Addr, feed.GetFeedOwner())
s.Require().EqualValues(1, len(feed.GetDataProviders()))
s.Require().Contains(feed.GetDataProviders(), &types.DataProvider{Address: cerlo.Addr, PubKey: []byte(cerlo.Cosmos)})
s.Require().EqualValues(10, feed.GetSubmissionCount())
s.Require().EqualValues(2, feed.GetHeartbeatTrigger())
s.Require().EqualValues(3, feed.GetDeviationThresholdTrigger())
s.Require().EqualValues(uint32(0x64), feed.GetFeedReward().GetAmount())
s.Require().EqualValues("", feed.GetFeedReward().GetStrategy())
s.T().Log("5 - Add data provider by cerlo")
addDataProviderTx := &types.MsgAddDataProvider{
FeedId: feedId,
DataProvider: &types.DataProvider{
Address: bob.Addr,
PubKey: []byte(bob.Cosmos),
},
Signer: cerlo.Addr,
}
s.Require().NoError(addDataProviderTx.ValidateBasic())
addDataProviderResponse := s.BroadcastTx(ctx, cerlo, addDataProviderTx)
s.Require().EqualValues(0, addDataProviderResponse.TxResponse.Code)
getFeedByFeedIdResponse, err = queryClient.GetFeedByFeedId(ctx, &types.GetFeedByIdRequest{FeedId: feedId})
s.Require().NoError(err)
feed = getFeedByFeedIdResponse.GetFeed()
s.Require().EqualValues(2, len(feed.GetDataProviders()))
s.Require().Contains(feed.GetDataProviders(), &types.DataProvider{Address: cerlo.Addr, PubKey: []byte(cerlo.Cosmos)})
s.Require().Contains(feed.GetDataProviders(), &types.DataProvider{Address: bob.Addr, PubKey: []byte(bob.Cosmos)})
s.T().Log("6 - Remove data provider by cerlo")
removeDataProviderTx := &types.MsgRemoveDataProvider{
FeedId: feedId,
Address: cerlo.Addr,
Signer: cerlo.Addr,
}
s.Require().NoError(removeDataProviderTx.ValidateBasic())
removeDataProviderResponse := s.BroadcastTx(ctx, cerlo, removeDataProviderTx)
s.Require().EqualValues(0, removeDataProviderResponse.TxResponse.Code)
getFeedByFeedIdResponse, err = queryClient.GetFeedByFeedId(ctx, &types.GetFeedByIdRequest{FeedId: feedId})
s.Require().NoError(err)
feed = getFeedByFeedIdResponse.GetFeed()
s.Require().EqualValues(1, len(feed.GetDataProviders()))
s.Require().Contains(feed.GetDataProviders(), &types.DataProvider{Address: bob.Addr, PubKey: []byte(bob.Cosmos)})
s.T().Log("7 - Feed ownership transfer to bob by cerlo")
feedOwnershipTransferTx := &types.MsgFeedOwnershipTransfer{
FeedId: feedId,
NewFeedOwnerAddress: bob.Addr,
Signer: cerlo.Addr,
}
s.Require().NoError(feedOwnershipTransferTx.ValidateBasic())
feedOwnershipTransferResponse := s.BroadcastTx(ctx, cerlo, feedOwnershipTransferTx)
s.Require().EqualValues(0, feedOwnershipTransferResponse.TxResponse.Code)
getFeedByFeedIdResponse, err = queryClient.GetFeedByFeedId(ctx, &types.GetFeedByIdRequest{FeedId: feedId})
s.Require().NoError(err)
feed = getFeedByFeedIdResponse.GetFeed()
s.Require().EqualValues(bob.Addr, feed.GetFeedOwner())
s.T().Log("8 - Update submission count parameter")
setSubmissionCountTx := &types.MsgSetSubmissionCount{
FeedId: feedId,
SubmissionCount: 1,
Signer: bob.Addr,
}
setHeartbeatTriggerTx := &types.MsgSetHeartbeatTrigger{
FeedId: feedId,
HeartbeatTrigger: 200,
Signer: bob.Addr,
}
setDeviationThresholdTriggerTx := &types.MsgSetDeviationThresholdTrigger{
FeedId: feedId,
DeviationThresholdTrigger: 300,
Signer: bob.Addr,
}
setFeedRewardTx := &types.MsgSetFeedReward{
FeedId: feedId,
FeedReward: &types.FeedRewardSchema{
Amount: 400,
Strategy: "",
},
Signer: bob.Addr,
}
s.Require().NoError(setSubmissionCountTx.ValidateBasic())
s.Require().NoError(setHeartbeatTriggerTx.ValidateBasic())
s.Require().NoError(setDeviationThresholdTriggerTx.ValidateBasic())
s.Require().NoError(setFeedRewardTx.ValidateBasic())
setFeedParamsResponse := s.BroadcastTx(ctx, bob, setSubmissionCountTx, setHeartbeatTriggerTx, setDeviationThresholdTriggerTx, setFeedRewardTx)
s.Require().EqualValues(0, setFeedParamsResponse.TxResponse.Code)
getFeedByFeedIdResponse, err = queryClient.GetFeedByFeedId(ctx, &types.GetFeedByIdRequest{FeedId: feedId})
s.Require().NoError(err)
feed = getFeedByFeedIdResponse.GetFeed()
s.Require().EqualValues(1, feed.GetSubmissionCount())
s.Require().EqualValues(200, feed.GetHeartbeatTrigger())
s.Require().EqualValues(300, feed.GetDeviationThresholdTrigger())
s.Require().EqualValues(400, feed.GetFeedReward().GetAmount())
s.Require().EqualValues("", feed.GetFeedReward().GetStrategy())
s.T().Log("9 - Submit feed data by bob")
// add bob in account store first before submitting feed data
addBobInAccountStoreTx := &types.MsgAccount{
Submitter: bob.Addr,
ChainlinkPublicKey: []byte("bobChainlinkPublicKey"),
ChainlinkSigningKey: []byte("ChainlinkSigningKey"),
PiggyAddress: bob.Addr,
}
s.Require().NoError(addBobInAccountStoreTx.ValidateBasic())
addBobInAccountStoreTxResponse := s.BroadcastTx(ctx, bob, addBobInAccountStoreTx)
s.Require().EqualValues(0, addBobInAccountStoreTxResponse.TxResponse.Code)
submitFeedDataTx := &types.MsgFeedData{
FeedId: feedId,
ObservationFeedData: [][]byte{[]byte("data")},
ObservationFeedDataSignatures: [][]byte{[]byte("signature_bob")},
Submitter: bob.Addr,
CosmosPubKeys: [][]byte{[]byte(bob.Cosmos)},
}
s.Require().NoError(submitFeedDataTx.ValidateBasic())
submitFeedDataResponse := s.BroadcastTx(ctx, bob, submitFeedDataTx)
s.Require().EqualValues(0, submitFeedDataResponse.TxResponse.Code)
getRoundDataResponse, err := queryClient.GetRoundData(ctx, &types.GetRoundDataRequest{FeedId: feedId, RoundId: 1})
s.Require().NoError(err)
roundData := getRoundDataResponse.GetRoundData()
s.Require().EqualValues(1, len(roundData))
// TODO check round data when OCR ready
}
func (s *GRPCTestSuite) waitForBlock(h int64) (int64, error) {
ticker := time.NewTicker(time.Second)
timeout := time.After(10 * time.Second)
var latestHeight int64
for {
select {
case <-timeout:
ticker.Stop()
return latestHeight, errors.New("timeout exceeded waiting for block")
case <-ticker.C:
status, err := s.rpcClient.Status(context.Background())
if err == nil && status != nil {
latestHeight = status.SyncInfo.LatestBlockHeight
if latestHeight >= h {
return latestHeight, nil
}
}
}
}
}
| [
"\"GRPC_INTEGRATION_TEST\""
] | [] | [
"GRPC_INTEGRATION_TEST"
] | [] | ["GRPC_INTEGRATION_TEST"] | go | 1 | 0 | |
feathr_project/feathr/client.py | import base64
import logging
import os
import tempfile
from datetime import datetime, timedelta
from pathlib import Path
from typing import Dict, List, Optional, Union
import redis
from azure.identity import DefaultAzureCredential
from jinja2 import Template
from pyhocon import ConfigFactory
from feathr._databricks_submission import _FeathrDatabricksJobLauncher
from feathr._envvariableutil import _EnvVaraibleUtil
from feathr._feature_registry import _FeatureRegistry
from feathr._file_utils import write_to_file
from feathr._materialization_utils import _to_materialization_config
from feathr._preprocessing_pyudf_manager import _PreprocessingPyudfManager
from feathr._synapse_submission import _FeathrSynapseJobLauncher
from feathr.constants import *
from feathr.feathr_configurations import SparkExecutionConfiguration
from feathr.feature_derivations import DerivedFeature
from feathr.materialization_settings import MaterializationSettings
from feathr.protobuf.featureValue_pb2 import FeatureValue
from feathr.query_feature_list import FeatureQuery
from feathr.settings import ObservationSettings
from feathr.feature_derivations import DerivedFeature
from feathr.anchor import FeatureAnchor
from feathr.feathr_configurations import SparkExecutionConfiguration
class FeatureJoinJobParams:
"""Parameters related to feature join job.
Attributes:
join_config_path: Path to the join config.
observation_path: Absolute path in Cloud to the observation data path.
feature_config: Path to the features config.
job_output_path: Absolute path in Cloud that you want your output data to be in.
"""
def __init__(self, join_config_path, observation_path, feature_config, job_output_path):
self.join_config_path = join_config_path
self.observation_path = observation_path
self.feature_config = feature_config
self.job_output_path = job_output_path
class FeatureGenerationJobParams:
"""Parameters related to feature generation job.
Attributes:
generation_config_path: Path to the feature generation config.
feature_config: Path to the features config.
"""
def __init__(self, generation_config_path, feature_config):
self.generation_config_path = generation_config_path
self.feature_config = feature_config
class FeathrClient(object):
"""Feathr client.
The client is used to create training dataset, materialize features, register features, and fetch features from
the online storage.
For offline storage and compute engine, Azure ADLS, AWS S3 and Azure Synapse are supported.
For online storage, currently only Redis is supported.
The users of this client is responsible for set up all the necessary information needed to start a Redis client via
environment variable or a Spark cluster. Host address, port and password are needed to start the Redis client.
Args:
config_path (str, optional): config path. See [Feathr Config Template](https://github.com/linkedin/feathr/blob/main/feathr_project/feathrcli/data/feathr_user_workspace/feathr_config.yaml) for more details. Defaults to "./feathr_config.yaml".
local_workspace_dir (str, optional): set where is the local work space dir. If not set, Feathr will create a temporary folder to store local workspace related files.
credential (optional): credential to access cloud resources, most likely to be the returned result of DefaultAzureCredential(). If not set, Feathr will initialize DefaultAzureCredential() inside the __init__ function to get credentials.
project_registry_tag (Dict[str, str]): adding tags for project in Feathr registry. This might be useful if you want to tag your project as deprecated, or allow certain customizations on project leve. Default is empty
Raises:
RuntimeError: Fail to create the client since necessary environment variables are not set for Redis
client creation.
"""
def __init__(self, config_path:str = "./feathr_config.yaml", local_workspace_dir: str = None, credential=None, project_registry_tag: Dict[str, str]=None):
self.logger = logging.getLogger(__name__)
# Redis key separator
self._KEY_SEPARATOR = ':'
envutils = _EnvVaraibleUtil(config_path)
if local_workspace_dir:
self.local_workspace_dir = local_workspace_dir
else:
# this is required for Windows
tem_dir_obj = tempfile.TemporaryDirectory()
self.local_workspace_dir = tem_dir_obj.name
self.envutils = envutils
if not os.path.exists(config_path):
self.logger.warning('Configuration path does not exist, you need to set the environment variables explicitly. For all the environment variables, please refer to https://github.com/linkedin/feathr/blob/main/feathr_project/feathrcli/data/feathr_user_workspace/feathr_config.yaml')
# Load all configs from yaml at initialization
# DO NOT load any configs from yaml during runtime.
self.project_name = envutils.get_environment_variable_with_default(
'project_config', 'project_name')
# Redis configs
self.redis_host = envutils.get_environment_variable_with_default(
'online_store', 'redis', 'host')
self.redis_port = envutils.get_environment_variable_with_default(
'online_store', 'redis', 'port')
self.redis_ssl_enabled = envutils.get_environment_variable_with_default(
'online_store', 'redis', 'ssl_enabled')
# S3 configs
self.s3_endpoint = envutils.get_environment_variable_with_default(
'offline_store', 's3', 's3_endpoint')
# spark configs
self.output_num_parts = envutils.get_environment_variable_with_default(
'spark_config', 'spark_result_output_parts')
self.spark_runtime = envutils.get_environment_variable_with_default(
'spark_config', 'spark_cluster')
self.credential = credential
if self.spark_runtime not in {'azure_synapse', 'databricks'}:
raise RuntimeError(
'Only \'azure_synapse\' and \'databricks\' are currently supported.')
elif self.spark_runtime == 'azure_synapse':
# Feathr is a spark-based application so the feathr jar compiled from source code will be used in the
# Spark job submission. The feathr jar hosted in cloud saves the time users needed to upload the jar from
# their local env.
self._FEATHR_JOB_JAR_PATH = \
envutils.get_environment_variable_with_default(
'spark_config', 'azure_synapse', 'feathr_runtime_location')
if self.credential is None:
self.credential = DefaultAzureCredential(exclude_interactive_browser_credential=False)
self.feathr_spark_laucher = _FeathrSynapseJobLauncher(
synapse_dev_url=envutils.get_environment_variable_with_default(
'spark_config', 'azure_synapse', 'dev_url'),
pool_name=envutils.get_environment_variable_with_default(
'spark_config', 'azure_synapse', 'pool_name'),
datalake_dir=envutils.get_environment_variable_with_default(
'spark_config', 'azure_synapse', 'workspace_dir'),
executor_size=envutils.get_environment_variable_with_default(
'spark_config', 'azure_synapse', 'executor_size'),
executors=envutils.get_environment_variable_with_default(
'spark_config', 'azure_synapse', 'executor_num'),
credential=self.credential
)
elif self.spark_runtime == 'databricks':
# Feathr is a spark-based application so the feathr jar compiled from source code will be used in the
# Spark job submission. The feathr jar hosted in cloud saves the time users needed to upload the jar from
# their local env.
self._FEATHR_JOB_JAR_PATH = \
envutils.get_environment_variable_with_default(
'spark_config', 'databricks', 'feathr_runtime_location')
self.feathr_spark_laucher = _FeathrDatabricksJobLauncher(
workspace_instance_url=envutils.get_environment_variable_with_default(
'spark_config', 'databricks', 'workspace_instance_url'),
token_value=_EnvVaraibleUtil.get_environment_variable(
'DATABRICKS_WORKSPACE_TOKEN_VALUE'),
config_template=envutils.get_environment_variable_with_default(
'spark_config', 'databricks', 'config_template'),
databricks_work_dir=envutils.get_environment_variable_with_default(
'spark_config', 'databricks', 'work_dir')
)
self._construct_redis_client()
# initialize registry
self.registry_delimiter = envutils.get_environment_variable_with_default(
'feature_registry', 'purview', 'delimiter')
self.azure_purview_name = envutils.get_environment_variable_with_default(
'feature_registry', 'purview', 'purview_name')
# initialize the registry no matter whether we set purview name or not, given some of the methods are used there.
self.registry = _FeatureRegistry(self.project_name, self.azure_purview_name, self.registry_delimiter, project_registry_tag, config_path = config_path, credential=self.credential)
def _check_required_environment_variables_exist(self):
"""Checks if the required environment variables(form feathr_config.yaml) is set.
Some required information has to be set via environment variables so the client can work.
"""
for required_field in self.required_fields:
if required_field not in os.environ:
raise RuntimeError(f'{required_field} is not set in environment variable. All required environment '
f'variables are: {self.required_fields}.')
def register_features(self, from_context: bool = True):
"""Registers features based on the current workspace
Args:
from_context: If from_context is True (default), the features will be generated from
the current context, with the previous built features in client.build(). Otherwise, the features will be generated from
configuration files.
"""
if from_context:
# make sure those items are in `self`
if 'anchor_list' in dir(self) and 'derived_feature_list' in dir(self):
_FeatureRegistry.save_to_feature_config_from_context(self.anchor_list, self.derived_feature_list, self.local_workspace_dir)
self.registry.register_features(self.local_workspace_dir, from_context=from_context, anchor_list=self.anchor_list, derived_feature_list=self.derived_feature_list)
else:
raise RuntimeError("Please call FeathrClient.build_features() first in order to register features")
else:
self.registry.register_features(self.local_workspace_dir, from_context=from_context)
def build_features(self, anchor_list: List[FeatureAnchor] = [], derived_feature_list: List[DerivedFeature] = []):
"""Registers features based on the current workspace
"""
# Run necessary validations
# anchor name and source name should be unique
anchor_names = {}
source_names = {}
for anchor in anchor_list:
if anchor.name in anchor_names:
raise RuntimeError(f"Anchor name should be unique but there are duplicate anchor names in your anchor "
f"definitions. Anchor name of {anchor} is already defined in {anchor_names[anchor.name]}")
else:
anchor_names[anchor.name] = anchor
if anchor.source.name in source_names:
raise RuntimeError(f"Source name should be unique but there are duplicate source names in your source "
f"definitions. Source name of {anchor.source} is already defined in {source_names[anchor.source.name]}")
else:
source_names[anchor.source.name] = anchor.source
preprocessingPyudfManager = _PreprocessingPyudfManager()
_PreprocessingPyudfManager.build_anchor_preprocessing_metadata(anchor_list, self.local_workspace_dir)
self.registry.save_to_feature_config_from_context(anchor_list, derived_feature_list, self.local_workspace_dir)
self.anchor_list = anchor_list
self.derived_feature_list = derived_feature_list
def list_registered_features(self, project_name: str = None) -> List[str]:
"""List all the already registered features. If project_name is not provided or is None, it will return all
the registered features; otherwise it will only return features under this project
"""
return self.registry.list_registered_features(project_name)
def _get_registry_client(self):
"""
Returns registry client in case users want to perform more advanced operations
"""
return self.registry._get_registry_client()
def get_online_features(self, feature_table, key, feature_names):
"""Fetches feature value for a certain key from a online feature table.
Args:
feature_table: the name of the feature table.
key: the key of the entity
feature_names: list of feature names to fetch
Return:
A list of feature values for this entity. It's ordered by the requested feature names.
For example, feature_names = ['f_is_medium_trip_distance', 'f_day_of_week', 'f_day_of_month', 'f_hour_of_day']
then, the returned feature values is: [b'true', b'4.0', b'31.0', b'23.0'].
If the feature_table or key doesn't exist, then a list of Nones are returned. For example,
[None, None, None, None].
If a feature doesn't exist, then a None is returned for that feature. For example:
[None, b'4.0', b'31.0', b'23.0'].
"""
redis_key = self._construct_redis_key(feature_table, key)
res = self.redis_clint.hmget(redis_key, *feature_names)
return self._decode_proto(res)
def multi_get_online_features(self, feature_table, keys, feature_names):
"""Fetches feature value for a list of keys from a online feature table. This is the batch version of the get API.
Args:
feature_table: the name of the feature table.
keys: list of keys for the entities
feature_names: list of feature names to fetch
Return:
A list of feature values for the requested entities. It's ordered by the requested feature names. For
example, keys = [12, 24], feature_names = ['f_is_medium_trip_distance', 'f_day_of_week', 'f_day_of_month',
'f_hour_of_day'] then, the returned feature values is: {'12': [b'false', b'5.0', b'1.0', b'0.0'],
'24': [b'true', b'4.0', b'31.0', b'23.0']}. If the feature_table or key doesn't exist, then a list of Nones
are returned. For example, {'12': [None, None, None, None], '24': [None, None, None, None]} If a feature
doesn't exist, then a None is returned for that feature. For example: {'12': [None, b'4.0', b'31.0',
b'23.0'], '24': [b'true', b'4.0', b'31.0', b'23.0']}.
"""
with self.redis_clint.pipeline() as redis_pipeline:
for key in keys:
redis_key = self._construct_redis_key(feature_table, key)
redis_pipeline.hmget(redis_key, *feature_names)
pipeline_result = redis_pipeline.execute()
decoded_pipeline_result = []
for feature_list in pipeline_result:
decoded_pipeline_result.append(self._decode_proto(feature_list))
return dict(zip(keys, decoded_pipeline_result))
def _decode_proto(self, feature_list):
"""Decode the bytes(in string form) via base64 decoder. For dense array, it will be returned as Python List.
For sparse array, it will be returned as tuple of index array and value array. The order of elements in the
arrays won't be changed.
"""
typed_result = []
for raw_feature in feature_list:
if raw_feature:
feature_value = FeatureValue()
decoded = base64.b64decode(raw_feature)
feature_value.ParseFromString(decoded)
if feature_value.WhichOneof('FeatureValueOneOf') == 'boolean_value':
typed_result.append(feature_value.boolean_value)
elif feature_value.WhichOneof('FeatureValueOneOf') == 'string_value':
typed_result.append(feature_value.string_value)
elif feature_value.WhichOneof('FeatureValueOneOf') == 'float_value':
typed_result.append(feature_value.float_value)
elif feature_value.WhichOneof('FeatureValueOneOf') == 'double_value':
typed_result.append(feature_value.double_value)
elif feature_value.WhichOneof('FeatureValueOneOf') == 'int_value':
typed_result.append(feature_value.int_value)
elif feature_value.WhichOneof('FeatureValueOneOf') == 'long_value':
typed_result.append(feature_value.long_value)
elif feature_value.WhichOneof('FeatureValueOneOf') == 'int_array':
typed_result.append(feature_value.int_array.integers)
elif feature_value.WhichOneof('FeatureValueOneOf') == 'string_array':
typed_result.append(feature_value.string_array.strings)
elif feature_value.WhichOneof('FeatureValueOneOf') == 'float_array':
typed_result.append(feature_value.float_array.floats)
elif feature_value.WhichOneof('FeatureValueOneOf') == 'double_array':
typed_result.append(feature_value.double_array.doubles)
elif feature_value.WhichOneof('FeatureValueOneOf') == 'boolean_array':
typed_result.append(feature_value.boolean_array.booleans)
elif feature_value.WhichOneof('FeatureValueOneOf') == 'sparse_string_array':
typed_result.append((feature_value.sparse_string_array.index_integers, feature_value.sparse_string_array.value_strings))
elif feature_value.WhichOneof('FeatureValueOneOf') == 'sparse_bool_array':
typed_result.append((feature_value.sparse_bool_array.index_integers, feature_value.sparse_bool_array.value_booleans))
elif feature_value.WhichOneof('FeatureValueOneOf') == 'sparse_float_array':
typed_result.append((feature_value.sparse_float_array.index_integers, feature_value.sparse_float_array.value_floats))
elif feature_value.WhichOneof('FeatureValueOneOf') == 'sparse_double_array':
typed_result.append((feature_value.sparse_double_array.index_integers, feature_value.sparse_double_array.value_doubles))
elif feature_value.WhichOneof('FeatureValueOneOf') == 'sparse_long_array':
typed_result.append((feature_value.sparse_long_array.index_integers, feature_value.sparse_long_array.value_longs))
else:
self.logger.debug("Fail to load the feature type. Maybe a new type that is not supported by this "
"client version")
self.logger.debug(f"The raw feature is {raw_feature}.")
self.logger.debug(f"The loaded feature is {feature_value}")
typed_result.append(None)
else:
typed_result.append(raw_feature)
return typed_result
def _clean_test_data(self, feature_table):
"""
WARNING: THIS IS ONLY USED FOR TESTING
Clears a namespace in redis cache.
This may be very time consuming.
Args:
feature_table: str, feature_table i.e your prefix before the separator in the Redis database.
"""
cursor = '0'
ns_keys = feature_table + '*'
while cursor != 0:
# 5000 count at a scan seems reasonable faster for our testing data
cursor, keys = self.redis_clint.scan(
cursor=cursor, match=ns_keys, count=5000)
if keys:
self.redis_clint.delete(*keys)
def _construct_redis_key(self, feature_table, key):
return feature_table + self._KEY_SEPARATOR + key
def _construct_redis_client(self):
"""Constructs the Redis client. The host, port, credential and other parameters can be set via environment
parameters.
"""
password = _EnvVaraibleUtil.get_environment_variable(REDIS_PASSWORD)
host = self.redis_host
port = self.redis_port
ssl_enabled = self.redis_ssl_enabled
redis_clint = redis.Redis(
host=host,
port=port,
password=password,
ssl=ssl_enabled)
self.logger.info('Redis connection is successful and completed.')
self.redis_clint = redis_clint
def get_offline_features(self,
observation_settings: ObservationSettings,
feature_query: Union[FeatureQuery, List[FeatureQuery]],
output_path: str,
execution_configuratons: Union[SparkExecutionConfiguration ,Dict[str,str]] = None,
udf_files = None,
):
"""
Get offline features for the observation dataset
Args:
observation_settings: settings of the observation data, e.g. timestamp columns, input path, etc.
feature_query: features that are requested to add onto the observation data
output_path: output path of job, i.e. the observation data with features attached.
execution_configuratons: a dict that will be passed to spark job when the job starts up, i.e. the "spark configurations". Note that not all of the configuration will be honored since some of the configurations are managed by the Spark platform, such as Databricks or Azure Synapse. Refer to the [spark documentation](https://spark.apache.org/docs/latest/configuration.html) for a complete list of spark configurations.
"""
feature_queries = feature_query if isinstance(feature_query, List) else [feature_query]
feature_names = []
for feature_query in feature_queries:
for feature_name in feature_query.feature_list:
feature_names.append(feature_name)
udf_files = _PreprocessingPyudfManager.prepare_pyspark_udf_files(feature_names, self.local_workspace_dir)
# produce join config
tm = Template("""
{{observation_settings.to_config()}}
featureList: [
{% for list in feature_lists %}
{{list.to_config()}}
{% endfor %}
]
outputPath: "{{output_path}}"
""")
config = tm.render(feature_lists=feature_queries, observation_settings=observation_settings, output_path=output_path)
config_file_name = "feature_join_conf/feature_join.conf"
config_file_path = os.path.join(self.local_workspace_dir, config_file_name)
# make sure `FeathrClient.build_features()` is called before getting offline features/materialize features
# otherwise users will be confused on what are the available features
# in build_features it will assign anchor_list and derived_feature_list variable, hence we are checking if those two variables exist to make sure the above condition is met
if 'anchor_list' in dir(self) and 'derived_feature_list' in dir(self):
_FeatureRegistry.save_to_feature_config_from_context(self.anchor_list, self.derived_feature_list, self.local_workspace_dir)
else:
raise RuntimeError("Please call FeathrClient.build_features() first in order to get offline features")
write_to_file(content=config, full_file_name=config_file_path)
return self._get_offline_features_with_config(config_file_path, execution_configuratons, udf_files=udf_files)
def _get_offline_features_with_config(self, feature_join_conf_path='feature_join_conf/feature_join.conf', execution_configuratons: Dict[str,str] = None, udf_files=[]):
"""Joins the features to your offline observation dataset based on the join config.
Args:
feature_join_conf_path: Relative path to your feature join config file.
"""
cloud_udf_paths = [self.feathr_spark_laucher.upload_or_get_cloud_path(udf_local_path) for udf_local_path in udf_files]
feathr_feature = ConfigFactory.parse_file(feature_join_conf_path)
feature_join_job_params = FeatureJoinJobParams(join_config_path=os.path.abspath(feature_join_conf_path),
observation_path=feathr_feature['observationPath'],
feature_config=os.path.join(self.local_workspace_dir, 'feature_conf/'),
job_output_path=feathr_feature['outputPath'],
)
job_tags = {OUTPUT_PATH_TAG:feature_join_job_params.job_output_path}
# set output format in job tags if it's set by user, so that it can be used to parse the job result in the helper function
if execution_configuratons is not None and OUTPUT_FORMAT in execution_configuratons:
job_tags[OUTPUT_FORMAT]= execution_configuratons[OUTPUT_FORMAT]
'''
- Job tags are for job metadata and it's not passed to the actual spark job (i.e. not visible to spark job), more like a platform related thing that Feathr want to add (currently job tags only have job output URL and job output format, ). They are carried over with the job and is visible to every Feathr client. Think this more like some customized metadata for the job which would be weird to be put in the spark job itself.
- Job arguments (or sometimes called job parameters)are the arguments which are command line arguments passed into the actual spark job. This is usually highly related with the spark job. In Feathr it's like the input to the scala spark CLI. They are usually not spark specific (for example if we want to specify the location of the feature files, or want to
- Job configuration are like "configurations" for the spark job and are usually spark specific. For example, we want to control the no. of write parts for spark
Job configurations and job arguments (or sometimes called job parameters) have quite some overlaps (i.e. you can achieve the same goal by either using the job arguments/parameters vs. job configurations). But the job tags should just be used for metadata purpose.
'''
# submit the jars
return self.feathr_spark_laucher.submit_feathr_job(
job_name=self.project_name + '_feathr_feature_join_job',
main_jar_path=self._FEATHR_JOB_JAR_PATH,
python_files=cloud_udf_paths,
job_tags=job_tags,
main_class_name='com.linkedin.feathr.offline.job.FeatureJoinJob',
arguments=[
'--join-config', self.feathr_spark_laucher.upload_or_get_cloud_path(
feature_join_job_params.join_config_path),
'--input', feature_join_job_params.observation_path,
'--output', feature_join_job_params.job_output_path,
'--feature-config', self.feathr_spark_laucher.upload_or_get_cloud_path(
feature_join_job_params.feature_config),
'--num-parts', self.output_num_parts,
'--s3-config', self._get_s3_config_str(),
'--adls-config', self._get_adls_config_str(),
'--blob-config', self._get_blob_config_str(),
'--sql-config', self._get_sql_config_str(),
'--snowflake-config', self._get_snowflake_config_str()
],
reference_files_path=[],
configuration=execution_configuratons
)
def get_job_result_uri(self, block=True, timeout_sec=300) -> str:
"""Gets the job output URI
"""
if not block:
return self.feathr_spark_laucher.get_job_result_uri()
# Block the API by pooling the job status and wait for complete
if self.feathr_spark_laucher.wait_for_completion(timeout_sec):
return self.feathr_spark_laucher.get_job_result_uri()
else:
raise RuntimeError(
'Spark job failed so output cannot be retrieved.')
def get_job_tags(self) -> Dict[str, str]:
"""Gets the job tags
"""
return self.feathr_spark_laucher.get_job_tags()
def wait_job_to_finish(self, timeout_sec: int = 300):
"""Waits for the job to finish in a blocking way unless it times out
"""
if self.feathr_spark_laucher.wait_for_completion(timeout_sec):
return
else:
raise RuntimeError('Spark job failed.')
def materialize_features(self, settings: MaterializationSettings, execution_configuratons: Union[SparkExecutionConfiguration ,Dict[str,str]] = None):
"""Materialize feature data
Args:
settings: Feature materialization settings
execution_configuratons: a dict that will be passed to spark job when the job starts up, i.e. the "spark configurations". Note that not all of the configuration will be honored since some of the configurations are managed by the Spark platform, such as Databricks or Azure Synapse. Refer to the [spark documentation](https://spark.apache.org/docs/latest/configuration.html) for a complete list of spark configurations.
"""
# produce materialization config
for end in settings.get_backfill_cutoff_time():
settings.backfill_time.end = end
config = _to_materialization_config(settings)
config_file_name = "feature_gen_conf/auto_gen_config_{}.conf".format(end.timestamp())
config_file_path = os.path.join(self.local_workspace_dir, config_file_name)
write_to_file(content=config, full_file_name=config_file_path)
# make sure `FeathrClient.build_features()` is called before getting offline features/materialize features in the python SDK
# otherwise users will be confused on what are the available features
# in build_features it will assign anchor_list and derived_feature_list variable, hence we are checking if those two variables exist to make sure the above condition is met
if 'anchor_list' in dir(self) and 'derived_feature_list' in dir(self):
_FeatureRegistry.save_to_feature_config_from_context(self.anchor_list, self.derived_feature_list, self.local_workspace_dir)
else:
raise RuntimeError("Please call FeathrClient.build_features() first in order to materialize the features")
udf_files = _PreprocessingPyudfManager.prepare_pyspark_udf_files(settings.feature_names, self.local_workspace_dir)
# CLI will directly call this so the experiene won't be broken
self._materialize_features_with_config(config_file_path, execution_configuratons, udf_files)
if os.path.exists(config_file_path):
os.remove(config_file_path)
def _materialize_features_with_config(self, feature_gen_conf_path: str = 'feature_gen_conf/feature_gen.conf',execution_configuratons: Dict[str,str] = None, udf_files=[]):
"""Materializes feature data based on the feature generation config. The feature
data will be materialized to the destination specified in the feature generation config.
Args
feature_gen_conf_path: Relative path to the feature generation config you want to materialize.
"""
cloud_udf_paths = [self.feathr_spark_laucher.upload_or_get_cloud_path(udf_local_path) for udf_local_path in udf_files]
# Read all features conf
generation_config = FeatureGenerationJobParams(
generation_config_path=os.path.abspath(feature_gen_conf_path),
feature_config=os.path.join(self.local_workspace_dir, "feature_conf/"))
'''
- Job tags are for job metadata and it's not passed to the actual spark job (i.e. not visible to spark job), more like a platform related thing that Feathr want to add (currently job tags only have job output URL and job output format, ). They are carried over with the job and is visible to every Feathr client. Think this more like some customized metadata for the job which would be weird to be put in the spark job itself.
- Job arguments (or sometimes called job parameters)are the arguments which are command line arguments passed into the actual spark job. This is usually highly related with the spark job. In Feathr it's like the input to the scala spark CLI. They are usually not spark specific (for example if we want to specify the location of the feature files, or want to
- Job configuration are like "configurations" for the spark job and are usually spark specific. For example, we want to control the no. of write parts for spark
Job configurations and job arguments (or sometimes called job parameters) have quite some overlaps (i.e. you can achieve the same goal by either using the job arguments/parameters vs. job configurations). But the job tags should just be used for metadata purpose.
'''
return self.feathr_spark_laucher.submit_feathr_job(
job_name=self.project_name + '_feathr_feature_materialization_job',
main_jar_path=self._FEATHR_JOB_JAR_PATH,
python_files=cloud_udf_paths,
main_class_name='com.linkedin.feathr.offline.job.FeatureGenJob',
arguments=[
'--generation-config', self.feathr_spark_laucher.upload_or_get_cloud_path(
generation_config.generation_config_path),
# Local Config, comma seperated file names
'--feature-config', self.feathr_spark_laucher.upload_or_get_cloud_path(
generation_config.feature_config),
'--redis-config', self._getRedisConfigStr(),
'--s3-config', self._get_s3_config_str(),
'--adls-config', self._get_adls_config_str(),
'--blob-config', self._get_blob_config_str(),
'--sql-config', self._get_sql_config_str(),
'--snowflake-config', self._get_snowflake_config_str(),
'--kafka-config', self._get_kafka_config_str()
],
reference_files_path=[],
configuration=execution_configuratons,
)
def wait_job_to_finish(self, timeout_sec: int = 300):
"""Waits for the job to finish in a blocking way unless it times out
"""
if self.feathr_spark_laucher.wait_for_completion(timeout_sec):
return
else:
raise RuntimeError('Spark job failed.')
def _getRedisConfigStr(self):
"""Construct the Redis config string. The host, port, credential and other parameters can be set via environment
variables."""
password = _EnvVaraibleUtil.get_environment_variable(REDIS_PASSWORD)
host = self.redis_host
port = self.redis_port
ssl_enabled = self.redis_ssl_enabled
config_str = """
REDIS_PASSWORD: "{REDIS_PASSWORD}"
REDIS_HOST: "{REDIS_HOST}"
REDIS_PORT: {REDIS_PORT}
REDIS_SSL_ENABLED: {REDIS_SSL_ENABLED}
""".format(REDIS_PASSWORD=password, REDIS_HOST=host, REDIS_PORT=port, REDIS_SSL_ENABLED=ssl_enabled)
return config_str
def _get_s3_config_str(self):
"""Construct the S3 config string. The endpoint, access key, secret key, and other parameters can be set via
environment variables."""
endpoint = self.s3_endpoint
# if s3 endpoint is set in the feathr_config, then we need other environment variables
# keys can't be only accessed through environment
access_key = _EnvVaraibleUtil.get_environment_variable('S3_ACCESS_KEY')
secret_key = _EnvVaraibleUtil.get_environment_variable('S3_SECRET_KEY')
# HOCCON format will be parsed by the Feathr job
config_str = """
S3_ENDPOINT: {S3_ENDPOINT}
S3_ACCESS_KEY: "{S3_ACCESS_KEY}"
S3_SECRET_KEY: "{S3_SECRET_KEY}"
""".format(S3_ENDPOINT=endpoint, S3_ACCESS_KEY=access_key, S3_SECRET_KEY=secret_key)
return config_str
def _get_adls_config_str(self):
"""Construct the ADLS config string for abfs(s). The Account, access key and other parameters can be set via
environment variables."""
account = _EnvVaraibleUtil.get_environment_variable('ADLS_ACCOUNT')
# if ADLS Account is set in the feathr_config, then we need other environment variables
# keys can't be only accessed through environment
key = _EnvVaraibleUtil.get_environment_variable('ADLS_KEY')
# HOCCON format will be parsed by the Feathr job
config_str = """
ADLS_ACCOUNT: {ADLS_ACCOUNT}
ADLS_KEY: "{ADLS_KEY}"
""".format(ADLS_ACCOUNT=account, ADLS_KEY=key)
return config_str
def _get_blob_config_str(self):
"""Construct the Blob config string for wasb(s). The Account, access key and other parameters can be set via
environment variables."""
account = _EnvVaraibleUtil.get_environment_variable('BLOB_ACCOUNT')
# if BLOB Account is set in the feathr_config, then we need other environment variables
# keys can't be only accessed through environment
key = _EnvVaraibleUtil.get_environment_variable('BLOB_KEY')
# HOCCON format will be parsed by the Feathr job
config_str = """
BLOB_ACCOUNT: {BLOB_ACCOUNT}
BLOB_KEY: "{BLOB_KEY}"
""".format(BLOB_ACCOUNT=account, BLOB_KEY=key)
return config_str
def _get_sql_config_str(self):
"""Construct the SQL config string for jdbc. The dbtable (query), user, password and other parameters can be set via
environment variables."""
table = _EnvVaraibleUtil.get_environment_variable('JDBC_TABLE')
user = _EnvVaraibleUtil.get_environment_variable('JDBC_USER')
password = _EnvVaraibleUtil.get_environment_variable('JDBC_PASSWORD')
driver = _EnvVaraibleUtil.get_environment_variable('JDBC_DRIVER')
auth_flag = _EnvVaraibleUtil.get_environment_variable('JDBC_AUTH_FLAG')
token = _EnvVaraibleUtil.get_environment_variable('JDBC_TOKEN')
# HOCCON format will be parsed by the Feathr job
config_str = """
JDBC_TABLE: {JDBC_TABLE}
JDBC_USER: {JDBC_USER}
JDBC_PASSWORD: {JDBC_PASSWORD}
JDBC_DRIVER: {JDBC_DRIVER}
JDBC_AUTH_FLAG: {JDBC_AUTH_FLAG}
JDBC_TOKEN: {JDBC_TOKEN}
""".format(JDBC_TABLE=table, JDBC_USER=user, JDBC_PASSWORD=password, JDBC_DRIVER = driver, JDBC_AUTH_FLAG = auth_flag, JDBC_TOKEN = token)
return config_str
def _get_snowflake_config_str(self):
"""Construct the Snowflake config string for jdbc. The url, user, role and other parameters can be set via
yaml config. Password can be set via environment variables."""
sf_url = self.envutils.get_environment_variable_with_default('offline_store', 'snowflake', 'url')
sf_user = self.envutils.get_environment_variable_with_default('offline_store', 'snowflake', 'user')
sf_role = self.envutils.get_environment_variable_with_default('offline_store', 'snowflake', 'role')
sf_password = self.envutils.get_environment_variable('JDBC_SF_PASSWORD')
# HOCCON format will be parsed by the Feathr job
config_str = """
JDBC_SF_URL: {JDBC_SF_URL}
JDBC_SF_USER: {JDBC_SF_USER}
JDBC_SF_ROLE: {JDBC_SF_ROLE}
JDBC_SF_PASSWORD: {JDBC_SF_PASSWORD}
""".format(JDBC_SF_URL=sf_url, JDBC_SF_USER=sf_user, JDBC_SF_PASSWORD=sf_password, JDBC_SF_ROLE=sf_role)
return config_str
def _get_kafka_config_str(self):
"""Construct the Kafka config string. The endpoint, access key, secret key, and other parameters can be set via
environment variables."""
sasl = _EnvVaraibleUtil.get_environment_variable('KAFKA_SASL_JAAS_CONFIG')
# HOCCON format will be parsed by the Feathr job
config_str = """
KAFKA_SASL_JAAS_CONFIG: "{sasl}"
""".format(sasl=sasl)
return config_str
| [] | [] | [] | [] | [] | python | 0 | 0 | |
main.go | package main
import (
"bufio"
"fmt"
"os"
"path/filepath"
"regexp"
"strings"
"time"
"github.com/bitrise-io/go-steputils/input"
"github.com/bitrise-io/go-steputils/stepconf"
"github.com/bitrise-io/go-utils/colorstring"
"github.com/bitrise-io/go-utils/command"
"github.com/bitrise-io/go-utils/errorutil"
"github.com/bitrise-io/go-utils/fileutil"
"github.com/bitrise-io/go-utils/log"
"github.com/bitrise-io/go-utils/pathutil"
"github.com/bitrise-io/go-utils/sliceutil"
"github.com/bitrise-io/go-utils/stringutil"
"github.com/bitrise-io/go-xcode/certificateutil"
"github.com/bitrise-io/go-xcode/export"
"github.com/bitrise-io/go-xcode/exportoptions"
"github.com/bitrise-io/go-xcode/profileutil"
"github.com/bitrise-io/go-xcode/utility"
"github.com/bitrise-io/go-xcode/xcarchive"
"github.com/bitrise-io/go-xcode/xcodebuild"
"github.com/bitrise-io/go-xcode/xcpretty"
"github.com/tamasbazs/steps-xcode-archive-without-export/utils"
"github.com/kballard/go-shellquote"
"howett.net/plist"
)
const (
minSupportedXcodeMajorVersion = 6
)
const (
bitriseXcodeRawResultTextEnvKey = "BITRISE_XCODE_RAW_RESULT_TEXT_PATH"
bitriseIDEDistributionLogsPthEnvKey = "BITRISE_IDEDISTRIBUTION_LOGS_PATH"
bitriseXCArchivePthEnvKey = "BITRISE_XCARCHIVE_PATH"
bitriseXCArchiveZipPthEnvKey = "BITRISE_XCARCHIVE_ZIP_PATH"
bitriseAppDirPthEnvKey = "BITRISE_APP_DIR_PATH"
bitriseIPAPthEnvKey = "BITRISE_IPA_PATH"
bitriseDSYMDirPthEnvKey = "BITRISE_DSYM_DIR_PATH"
bitriseDSYMPthEnvKey = "BITRISE_DSYM_PATH"
)
// configs ...
type configs struct {
ExportMethod string `env:"export_method,opt[auto-detect,app-store,ad-hoc,enterprise,development]"`
UploadBitcode string `env:"upload_bitcode,opt[yes,no]"`
CompileBitcode string `env:"compile_bitcode,opt[yes,no]"`
ICloudContainerEnvironment string `env:"icloud_container_environment"`
TeamID string `env:"team_id"`
UseDeprecatedExport string `env:"use_deprecated_export,opt[yes,no]"`
ForceTeamID string `env:"force_team_id"`
ForceProvisioningProfileSpecifier string `env:"force_provisioning_profile_specifier"`
ForceProvisioningProfile string `env:"force_provisioning_profile"`
ForceCodeSignIdentity string `env:"force_code_sign_identity"`
CustomExportOptionsPlistContent string `env:"custom_export_options_plist_content"`
OutputTool string `env:"output_tool,opt[xcpretty,xcodebuild]"`
Workdir string `env:"workdir"`
ProjectPath string `env:"project_path,file"`
Scheme string `env:"scheme,required"`
Configuration string `env:"configuration"`
OutputDir string `env:"output_dir,required"`
IsCleanBuild string `env:"is_clean_build,opt[yes,no]"`
XcodebuildOptions string `env:"xcodebuild_options"`
DisableIndexWhileBuilding bool `env:"disable_index_while_building,opt[yes,no]"`
IsExportXcarchiveZip string `env:"is_export_xcarchive_zip,opt[yes,no]"`
ExportAllDsyms string `env:"export_all_dsyms,opt[yes,no]"`
ArtifactName string `env:"artifact_name"`
VerboseLog bool `env:"verbose_log,opt[yes,no]"`
}
func fail(format string, v ...interface{}) {
log.Errorf(format, v...)
os.Exit(1)
}
func findIDEDistrubutionLogsPath(output string) (string, error) {
pattern := `IDEDistribution: -\[IDEDistributionLogging _createLoggingBundleAtPath:\]: Created bundle at path '(?P<log_path>.*)'`
re := regexp.MustCompile(pattern)
scanner := bufio.NewScanner(strings.NewReader(output))
for scanner.Scan() {
line := scanner.Text()
if match := re.FindStringSubmatch(line); len(match) == 2 {
return match[1], nil
}
}
if err := scanner.Err(); err != nil {
return "", err
}
return "", nil
}
func currentTimestamp() string {
timeStampFormat := "15:04:05"
currentTime := time.Now()
return currentTime.Format(timeStampFormat)
}
// ColoringFunc ...
type ColoringFunc func(...interface{}) string
func logWithTimestamp(coloringFunc ColoringFunc, format string, v ...interface{}) {
message := fmt.Sprintf(format, v...)
messageWithTimeStamp := fmt.Sprintf("[%s] %s", currentTimestamp(), coloringFunc(message))
fmt.Println(messageWithTimeStamp)
}
func main() {
var cfg configs
if err := stepconf.Parse(&cfg); err != nil {
fail("Issue with input: %s", err)
}
stepconf.Print(cfg)
fmt.Println()
log.SetEnableDebugLog(cfg.VerboseLog)
if cfg.ExportMethod == "auto-detect" {
exportMethods := []exportoptions.Method{exportoptions.MethodAppStore, exportoptions.MethodAdHoc, exportoptions.MethodEnterprise, exportoptions.MethodDevelopment}
log.Warnf("Export method: auto-detect is DEPRECATED, use a direct export method %s", exportMethods)
fmt.Println()
}
if cfg.Workdir != "" {
if err := input.ValidateIfDirExists(cfg.Workdir); err != nil {
fail("issue with input Workdir: " + err.Error())
}
}
if cfg.CustomExportOptionsPlistContent != "" {
var options map[string]interface{}
if _, err := plist.Unmarshal([]byte(cfg.CustomExportOptionsPlistContent), &options); err != nil {
fail("issue with input CustomExportOptionsPlistContent: " + err.Error())
}
}
log.Infof("step determined configs:")
// Detect Xcode major version
xcodebuildVersion, err := utility.GetXcodeVersion()
if err != nil {
fail("Failed to determin xcode version, error: %s", err)
}
log.Printf("- xcodebuildVersion: %s (%s)", xcodebuildVersion.Version, xcodebuildVersion.BuildVersion)
xcodeMajorVersion := xcodebuildVersion.MajorVersion
if xcodeMajorVersion < minSupportedXcodeMajorVersion {
fail("Invalid xcode major version (%d), should not be less then min supported: %d", xcodeMajorVersion, minSupportedXcodeMajorVersion)
}
// Detect xcpretty version
outputTool := cfg.OutputTool
if outputTool == "xcpretty" {
fmt.Println()
log.Infof("Checking if output tool (xcpretty) is installed")
installed, err := xcpretty.IsInstalled()
if err != nil {
log.Warnf("Failed to check if xcpretty is installed, error: %s", err)
log.Printf("Switching to xcodebuild for output tool")
outputTool = "xcodebuild"
} else if !installed {
log.Warnf(`xcpretty is not installed`)
fmt.Println()
log.Printf("Installing xcpretty")
if cmds, err := xcpretty.Install(); err != nil {
log.Warnf("Failed to create xcpretty install command: %s", err)
log.Warnf("Switching to xcodebuild for output tool")
outputTool = "xcodebuild"
} else {
for _, cmd := range cmds {
if out, err := cmd.RunAndReturnTrimmedCombinedOutput(); err != nil {
if errorutil.IsExitStatusError(err) {
log.Warnf("%s failed: %s", out)
} else {
log.Warnf("%s failed: %s", err)
}
log.Warnf("Switching to xcodebuild for output tool")
outputTool = "xcodebuild"
}
}
}
}
}
if outputTool == "xcpretty" {
xcprettyVersion, err := xcpretty.Version()
if err != nil {
log.Warnf("Failed to determin xcpretty version, error: %s", err)
log.Printf("Switching to xcodebuild for output tool")
outputTool = "xcodebuild"
}
log.Printf("- xcprettyVersion: %s", xcprettyVersion.String())
}
// Validation CustomExportOptionsPlistContent
customExportOptionsPlistContent := strings.TrimSpace(cfg.CustomExportOptionsPlistContent)
if customExportOptionsPlistContent != cfg.CustomExportOptionsPlistContent {
fmt.Println()
log.Warnf("CustomExportOptionsPlistContent is stripped to remove spaces and new lines:")
log.Printf(customExportOptionsPlistContent)
}
if customExportOptionsPlistContent != "" {
if xcodeMajorVersion < 7 {
fmt.Println()
log.Warnf("CustomExportOptionsPlistContent is set, but CustomExportOptionsPlistContent only used if xcodeMajorVersion > 6")
customExportOptionsPlistContent = ""
} else {
fmt.Println()
log.Warnf("Ignoring the following options because CustomExportOptionsPlistContent provided:")
log.Printf("- ExportMethod: %s", cfg.ExportMethod)
log.Printf("- UploadBitcode: %s", cfg.UploadBitcode)
log.Printf("- CompileBitcode: %s", cfg.CompileBitcode)
log.Printf("- TeamID: %s", cfg.TeamID)
fmt.Println()
}
}
if cfg.ForceProvisioningProfileSpecifier != "" &&
xcodeMajorVersion < 8 {
fmt.Println()
log.Warnf("ForceProvisioningProfileSpecifier is set, but ForceProvisioningProfileSpecifier only used if xcodeMajorVersion > 7")
cfg.ForceProvisioningProfileSpecifier = ""
}
if cfg.ForceTeamID != "" &&
xcodeMajorVersion < 8 {
fmt.Println()
log.Warnf("ForceTeamID is set, but ForceTeamID only used if xcodeMajorVersion > 7")
cfg.ForceTeamID = ""
}
if cfg.ForceProvisioningProfileSpecifier != "" &&
cfg.ForceProvisioningProfile != "" {
fmt.Println()
log.Warnf("both ForceProvisioningProfileSpecifier and ForceProvisioningProfile are set, using ForceProvisioningProfileSpecifier")
cfg.ForceProvisioningProfile = ""
}
fmt.Println()
// abs out dir pth
absOutputDir, err := pathutil.AbsPath(cfg.OutputDir)
if err != nil {
fail("Failed to expand OutputDir (%s), error: %s", cfg.OutputDir, err)
}
cfg.OutputDir = absOutputDir
if exist, err := pathutil.IsPathExists(cfg.OutputDir); err != nil {
fail("Failed to check if OutputDir exist, error: %s", err)
} else if !exist {
if err := os.MkdirAll(cfg.OutputDir, 0777); err != nil {
fail("Failed to create OutputDir (%s), error: %s", cfg.OutputDir, err)
}
}
// output files
tmpArchiveDir, err := pathutil.NormalizedOSTempDirPath("__archive__")
if err != nil {
fail("Failed to create temp dir for archives, error: %s", err)
}
tmpArchivePath := filepath.Join(tmpArchiveDir, cfg.ArtifactName+".xcarchive")
appPath := filepath.Join(cfg.OutputDir, cfg.ArtifactName+".app")
ipaPath := filepath.Join(cfg.OutputDir, cfg.ArtifactName+".ipa")
exportOptionsPath := filepath.Join(cfg.OutputDir, "export_options.plist")
rawXcodebuildOutputLogPath := filepath.Join(cfg.OutputDir, "raw-xcodebuild-output.log")
dsymZipPath := filepath.Join(cfg.OutputDir, cfg.ArtifactName+".dSYM.zip")
archiveZipPath := filepath.Join(cfg.OutputDir, cfg.ArtifactName+".xcarchive.zip")
ideDistributionLogsZipPath := filepath.Join(cfg.OutputDir, "xcodebuild.xcdistributionlogs.zip")
// cleanup
filesToCleanup := []string{
appPath,
ipaPath,
exportOptionsPath,
rawXcodebuildOutputLogPath,
dsymZipPath,
archiveZipPath,
ideDistributionLogsZipPath,
}
for _, pth := range filesToCleanup {
if exist, err := pathutil.IsPathExists(pth); err != nil {
fail("Failed to check if path (%s) exist, error: %s", pth, err)
} else if exist {
if err := os.RemoveAll(pth); err != nil {
fail("Failed to remove path (%s), error: %s", pth, err)
}
}
}
//
// Create the Archive with Xcode Command Line tools
log.Infof("Create the Archive ...")
fmt.Println()
isWorkspace := false
ext := filepath.Ext(cfg.ProjectPath)
if ext == ".xcodeproj" {
isWorkspace = false
} else if ext == ".xcworkspace" {
isWorkspace = true
} else {
fail("Project file extension should be .xcodeproj or .xcworkspace, but got: %s", ext)
}
archiveCmd := xcodebuild.NewCommandBuilder(cfg.ProjectPath, isWorkspace, xcodebuild.ArchiveAction)
archiveCmd.SetScheme(cfg.Scheme)
archiveCmd.SetConfiguration(cfg.Configuration)
if cfg.ForceTeamID != "" {
log.Printf("Forcing Development Team: %s", cfg.ForceTeamID)
archiveCmd.SetForceDevelopmentTeam(cfg.ForceTeamID)
}
if cfg.ForceProvisioningProfileSpecifier != "" {
log.Printf("Forcing Provisioning Profile Specifier: %s", cfg.ForceProvisioningProfileSpecifier)
archiveCmd.SetForceProvisioningProfileSpecifier(cfg.ForceProvisioningProfileSpecifier)
}
if cfg.ForceProvisioningProfile != "" {
log.Printf("Forcing Provisioning Profile: %s", cfg.ForceProvisioningProfile)
archiveCmd.SetForceProvisioningProfile(cfg.ForceProvisioningProfile)
}
if cfg.ForceCodeSignIdentity != "" {
log.Printf("Forcing Code Signing Identity: %s", cfg.ForceCodeSignIdentity)
archiveCmd.SetForceCodeSignIdentity(cfg.ForceCodeSignIdentity)
}
if cfg.IsCleanBuild == "yes" {
archiveCmd.SetCustomBuildAction("clean")
}
archiveCmd.SetDisableIndexWhileBuilding(cfg.DisableIndexWhileBuilding)
archiveCmd.SetArchivePath(tmpArchivePath)
if cfg.XcodebuildOptions != "" {
options, err := shellquote.Split(cfg.XcodebuildOptions)
if err != nil {
fail("Failed to shell split XcodebuildOptions (%s), error: %s", cfg.XcodebuildOptions)
}
archiveCmd.SetCustomOptions(options)
}
if outputTool == "xcpretty" {
xcprettyCmd := xcpretty.New(archiveCmd)
logWithTimestamp(colorstring.Green, "$ %s", xcprettyCmd.PrintableCmd())
fmt.Println()
if rawXcodebuildOut, err := xcprettyCmd.Run(); err != nil {
log.Errorf("\nLast lines of the Xcode's build log:")
fmt.Println(stringutil.LastNLines(rawXcodebuildOut, 10))
if err := utils.ExportOutputFileContent(rawXcodebuildOut, rawXcodebuildOutputLogPath, bitriseXcodeRawResultTextEnvKey); err != nil {
log.Warnf("Failed to export %s, error: %s", bitriseXcodeRawResultTextEnvKey, err)
} else {
log.Warnf(`You can find the last couple of lines of Xcode's build log above, but the full log is also available in the raw-xcodebuild-output.log
The log file is stored in $BITRISE_DEPLOY_DIR, and its full path is available in the $BITRISE_XCODE_RAW_RESULT_TEXT_PATH environment variable
(value: %s)`, rawXcodebuildOutputLogPath)
}
fail("Archive failed, error: %s", err)
}
} else {
logWithTimestamp(colorstring.Green, "$ %s", archiveCmd.PrintableCmd())
fmt.Println()
archiveRootCmd := archiveCmd.Command()
archiveRootCmd.SetStdout(os.Stdout)
archiveRootCmd.SetStderr(os.Stderr)
if err := archiveRootCmd.Run(); err != nil {
fail("Archive failed, error: %s", err)
}
}
fmt.Println()
// Ensure xcarchive exists
if exist, err := pathutil.IsPathExists(tmpArchivePath); err != nil {
fail("Failed to check if archive exist, error: %s", err)
} else if !exist {
fail("No archive generated at: %s", tmpArchivePath)
}
if xcodeMajorVersion >= 9 && cfg.UseDeprecatedExport == "yes" {
fail("Legacy export method (using '-exportFormat ipa' flag) is not supported from Xcode version 9")
}
envsToUnset := []string{"GEM_HOME", "GEM_PATH", "RUBYLIB", "RUBYOPT", "BUNDLE_BIN_PATH", "_ORIGINAL_GEM_PATH", "BUNDLE_GEMFILE"}
for _, key := range envsToUnset {
if err := os.Unsetenv(key); err != nil {
fail("Failed to unset (%s), error: %s", key, err)
}
}
/*
archive, err := xcarchive.NewIosArchive(tmpArchivePath)
if err != nil {
fail("Failed to parse archive, error: %s", err)
}
mainApplication := archive.Application
archiveExportMethod := mainApplication.ProvisioningProfile.ExportType
archiveCodeSignIsXcodeManaged := profileutil.IsXcodeManaged(mainApplication.ProvisioningProfile.Name)
log.Infof("Archive infos:")
log.Printf("team: %s (%s)", mainApplication.ProvisioningProfile.TeamName, mainApplication.ProvisioningProfile.TeamID)
log.Printf("profile: %s (%s)", mainApplication.ProvisioningProfile.Name, mainApplication.ProvisioningProfile.UUID)
log.Printf("export: %s", archiveExportMethod)
log.Printf("xcode managed profile: %v", archiveCodeSignIsXcodeManaged)
fmt.Println()
//
// Exporting the ipa with Xcode Command Line tools
You'll get a "Error Domain=IDEDistributionErrorDomain Code=14 "No applicable devices found."" error
if $GEM_HOME is set and the project's directory includes a Gemfile - to fix this
we'll unset GEM_HOME as that's not required for xcodebuild anyway.
This probably fixes the RVM issue too, but that still should be tested.
See also:
- http://stackoverflow.com/questions/33041109/xcodebuild-no-applicable-devices-found-when-exporting-archive
- https://gist.github.com/claybridges/cea5d4afd24eda268164
log.Infof("Exporting ipa from the archive...")
fmt.Println()
if xcodeMajorVersion <= 6 || cfg.UseDeprecatedExport == "yes" {
log.Printf("Using legacy export")
Get the name of the profile which was used for creating the archive
--> Search for embedded.mobileprovision in the xcarchive.
It should contain a .app folder in the xcarchive folder
under the Products/Applications folder
legacyExportCmd := xcodebuild.NewLegacyExportCommand()
legacyExportCmd.SetExportFormat("ipa")
legacyExportCmd.SetArchivePath(tmpArchivePath)
legacyExportCmd.SetExportPath(ipaPath)
legacyExportCmd.SetExportProvisioningProfileName(mainApplication.ProvisioningProfile.Name)
if outputTool == "xcpretty" {
xcprettyCmd := xcpretty.New(legacyExportCmd)
logWithTimestamp(colorstring.Green, xcprettyCmd.PrintableCmd())
fmt.Println()
if rawXcodebuildOut, err := xcprettyCmd.Run(); err != nil {
if err := utils.ExportOutputFileContent(rawXcodebuildOut, rawXcodebuildOutputLogPath, bitriseXcodeRawResultTextEnvKey); err != nil {
log.Warnf("Failed to export %s, error: %s", bitriseXcodeRawResultTextEnvKey, err)
} else {
log.Warnf(`If you can't find the reason of the error in the log, please check the raw-xcodebuild-output.log
The log file is stored in $BITRISE_DEPLOY_DIR, and its full path
is available in the $BITRISE_XCODE_RAW_RESULT_TEXT_PATH environment variable`)
}
fail("Export failed, error: %s", err)
}
} else {
logWithTimestamp(colorstring.Green, legacyExportCmd.PrintableCmd())
fmt.Println()
if err := legacyExportCmd.Run(); err != nil {
fail("Export failed, error: %s", err)
}
}
} else {
log.Printf("Exporting ipa with ExportOptions.plist")
if customExportOptionsPlistContent != "" {
log.Printf("Custom export options content provided, using it:")
fmt.Println(customExportOptionsPlistContent)
if err := fileutil.WriteStringToFile(exportOptionsPath, customExportOptionsPlistContent); err != nil {
fail("Failed to write export options to file, error: %s", err)
}
} else {
log.Printf("No custom export options content provided, generating export options...")
var exportMethod exportoptions.Method
exportTeamID := ""
exportCodeSignIdentity := ""
exportCodeSignStyle := ""
exportProfileMapping := map[string]string{}
if cfg.ExportMethod == "auto-detect" {
log.Printf("auto-detect export method specified")
exportMethod = archiveExportMethod
log.Printf("using the archive profile's (%s) export method: %s", mainApplication.ProvisioningProfile.Name, exportMethod)
} else {
parsedMethod, err := exportoptions.ParseMethod(cfg.ExportMethod)
if err != nil {
fail("Failed to parse export options, error: %s", err)
}
exportMethod = parsedMethod
log.Printf("export-method specified: %s", cfg.ExportMethod)
}
bundleIDEntitlementsMap, err := utils.ProjectEntitlementsByBundleID(cfg.ProjectPath, cfg.Scheme, cfg.Configuration)
if err != nil {
fail(err.Error())
}
// iCloudContainerEnvironment: If the app is using CloudKit, this configures the "com.apple.developer.icloud-container-environment" entitlement.
// Available options vary depending on the type of provisioning profile used, but may include: Development and Production.
usesCloudKit := false
for _, entitlements := range bundleIDEntitlementsMap {
if entitlements == nil {
continue
}
services, ok := entitlements.GetStringArray("com.apple.developer.icloud-services")
if ok {
usesCloudKit = sliceutil.IsStringInSlice("CloudKit", services) || sliceutil.IsStringInSlice("CloudDocuments", services)
if usesCloudKit {
break
}
}
}
// From Xcode 9 iCloudContainerEnvironment is required for every export method, before that version only for non app-store exports.
var iCloudContainerEnvironment string
if usesCloudKit && (xcodeMajorVersion >= 9 || exportMethod != exportoptions.MethodAppStore) {
if exportMethod == exportoptions.MethodAppStore {
iCloudContainerEnvironment = "Production"
} else if cfg.ICloudContainerEnvironment == "" {
fail("project uses CloudKit, but iCloud container environment input not specified")
} else {
iCloudContainerEnvironment = cfg.ICloudContainerEnvironment
}
}
if xcodeMajorVersion >= 9 {
log.Printf("xcode major version > 9, generating provisioningProfiles node")
fmt.Println()
log.Printf("Target Bundle ID - Entitlements map")
var bundleIDs []string
for bundleID, entitlements := range bundleIDEntitlementsMap {
bundleIDs = append(bundleIDs, bundleID)
entitlementKeys := []string{}
for key := range entitlements {
entitlementKeys = append(entitlementKeys, key)
}
log.Printf("%s: %s", bundleID, entitlementKeys)
}
fmt.Println()
log.Printf("Resolving CodeSignGroups...")
certs, err := certificateutil.InstalledCodesigningCertificateInfos()
if err != nil {
fail("Failed to get installed certificates, error: %s", err)
}
certs = certificateutil.FilterValidCertificateInfos(certs)
log.Debugf("Installed certificates:")
for _, certInfo := range certs {
log.Debugf(certInfo.String())
}
profs, err := profileutil.InstalledProvisioningProfileInfos(profileutil.ProfileTypeIos)
if err != nil {
fail("Failed to get installed provisioning profiles, error: %s", err)
}
log.Debugf("Installed profiles:")
for _, profileInfo := range profs {
log.Debugf(profileInfo.String(certs...))
}
log.Printf("Resolving CodeSignGroups...")
codeSignGroups := export.CreateSelectableCodeSignGroups(certs, profs, bundleIDs)
if len(codeSignGroups) == 0 {
log.Errorf("Failed to find code signing groups for specified export method (%s)", exportMethod)
}
for _, group := range codeSignGroups {
log.Debugf(group.String())
}
filters := []export.SelectableCodeSignGroupFilter{}
if len(bundleIDEntitlementsMap) > 0 {
log.Warnf("Filtering CodeSignInfo groups for target capabilities")
filters = append(filters,
export.CreateEntitlementsSelectableCodeSignGroupFilter(bundleIDEntitlementsMap))
}
log.Warnf("Filtering CodeSignInfo groups for export method")
filters = append(filters,
export.CreateExportMethodSelectableCodeSignGroupFilter(exportMethod))
if cfg.TeamID != "" {
log.Warnf("Export TeamID specified: %s, filtering CodeSignInfo groups...", cfg.TeamID)
filters = append(filters,
export.CreateTeamSelectableCodeSignGroupFilter(cfg.TeamID))
}
if !archiveCodeSignIsXcodeManaged {
log.Warnf("App was signed with NON xcode managed profile when archiving,\n" +
"only NOT xcode managed profiles are allowed to sign when exporting the archive.\n" +
"Removing xcode managed CodeSignInfo groups")
filters = append(filters, export.CreateNotXcodeManagedSelectableCodeSignGroupFilter())
}
codeSignGroups = export.FilterSelectableCodeSignGroups(codeSignGroups, filters...)
defaultProfileURL := os.Getenv("BITRISE_DEFAULT_PROVISION_URL")
if cfg.TeamID == "" && defaultProfileURL != "" {
if defaultProfile, err := utils.GetDefaultProvisioningProfile(); err == nil {
log.Debugf("\ndefault profile: %v\n", defaultProfile)
filteredCodeSignGroups := export.FilterSelectableCodeSignGroups(codeSignGroups,
export.CreateExcludeProfileNameSelectableCodeSignGroupFilter(defaultProfile.Name))
if len(filteredCodeSignGroups) > 0 {
codeSignGroups = filteredCodeSignGroups
}
}
}
iosCodeSignGroups := export.CreateIosCodeSignGroups(codeSignGroups)
if len(iosCodeSignGroups) > 0 {
codeSignGroup := export.IosCodeSignGroup{}
if len(iosCodeSignGroups) >= 1 {
codeSignGroup = iosCodeSignGroups[0]
}
if len(iosCodeSignGroups) > 1 {
log.Warnf("Multiple code signing groups found! Using the first code signing group")
}
exportTeamID = codeSignGroup.Certificate().TeamID
exportCodeSignIdentity = codeSignGroup.Certificate().CommonName
for bundleID, profileInfo := range codeSignGroup.BundleIDProfileMap() {
exportProfileMapping[bundleID] = profileInfo.Name
isXcodeManaged := profileutil.IsXcodeManaged(profileInfo.Name)
if isXcodeManaged {
if exportCodeSignStyle != "" && exportCodeSignStyle != "automatic" {
log.Errorf("Both xcode managed and NON xcode managed profiles in code signing group")
}
exportCodeSignStyle = "automatic"
} else {
if exportCodeSignStyle != "" && exportCodeSignStyle != "manual" {
log.Errorf("Both xcode managed and NON xcode managed profiles in code signing group")
}
exportCodeSignStyle = "manual"
}
}
} else {
log.Errorf("Failed to find Codesign Groups")
}
}
var exportOpts exportoptions.ExportOptions
if exportMethod == exportoptions.MethodAppStore {
options := exportoptions.NewAppStoreOptions()
options.UploadBitcode = (cfg.UploadBitcode == "yes")
if xcodeMajorVersion >= 9 {
options.BundleIDProvisioningProfileMapping = exportProfileMapping
options.SigningCertificate = exportCodeSignIdentity
options.TeamID = exportTeamID
if archiveCodeSignIsXcodeManaged && exportCodeSignStyle == "manual" {
log.Warnf("App was signed with xcode managed profile when archiving,")
log.Warnf("ipa export uses manual code signing.")
log.Warnf(`Setting "signingStyle" to "manual"`)
options.SigningStyle = "manual"
}
}
if iCloudContainerEnvironment != "" {
options.ICloudContainerEnvironment = exportoptions.ICloudContainerEnvironment(iCloudContainerEnvironment)
}
exportOpts = options
} else {
options := exportoptions.NewNonAppStoreOptions(exportMethod)
options.CompileBitcode = (cfg.CompileBitcode == "yes")
if xcodeMajorVersion >= 9 {
options.BundleIDProvisioningProfileMapping = exportProfileMapping
options.SigningCertificate = exportCodeSignIdentity
options.TeamID = exportTeamID
if archiveCodeSignIsXcodeManaged && exportCodeSignStyle == "manual" {
log.Warnf("App was signed with xcode managed profile when archiving,")
log.Warnf("ipa export uses manual code signing.")
log.Warnf(`Setting "signingStyle" to "manual"`)
options.SigningStyle = "manual"
}
}
if iCloudContainerEnvironment != "" {
options.ICloudContainerEnvironment = exportoptions.ICloudContainerEnvironment(iCloudContainerEnvironment)
}
exportOpts = options
}
fmt.Println()
log.Printf("generated export options content:")
fmt.Println()
fmt.Println(exportOpts.String())
if err = exportOpts.WriteToFile(exportOptionsPath); err != nil {
fail("Failed to write export options to file, error: %s", err)
}
}
fmt.Println()
tmpDir, err := pathutil.NormalizedOSTempDirPath("__export__")
if err != nil {
fail("Failed to create tmp dir, error: %s", err)
}
exportCmd := xcodebuild.NewExportCommand()
exportCmd.SetArchivePath(tmpArchivePath)
exportCmd.SetExportDir(tmpDir)
exportCmd.SetExportOptionsPlist(exportOptionsPath)
if outputTool == "xcpretty" {
xcprettyCmd := xcpretty.New(exportCmd)
logWithTimestamp(colorstring.Green, xcprettyCmd.PrintableCmd())
fmt.Println()
if xcodebuildOut, err := xcprettyCmd.Run(); err != nil {
// xcodebuild raw output
if err := utils.ExportOutputFileContent(xcodebuildOut, rawXcodebuildOutputLogPath, bitriseXcodeRawResultTextEnvKey); err != nil {
log.Warnf("Failed to export %s, error: %s", bitriseXcodeRawResultTextEnvKey, err)
} else {
log.Warnf(`If you can't find the reason of the error in the log, please check the raw-xcodebuild-output.log
The log file is stored in $BITRISE_DEPLOY_DIR, and its full path
is available in the $BITRISE_XCODE_RAW_RESULT_TEXT_PATH environment variable`)
}
// xcdistributionlogs
if logsDirPth, err := findIDEDistrubutionLogsPath(xcodebuildOut); err != nil {
log.Warnf("Failed to find xcdistributionlogs, error: %s", err)
} else if err := utils.ExportOutputDirAsZip(logsDirPth, ideDistributionLogsZipPath, bitriseIDEDistributionLogsPthEnvKey); err != nil {
log.Warnf("Failed to export %s, error: %s", bitriseIDEDistributionLogsPthEnvKey, err)
} else {
criticalDistLogFilePth := filepath.Join(logsDirPth, "IDEDistribution.critical.log")
log.Warnf("IDEDistribution.critical.log:")
if criticalDistLog, err := fileutil.ReadStringFromFile(criticalDistLogFilePth); err == nil {
log.Printf(criticalDistLog)
}
log.Warnf(`Also please check the xcdistributionlogs
The logs directory is stored in $BITRISE_DEPLOY_DIR, and its full path
is available in the $BITRISE_IDEDISTRIBUTION_LOGS_PATH environment variable`)
}
fail("Export failed, error: %s", err)
}
} else {
logWithTimestamp(colorstring.Green, exportCmd.PrintableCmd())
fmt.Println()
if xcodebuildOut, err := exportCmd.RunAndReturnOutput(); err != nil {
// xcdistributionlogs
if logsDirPth, err := findIDEDistrubutionLogsPath(xcodebuildOut); err != nil {
log.Warnf("Failed to find xcdistributionlogs, error: %s", err)
} else if err := utils.ExportOutputDirAsZip(logsDirPth, ideDistributionLogsZipPath, bitriseIDEDistributionLogsPthEnvKey); err != nil {
log.Warnf("Failed to export %s, error: %s", bitriseIDEDistributionLogsPthEnvKey, err)
} else {
criticalDistLogFilePth := filepath.Join(logsDirPth, "IDEDistribution.critical.log")
log.Warnf("IDEDistribution.critical.log:")
if criticalDistLog, err := fileutil.ReadStringFromFile(criticalDistLogFilePth); err == nil {
log.Printf(criticalDistLog)
}
log.Warnf(`If you can't find the reason of the error in the log, please check the xcdistributionlogs
The logs directory is stored in $BITRISE_DEPLOY_DIR, and its full path
is available in the $BITRISE_IDEDISTRIBUTION_LOGS_PATH environment variable`)
}
fail("Export failed, error: %s", err)
}
}
// Search for ipa
fileList := []string{}
ipaFiles := []string{}
if walkErr := filepath.Walk(tmpDir, func(pth string, info os.FileInfo, err error) error {
if err != nil {
return err
}
fileList = append(fileList, pth)
if filepath.Ext(pth) == ".ipa" {
ipaFiles = append(ipaFiles, pth)
}
return nil
}); walkErr != nil {
fail("Failed to search for .ipa file, error: %s", err)
}
if len(ipaFiles) == 0 {
log.Errorf("No .ipa file found at export dir: %s", tmpDir)
log.Printf("File list in the export dir:")
for _, pth := range fileList {
log.Printf("- %s", pth)
}
fail("")
} else {
if err := command.CopyFile(ipaFiles[0], ipaPath); err != nil {
fail("Failed to copy (%s) -> (%s), error: %s", ipaFiles[0], ipaPath, err)
}
if len(ipaFiles) > 1 {
log.Warnf("More than 1 .ipa file found, exporting first one: %s", ipaFiles[0])
log.Warnf("Moving every ipa to the BITRISE_DEPLOY_DIR")
for i, pth := range ipaFiles {
if i == 0 {
continue
}
base := filepath.Base(pth)
deployPth := filepath.Join(cfg.OutputDir, base)
if err := command.CopyFile(pth, deployPth); err != nil {
fail("Failed to copy (%s) -> (%s), error: %s", pth, ipaPath, err)
}
}
}
}
}
log.Infof("Exporting outputs...")
//
// Export outputs
// Export .xcarchive
fmt.Println()
if err := utils.ExportOutputDir(tmpArchivePath, tmpArchivePath, bitriseXCArchivePthEnvKey); err != nil {
fail("Failed to export %s, error: %s", bitriseXCArchivePthEnvKey, err)
}
log.Donef("The xcarchive path is now available in the Environment Variable: %s (value: %s)", bitriseXCArchivePthEnvKey, tmpArchivePath)
if cfg.IsExportXcarchiveZip == "yes" {
if err := utils.ExportOutputDirAsZip(tmpArchivePath, archiveZipPath, bitriseXCArchiveZipPthEnvKey); err != nil {
fail("Failed to export %s, error: %s", bitriseXCArchiveZipPthEnvKey, err)
}
log.Donef("The xcarchive zip path is now available in the Environment Variable: %s (value: %s)", bitriseXCArchiveZipPthEnvKey, archiveZipPath)
}
// Export .app
fmt.Println()
exportedApp := mainApplication.Path
if err := utils.ExportOutputDir(exportedApp, exportedApp, bitriseAppDirPthEnvKey); err != nil {
fail("Failed to export %s, error: %s", bitriseAppDirPthEnvKey, err)
}
log.Donef("The app directory is now available in the Environment Variable: %s (value: %s)", bitriseAppDirPthEnvKey, appPath)
// Export .ipa
fmt.Println()
if err := utils.ExportOutputFile(ipaPath, ipaPath, bitriseIPAPthEnvKey); err != nil {
fail("Failed to export %s, error: %s", bitriseIPAPthEnvKey, err)
}
log.Donef("The ipa path is now available in the Environment Variable: %s (value: %s)", bitriseIPAPthEnvKey, ipaPath)
// Export .dSYMs
fmt.Println()
appDSYM, frameworkDSYMs, err := archive.FindDSYMs()
if err != nil {
if err.Error() == "no dsym found" {
log.Warnf("no app nor framework dsyms found")
} else {
fail("Failed to export dsyms, error: %s", err)
}
}
if err == nil {
dsymDir, err := pathutil.NormalizedOSTempDirPath("__dsyms__")
if err != nil {
fail("Failed to create tmp dir, error: %s", err)
}
if err := command.CopyDir(appDSYM, dsymDir, false); err != nil {
fail("Failed to copy (%s) -> (%s), error: %s", appDSYM, dsymDir, err)
}
if cfg.ExportAllDsyms == "yes" {
for _, dsym := range frameworkDSYMs {
if err := command.CopyDir(dsym, dsymDir, false); err != nil {
fail("Failed to copy (%s) -> (%s), error: %s", dsym, dsymDir, err)
}
}
}
if err := utils.ExportOutputDir(dsymDir, dsymDir, bitriseDSYMDirPthEnvKey); err != nil {
fail("Failed to export %s, error: %s", bitriseDSYMDirPthEnvKey, err)
}
log.Donef("The dSYM dir path is now available in the Environment Variable: %s (value: %s)", bitriseDSYMDirPthEnvKey, dsymDir)
if err := utils.ExportOutputDirAsZip(dsymDir, dsymZipPath, bitriseDSYMPthEnvKey); err != nil {
fail("Failed to export %s, error: %s", bitriseDSYMPthEnvKey, err)
}
log.Donef("The dSYM zip path is now available in the Environment Variable: %s (value: %s)", bitriseDSYMPthEnvKey, dsymZipPath)
}*/
}
| [
"\"BITRISE_DEFAULT_PROVISION_URL\""
] | [] | [
"BITRISE_DEFAULT_PROVISION_URL"
] | [] | ["BITRISE_DEFAULT_PROVISION_URL"] | go | 1 | 0 | |
src/mask_rcnn_ros/scripts/mask_rcnn_node.py | #!/usr/bin/env python
import os
import threading
import numpy as np
import cv2
from cv_bridge import CvBridge
import matplotlib.pyplot as plt
import rospy
from sensor_msgs.msg import Image
from sensor_msgs.msg import RegionOfInterest
from mask_rcnn_ros import coco
from mask_rcnn_ros import utils
from mask_rcnn_ros import model as modellib
from mask_rcnn_ros import visualize
from mask_rcnn_ros.msg import Result
# Local path to trained weights file
ROS_HOME = os.environ.get('ROS_HOME', os.path.join(os.environ['HOME'], '.ros'))
COCO_MODEL_PATH = os.path.join(ROS_HOME, 'mask_rcnn_coco.h5')
RGB_TOPIC = '/camera/rgb/image_raw'
# COCO Class names
# Index of the class in the list is its ID. For example, to get ID of
# the teddy bear class, use: CLASS_NAMES.index('teddy bear')
CLASS_NAMES = ['BG', 'person', 'bicycle', 'car', 'motorcycle', 'airplane',
'bus', 'train', 'truck', 'boat', 'traffic light',
'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird',
'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear',
'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie',
'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball',
'kite', 'baseball bat', 'baseball glove', 'skateboard',
'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup',
'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',
'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza',
'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed',
'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote',
'keyboard', 'cell phone', 'microwave', 'oven', 'toaster',
'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors',
'teddy bear', 'hair drier', 'toothbrush']
class InferenceConfig(coco.CocoConfig):
# Set batch size to 1 since we'll be running inference on
# one image at a time. Batch size = GPU_COUNT * IMAGES_PER_GPU
GPU_COUNT = 1
IMAGES_PER_GPU = 1
class MaskRCNNNode(object):
def __init__(self):
self._cv_bridge = CvBridge()
config = InferenceConfig()
config.display()
# Get input RGB topic.
self._rgb_input_topic = rospy.get_param('~input', RGB_TOPIC)
self._visualization = rospy.get_param('~visualization', True)
# Create model object in inference mode.
self._model = modellib.MaskRCNN(mode="inference", model_dir="",
config=config)
# Load weights trained on MS-COCO
model_path = rospy.get_param('~model_path', COCO_MODEL_PATH)
# Download COCO trained weights from Releases if needed
if model_path == COCO_MODEL_PATH and not os.path.exists(COCO_MODEL_PATH):
utils.download_trained_weights(COCO_MODEL_PATH)
self._model.load_weights(model_path, by_name=True)
self._class_names = rospy.get_param('~class_names', CLASS_NAMES)
self._last_msg = None
self._msg_lock = threading.Lock()
self._class_colors = visualize.random_colors(len(CLASS_NAMES))
self._publish_rate = rospy.get_param('~publish_rate', 100)
def run(self):
self._result_pub = rospy.Publisher('~result', Result, queue_size=1)
vis_pub = rospy.Publisher('~visualization', Image, queue_size=1)
rospy.Subscriber(self._rgb_input_topic, Image,
self._image_callback, queue_size=1)
rate = rospy.Rate(self._publish_rate)
while not rospy.is_shutdown():
if self._msg_lock.acquire(False):
msg = self._last_msg
self._last_msg = None
self._msg_lock.release()
else:
rate.sleep()
continue
if msg is not None:
np_image = self._cv_bridge.imgmsg_to_cv2(msg, 'bgr8')
# Run detection
results = self._model.detect([np_image], verbose=0)
result = results[0]
result_msg = self._build_result_msg(msg, result)
self._result_pub.publish(result_msg)
# Visualize results
if self._visualization:
cv_result = self._visualize_plt(result, np_image)
image_msg = self._cv_bridge.cv2_to_imgmsg(cv_result, 'bgr8')
vis_pub.publish(image_msg)
rate.sleep()
def _build_result_msg(self, msg, result):
result_msg = Result()
result_msg.header = msg.header
for i, (y1, x1, y2, x2) in enumerate(result['rois']):
box = RegionOfInterest()
box.x_offset = np.asscalar(x1)
box.y_offset = np.asscalar(y1)
box.height = np.asscalar(y2 - y1)
box.width = np.asscalar(x2 - x1)
result_msg.boxes.append(box)
class_id = result['class_ids'][i]
result_msg.class_ids.append(class_id)
class_name = self._class_names[class_id]
result_msg.class_names.append(class_name)
score = result['scores'][i]
result_msg.scores.append(score)
mask = Image()
mask.header = msg.header
mask.height = result['masks'].shape[0]
mask.width = result['masks'].shape[1]
mask.encoding = "mono8"
mask.is_bigendian = False
mask.step = mask.width
mask.data = (result['masks'][:, :, i] * 255).tobytes()
result_msg.masks.append(mask)
return result_msg
def _visualize(self, result, image):
from matplotlib.backends.backend_agg import FigureCanvasAgg
from matplotlib.figure import Figure
fig = Figure()
canvas = FigureCanvasAgg(fig)
axes = fig.gca()
visualize.display_instances(image, result['rois'], result['masks'],
result['class_ids'], CLASS_NAMES,
result['scores'], ax=axes,
class_colors=self._class_colors)
fig.tight_layout()
canvas.draw()
result = np.fromstring(canvas.tostring_rgb(), dtype='uint8')
_, _, w, h = fig.bbox.bounds
result = result.reshape((int(h), int(w), 3))
return result
def _get_fig_ax(self):
"""Return a Matplotlib Axes array to be used in
all visualizations. Provide a
central point to control graph sizes.
Change the default size attribute to control the size
of rendered images
"""
fig, ax = plt.subplots(1)
plt.subplots_adjust(
left=0, bottom=0, right=1, top=1, wspace=0, hspace=0)
return fig, ax
def _visualize_plt(self, result, image):
fig, ax = self._get_fig_ax()
image = visualize.display_instances_plt(
image,
result['rois'],
result['masks'],
result['class_ids'],
CLASS_NAMES,
result['scores'],
fig=fig,
ax=ax)
return image
def _image_callback(self, msg):
rospy.logdebug("Get an image")
if self._msg_lock.acquire(False):
self._last_msg = msg
self._msg_lock.release()
def main():
rospy.init_node('mask_rcnn')
node = MaskRCNNNode()
node.run()
if __name__ == '__main__':
main()
| [] | [] | [
"ROS_HOME",
"HOME"
] | [] | ["ROS_HOME", "HOME"] | python | 2 | 0 | |
lambda_functions/download/features/aws.py | import os
import json
import boto3
from dependencies import yaml
class S3Data(object):
"""
Class for AWS S3
"""
def __init__(self):
"""
Initialize the s3 client.
"""
self.s3 = boto3.client('s3')
self.bucket = os.environ['S3_BUCKET']
def fetch(self, key):
"""
Fetch a S3 object from
:param key: path + filename
:type key: string
:returns: content of the file (json/yaml)
:rtype: dict
"""
try:
obj = self.s3.get_object(
Bucket=self.bucket,
Key=key)
except:
return []
raw_content = obj['Body'].read()
return self.load(raw_content, key)
def load(self, raw_content, key):
"""
Load json or yaml content.
:param raw_content: json/yaml raw_content
:type raw_content: bytes
:param key: path + filename
:type key: string
:returns: content of the file (json/yaml)
:rype: dict
"""
if self.is_json(key):
return json.loads(raw_content)
else:
return yaml.load(raw_content)
def is_json(self, key):
"""
Check if the key has a json/geojson extension.
:param key: path + filename
:type key: string
:returns: True or False
:rtype: boolean
"""
if key.split('.')[-1] in ['json', 'geojson']:
return True
return False
def create(self, key, body):
"""
Create an object in the S3 bucket.
:param key: path + filename
:type key: string
:param body: content of the file
:type body: string
:returns:
"""
self.s3.put_object(
Bucket=self.bucket,
Key=key,
Body=body,
ACL='public-read') | [] | [] | [
"S3_BUCKET"
] | [] | ["S3_BUCKET"] | python | 1 | 0 | |
sdk/keyvault/azure-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/cryptography/CryptographyClientTestBase.java | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.security.keyvault.keys.cryptography;
import com.azure.core.credentials.AccessToken;
import com.azure.core.credentials.TokenCredential;
import com.azure.core.exception.HttpResponseException;
import com.azure.core.http.HttpClient;
import com.azure.core.http.HttpPipeline;
import com.azure.core.http.HttpPipelineBuilder;
import com.azure.core.http.netty.NettyAsyncHttpClientBuilder;
import com.azure.core.http.policy.*;
import com.azure.core.http.policy.HttpPolicyProviders;
import com.azure.core.test.TestBase;
import com.azure.core.util.Configuration;
import com.azure.identity.credential.DefaultAzureCredentialBuilder;
import com.azure.security.keyvault.keys.implementation.AzureKeyVaultConfiguration;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
import reactor.core.publisher.Mono;
import java.math.BigInteger;
import java.security.InvalidAlgorithmParameterException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.NoSuchAlgorithmException;
import java.security.spec.KeySpec;
import java.security.spec.RSAPrivateCrtKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.time.Duration;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.*;
import java.util.function.Consumer;
import java.util.function.Function;
import static org.junit.Assert.*;
public abstract class CryptographyClientTestBase extends TestBase {
@Rule
public TestName testName = new TestName();
@Override
protected String getTestName() {
return testName.getMethodName();
}
void beforeTestSetup() {
}
<T> T clientSetup(Function<HttpPipeline, T> clientBuilder) {
final String endpoint = interceptorManager.isPlaybackMode()
? "http://localhost:8080"
: System.getenv("AZURE_KEYVAULT_ENDPOINT");
TokenCredential credential;
HttpClient httpClient;
String tenantId = System.getenv("AZURE_TENANT_ID");
String clientId = System.getenv("AZURE_CLIENT_ID");
String clientSecret = System.getenv("AZURE_CLIENT_SECRET");
if (!interceptorManager.isPlaybackMode()) {
assertNotNull(tenantId);
assertNotNull(clientId);
assertNotNull(clientSecret);
}
if (interceptorManager.isPlaybackMode()) {
credential = resource -> Mono.just(new AccessToken("Some fake token", OffsetDateTime.now(ZoneOffset.UTC).plus(Duration.ofMinutes(30))));
} else {
credential = new DefaultAzureCredentialBuilder().build();
}
// Closest to API goes first, closest to wire goes last.
final List<HttpPipelinePolicy> policies = new ArrayList<>();
policies.add(new UserAgentPolicy(AzureKeyVaultConfiguration.SDK_NAME, AzureKeyVaultConfiguration.SDK_VERSION, Configuration.getGlobalConfiguration().clone()));
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(new RetryPolicy());
policies.add(new BearerTokenAuthenticationPolicy(credential, CryptographyAsyncClient.KEY_VAULT_SCOPE));
policies.addAll(policies);
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new HttpLoggingPolicy(HttpLogDetailLevel.BODY_AND_HEADERS));
if (interceptorManager.isPlaybackMode()) {
httpClient = interceptorManager.getPlaybackClient();
policies.add(interceptorManager.getRecordPolicy());
} else {
httpClient = new NettyAsyncHttpClientBuilder().wiretap(true).build();
policies.add(interceptorManager.getRecordPolicy());
}
HttpPipeline pipeline = new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
T client;
client = clientBuilder.apply(pipeline);
return Objects.requireNonNull(client);
}
@Test
public abstract void encryptDecryptRsa() throws Exception;
void encryptDecryptRsaRunner(Consumer<KeyPair> testRunner) throws Exception {
final Map<String, String> tags = new HashMap<>();
testRunner.accept(getWellKnownKey());
}
@Test
public abstract void signVerifyEc() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException;
@Test
public abstract void wrapUnwraptRsa() throws Exception;
@Test
public abstract void signVerifyRsa() throws Exception;
@Test
public abstract void wrapUnwrapSymmetricKeyAES128Kw();
@Test
public abstract void wrapUnwrapSymmetricKeyAES192Kw();
@Test
public abstract void wrapUnwrapSymmetricKeyAES256Kw();
@Test
public abstract void encryptDecryptSymmetricKeyAes128CbcHmacSha256();
@Test
public abstract void encryptDecryptSymmetricKeyAes128CbcHmacSha384();
@Test
public abstract void encryptDecryptSymmetricKeyAes128CbcHmacSha512();
@Test
public abstract void encryptDecryptSymmetricKeyaes128CbcOneBlock();
@Test
public abstract void encryptDecryptSymmetricKeyaes128CbcTwoBlock();
private static KeyPair getWellKnownKey() throws Exception {
BigInteger modulus = new BigInteger("27266783713040163753473734334021230592631652450892850648620119914958066181400432364213298181846462385257448168605902438305568194683691563208578540343969522651422088760509452879461613852042845039552547834002168737350264189810815735922734447830725099163869215360401162450008673869707774119785881115044406101346450911054819448375712432746968301739007624952483347278954755460152795801894283389540036131881712321193750961817346255102052653789197325341350920441746054233522546543768770643593655942246891652634114922277138937273034902434321431672058220631825053788262810480543541597284376261438324665363067125951152574540779");
BigInteger publicExponent = new BigInteger("65537");
BigInteger privateExponent = new BigInteger("10466613941269075477152428927796086150095892102279802916937552172064636326433780566497000814207416485739683286961848843255766652023400959086290344987308562817062506476465756840999981989957456897020361717197805192876094362315496459535960304928171129585813477132331538577519084006595335055487028872410579127692209642938724850603554885478763205394868103298473476811627231543504190652483290944218004086457805431824328448422034887148115990501701345535825110962804471270499590234116100216841170344686381902328362376624405803648588830575558058257742073963036264273582756620469659464278207233345784355220317478103481872995809");
BigInteger primeP = new BigInteger("175002941104568842715096339107566771592009112128184231961529953978142750732317724951747797764638217287618769007295505214923187971350518217670604044004381362495186864051394404165602744235299100790551775147322153206730562450301874236875459336154569893255570576967036237661594595803204808064127845257496057219227");
BigInteger primeQ = new BigInteger("155807574095269324897144428622185380283967159190626345335083690114147315509962698765044950001909553861571493035240542031420213144237033208612132704562174772894369053916729901982420535940939821673277140180113593951522522222348910536202664252481405241042414183668723338300649954708432681241621374644926879028977");
BigInteger primeExponentP = new BigInteger("79745606804504995938838168837578376593737280079895233277372027184693457251170125851946171360348440134236338520742068873132216695552312068793428432338173016914968041076503997528137698610601222912385953171485249299873377130717231063522112968474603281996190849604705284061306758152904594168593526874435238915345");
BigInteger primeExponentQ = new BigInteger("80619964983821018303966686284189517841976445905569830731617605558094658227540855971763115484608005874540349730961777634427740786642996065386667564038755340092176159839025706183161615488856833433976243963682074011475658804676349317075370362785860401437192843468423594688700132964854367053490737073471709030801");
BigInteger crtCoefficient = new BigInteger("2157818511040667226980891229484210846757728661751992467240662009652654684725325675037512595031058612950802328971801913498711880111052682274056041470625863586779333188842602381844572406517251106159327934511268610438516820278066686225397795046020275055545005189953702783748235257613991379770525910232674719428");
KeySpec publicKeySpec = new RSAPublicKeySpec(modulus, publicExponent);
KeySpec privateKeySpec = new RSAPrivateCrtKeySpec(modulus, publicExponent, privateExponent, primeP, primeQ, primeExponentP, primeExponentQ, crtCoefficient);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return new KeyPair(keyFactory.generatePublic(publicKeySpec), keyFactory.generatePrivate(privateKeySpec));
}
public String getEndpoint() {
final String endpoint = interceptorManager.isPlaybackMode()
? "http://localhost:8080"
: "https://cameravault.vault.azure.net";
// : System.getenv("AZURE_KEYVAULT_ENDPOINT");
Objects.requireNonNull(endpoint);
return endpoint;
}
static void assertRestException(Runnable exceptionThrower, int expectedStatusCode) {
assertRestException(exceptionThrower, HttpResponseException.class, expectedStatusCode);
}
static void assertRestException(Runnable exceptionThrower, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) {
try {
exceptionThrower.run();
fail();
} catch (Throwable ex) {
assertRestException(ex, expectedExceptionType, expectedStatusCode);
}
}
/**
* Helper method to verify the error was a HttpRequestException and it has a specific HTTP response code.
*
* @param exception Expected error thrown during the test
* @param expectedStatusCode Expected HTTP status code contained in the error response
*/
static void assertRestException(Throwable exception, int expectedStatusCode) {
assertRestException(exception, HttpResponseException.class, expectedStatusCode);
}
static void assertRestException(Throwable exception, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) {
assertEquals(expectedExceptionType, exception.getClass());
assertEquals(expectedStatusCode, ((HttpResponseException) exception).getResponse().getStatusCode());
}
/**
* Helper method to verify that a command throws an IllegalArgumentException.
*
* @param exceptionThrower Command that should throw the exception
*/
static <T> void assertRunnableThrowsException(Runnable exceptionThrower, Class<T> exception) {
try {
exceptionThrower.run();
fail();
} catch (Exception ex) {
assertEquals(exception, ex.getClass());
}
}
public void sleepInRecordMode(long millis) {
if (interceptorManager.isPlaybackMode()) {
return;
}
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
| [
"\"AZURE_KEYVAULT_ENDPOINT\"",
"\"AZURE_TENANT_ID\"",
"\"AZURE_CLIENT_ID\"",
"\"AZURE_CLIENT_SECRET\"",
"\"AZURE_KEYVAULT_ENDPOINT\""
] | [] | [
"AZURE_CLIENT_ID",
"AZURE_CLIENT_SECRET",
"AZURE_TENANT_ID",
"AZURE_KEYVAULT_ENDPOINT"
] | [] | ["AZURE_CLIENT_ID", "AZURE_CLIENT_SECRET", "AZURE_TENANT_ID", "AZURE_KEYVAULT_ENDPOINT"] | java | 4 | 0 | |
test/rlai/utils.py | import os
from typing import Dict
from xvfbwrapper import Xvfb
from rlai.actions import Action
from rlai.policies import Policy
from rlai.policies.tabular import TabularPolicy
from rlai.q_S_A.tabular import TabularStateActionValueEstimator
from rlai.states.mdp import MdpState
from rlai.utils import IncrementalSampleAverager
def tabular_pi_legacy_eq(
pi: Policy,
fixture: Dict[MdpState, Dict[Action, float]]
) -> bool:
pi: TabularPolicy
if len(pi) == len(fixture):
for s in pi:
if len(pi[s]) == len(fixture[s]):
for a in pi[s]:
if pi[s][a] != fixture[s][a]:
return False
else:
return False
else:
return False
return True
def tabular_estimator_legacy_eq(
estimator: TabularStateActionValueEstimator,
fixture: Dict[MdpState, Dict[Action, IncrementalSampleAverager]]
) -> bool:
"""
Our older fixtures use a nested dictionary structure (see the type of "other above) to store state-action value
estimates. The newer approach uses a class-based structure to support function approximation. This function bridges
the two for the purposes of test assertions.
:param estimator: Estimator.
:param fixture: Fixture.
:return: True if equal.
"""
if len(estimator.q_S_A) == len(fixture):
for s in estimator:
if len(estimator.q_S_A[s]) == len(fixture[s]):
for a in estimator.q_S_A[s]:
if estimator.q_S_A[s][a].get_value() != fixture[s][a].get_value():
return False
else:
return False
else:
return False
return True
VIRTUAL_DISPLAY = None
def start_virtual_display_if_headless():
"""
Start a new virtual display if running in headless mode.
"""
global VIRTUAL_DISPLAY
if os.getenv('HEADLESS') == 'True' and VIRTUAL_DISPLAY is None:
VIRTUAL_DISPLAY = Xvfb()
VIRTUAL_DISPLAY.start()
| [] | [] | [
"HEADLESS"
] | [] | ["HEADLESS"] | python | 1 | 0 | |
30 Days of Code/Recursion 3.java | import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
public class Solution {
// Complete the factorial function below.
static int factorial(int n) {
if(n==0)
{
return 1;
}
else
{
return n*factorial(n-1);
}
}
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws IOException {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int n = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
int result = factorial(n);
bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
bufferedWriter.close();
scanner.close();
}
}
| [
"\"OUTPUT_PATH\""
] | [] | [
"OUTPUT_PATH"
] | [] | ["OUTPUT_PATH"] | java | 1 | 0 | |
Backend/open_garden/open_garden/wsgi.py | """
WSGI config for open_garden project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "open_garden.settings")
application = get_wsgi_application()
| [] | [] | [] | [] | [] | python | 0 | 0 | |
cmd/osm-bootstrap/osm-bootstrap.go | // Package main implements the main entrypoint for osm-bootstrap and utility routines to
// bootstrap the various internal components of osm-bootstrap.
// osm-bootstrap provides crd conversion capability in OSM.
package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"os"
"github.com/pkg/errors"
"github.com/spf13/pflag"
admissionv1 "k8s.io/api/admissionregistration/v1"
corev1 "k8s.io/api/core/v1"
clientset "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset"
apiclient "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/typed/apiextensions/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/kubernetes"
clientgoscheme "k8s.io/client-go/kubernetes/scheme"
"k8s.io/client-go/tools/clientcmd"
"github.com/openservicemesh/osm/pkg/apis/config/v1alpha1"
"github.com/openservicemesh/osm/pkg/certificate/providers"
"github.com/openservicemesh/osm/pkg/configurator"
"github.com/openservicemesh/osm/pkg/constants"
"github.com/openservicemesh/osm/pkg/crdconversion"
configClientset "github.com/openservicemesh/osm/pkg/gen/client/config/clientset/versioned"
"github.com/openservicemesh/osm/pkg/httpserver"
httpserverconstants "github.com/openservicemesh/osm/pkg/httpserver/constants"
"github.com/openservicemesh/osm/pkg/k8s/events"
"github.com/openservicemesh/osm/pkg/logger"
"github.com/openservicemesh/osm/pkg/metricsstore"
"github.com/openservicemesh/osm/pkg/reconciler"
"github.com/openservicemesh/osm/pkg/signals"
"github.com/openservicemesh/osm/pkg/version"
)
const (
meshConfigName = "osm-mesh-config"
presetMeshConfigName = "preset-mesh-config"
presetMeshConfigJSONKey = "preset-mesh-config.json"
)
var (
verbosity string
osmNamespace string
caBundleSecretName string
osmMeshConfigName string
meshName string
crdConverterConfig crdconversion.Config
certProviderKind string
tresorOptions providers.TresorOptions
vaultOptions providers.VaultOptions
certManagerOptions providers.CertManagerOptions
enableReconciler bool
scheme = runtime.NewScheme()
)
var (
flags = pflag.NewFlagSet(`osm-bootstrap`, pflag.ExitOnError)
log = logger.New(constants.OSMBootstrapName)
)
func init() {
flags.StringVar(&meshName, "mesh-name", "", "OSM mesh name")
flags.StringVarP(&verbosity, "verbosity", "v", "info", "Set log verbosity level")
flags.StringVar(&osmNamespace, "osm-namespace", "", "Namespace to which OSM belongs to.")
flags.StringVar(&osmMeshConfigName, "osm-config-name", "osm-mesh-config", "Name of the OSM MeshConfig")
// Generic certificate manager/provider options
flags.StringVar(&certProviderKind, "certificate-manager", providers.TresorKind.String(), fmt.Sprintf("Certificate manager, one of [%v]", providers.ValidCertificateProviders))
flags.StringVar(&caBundleSecretName, "ca-bundle-secret-name", "", "Name of the Kubernetes Secret for the OSM CA bundle")
// Vault certificate manager/provider options
flags.StringVar(&vaultOptions.VaultProtocol, "vault-protocol", "http", "Host name of the Hashi Vault")
flags.StringVar(&vaultOptions.VaultHost, "vault-host", "vault.default.svc.cluster.local", "Host name of the Hashi Vault")
flags.StringVar(&vaultOptions.VaultToken, "vault-token", "", "Secret token for the the Hashi Vault")
flags.StringVar(&vaultOptions.VaultRole, "vault-role", "openservicemesh", "Name of the Vault role dedicated to Open Service Mesh")
flags.IntVar(&vaultOptions.VaultPort, "vault-port", 8200, "Port of the Hashi Vault")
// Cert-manager certificate manager/provider options
flags.StringVar(&certManagerOptions.IssuerName, "cert-manager-issuer-name", "osm-ca", "cert-manager issuer name")
flags.StringVar(&certManagerOptions.IssuerKind, "cert-manager-issuer-kind", "Issuer", "cert-manager issuer kind")
flags.StringVar(&certManagerOptions.IssuerGroup, "cert-manager-issuer-group", "cert-manager.io", "cert-manager issuer group")
// Reconciler options
flags.BoolVar(&enableReconciler, "enable-reconciler", false, "Enable reconciler for CDRs, mutating webhook and validating webhook")
_ = clientgoscheme.AddToScheme(scheme)
_ = admissionv1.AddToScheme(scheme)
}
func main() {
log.Info().Msgf("Starting osm-bootstrap %s; %s; %s", version.Version, version.GitCommit, version.BuildDate)
if err := parseFlags(); err != nil {
log.Fatal().Err(err).Msg("Error parsing cmd line arguments")
}
// This ensures CLI parameters (and dependent values) are correct.
if err := validateCLIParams(); err != nil {
events.GenericEventRecorder().FatalEvent(err, events.InvalidCLIParameters, "Error validating CLI parameters")
}
if err := logger.SetLogLevel(verbosity); err != nil {
log.Fatal().Err(err).Msg("Error setting log level")
}
// Initialize kube config and client
kubeConfig, err := clientcmd.BuildConfigFromFlags("", "")
if err != nil {
log.Fatal().Err(err).Msg("Error creating kube configs using in-cluster config")
}
kubeClient := kubernetes.NewForConfigOrDie(kubeConfig)
crdClient := apiclient.NewForConfigOrDie(kubeConfig)
apiServerClient := clientset.NewForConfigOrDie(kubeConfig)
configClient, err := configClientset.NewForConfig(kubeConfig)
if err != nil {
log.Fatal().Err(err).Msgf("Could not access Kubernetes cluster, check kubeconfig.")
return
}
presetMeshConfigMap, presetConfigErr := kubeClient.CoreV1().ConfigMaps(osmNamespace).Get(context.TODO(), presetMeshConfigName, metav1.GetOptions{})
_, meshConfigErr := configClient.ConfigV1alpha1().MeshConfigs(osmNamespace).Get(context.TODO(), meshConfigName, metav1.GetOptions{})
// If the presetMeshConfig could not be loaded and a default meshConfig doesn't exist, return the error
if presetConfigErr != nil && apierrors.IsNotFound(meshConfigErr) {
log.Fatal().Err(err).Msgf("Unable to create default meshConfig, as %s could not be found", presetMeshConfigName)
return
}
// Create a default meshConfig
defaultMeshConfig := createDefaultMeshConfig(presetMeshConfigMap)
if createdMeshConfig, err := configClient.ConfigV1alpha1().MeshConfigs(osmNamespace).Create(context.TODO(), defaultMeshConfig, metav1.CreateOptions{}); err == nil {
log.Info().Msgf("MeshConfig created in %s, %v", osmNamespace, createdMeshConfig)
} else if apierrors.IsAlreadyExists(err) {
log.Info().Msgf("MeshConfig already exists in %s. Skip creating.", osmNamespace)
} else {
log.Fatal().Err(err).Msgf("Error creating default MeshConfig")
}
// Initialize the generic Kubernetes event recorder and associate it with the osm-bootstrap pod resource
bootstrapPod, err := getBootstrapPod(kubeClient)
if err != nil {
log.Fatal().Msg("Error fetching osm-bootstrap pod")
}
eventRecorder := events.GenericEventRecorder()
if err := eventRecorder.Initialize(bootstrapPod, kubeClient, osmNamespace); err != nil {
log.Fatal().Msg("Error initializing generic event recorder")
}
stop := signals.RegisterExitHandlers()
_, cancel := context.WithCancel(context.Background())
defer cancel()
// Start the default metrics store
metricsstore.DefaultMetricsStore.Start(
metricsstore.DefaultMetricsStore.ErrCodeCounter,
)
// Initialize Configurator to retrieve mesh specific config
cfg := configurator.NewConfigurator(configClientset.NewForConfigOrDie(kubeConfig), stop, osmNamespace, osmMeshConfigName)
// Intitialize certificate manager/provider
certProviderConfig := providers.NewCertificateProviderConfig(kubeClient, kubeConfig, cfg, providers.Kind(certProviderKind), osmNamespace,
caBundleSecretName, tresorOptions, vaultOptions, certManagerOptions)
certManager, _, err := certProviderConfig.GetCertificateManager()
if err != nil {
events.GenericEventRecorder().FatalEvent(err, events.InvalidCertificateManager,
"Error initializing certificate manager of kind %s", certProviderKind)
}
// Initialize the crd conversion webhook server to support the conversion of OSM's CRDs
crdConverterConfig.ListenPort = 443
if err := crdconversion.NewConversionWebhook(crdConverterConfig, kubeClient, crdClient, certManager, osmNamespace, enableReconciler, stop); err != nil {
events.GenericEventRecorder().FatalEvent(err, events.InitializationError, "Error creating crd conversion webhook")
}
/*
* Initialize osm-bootstrap's HTTP server
*/
httpServer := httpserver.NewHTTPServer(constants.OSMHTTPServerPort)
// Metrics
httpServer.AddHandler(httpserverconstants.MetricsPath, metricsstore.DefaultMetricsStore.Handler())
// Version
httpServer.AddHandler(httpserverconstants.VersionPath, version.GetVersionHandler())
// Start HTTP server
err = httpServer.Start()
if err != nil {
log.Fatal().Err(err).Msgf("Failed to start OSM metrics/probes HTTP server")
}
if enableReconciler {
log.Info().Msgf("OSM reconciler enabled for custom resource definitions")
err = reconciler.NewReconcilerClient(kubeClient, apiServerClient, meshName, stop, reconciler.CrdInformerKey)
if err != nil {
events.GenericEventRecorder().FatalEvent(err, events.InitializationError, "Error creating reconciler client for custom resource definitions")
}
}
<-stop
log.Info().Msgf("Stopping osm-bootstrap %s; %s; %s", version.Version, version.GitCommit, version.BuildDate)
}
func parseFlags() error {
if err := flags.Parse(os.Args); err != nil {
return err
}
_ = flag.CommandLine.Parse([]string{})
return nil
}
// getBootstrapPod returns the osm-bootstrap pod spec.
// The pod name is inferred from the 'BOOTSTRAP_POD_NAME' env variable which is set during deployment.
func getBootstrapPod(kubeClient kubernetes.Interface) (*corev1.Pod, error) {
podName := os.Getenv("BOOTSTRAP_POD_NAME")
if podName == "" {
return nil, errors.New("BOOTSTRAP_POD_NAME env variable cannot be empty")
}
pod, err := kubeClient.CoreV1().Pods(osmNamespace).Get(context.TODO(), podName, metav1.GetOptions{})
if err != nil {
log.Error().Err(err).Msgf("Error retrieving osm-bootstrap pod %s", podName)
return nil, err
}
return pod, nil
}
// validateCLIParams contains all checks necessary that various permutations of the CLI flags are consistent
func validateCLIParams() error {
if osmNamespace == "" {
return errors.New("Please specify the OSM namespace using --osm-namespace")
}
if caBundleSecretName == "" {
return errors.Errorf("Please specify the CA bundle secret name using --ca-bundle-secret-name")
}
return nil
}
func createDefaultMeshConfig(presetMeshConfigMap *corev1.ConfigMap) *v1alpha1.MeshConfig {
presetMeshConfig := presetMeshConfigMap.Data[presetMeshConfigJSONKey]
presetMeshConfigSpec := v1alpha1.MeshConfigSpec{}
err := json.Unmarshal([]byte(presetMeshConfig), &presetMeshConfigSpec)
if err != nil {
log.Fatal().Err(err).Msgf("Error converting preset-mesh-config json string to meshConfig object")
}
return &v1alpha1.MeshConfig{
TypeMeta: metav1.TypeMeta{
Kind: "MeshConfig",
APIVersion: "config.openservicemesh.io/v1alpha1",
},
ObjectMeta: metav1.ObjectMeta{
Name: meshConfigName,
},
Spec: presetMeshConfigSpec,
}
}
| [
"\"BOOTSTRAP_POD_NAME\""
] | [] | [
"BOOTSTRAP_POD_NAME"
] | [] | ["BOOTSTRAP_POD_NAME"] | go | 1 | 0 | |
cmd/manager/main.go | /*
Copyright 2020 The Kubernetes authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"flag"
"log"
"os"
"strings"
"time"
"github.com/go-logr/zapr"
"go.uber.org/zap"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
clientgoscheme "k8s.io/client-go/kubernetes/scheme"
_ "k8s.io/client-go/plugin/pkg/client/auth/gcp"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/cache"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/healthz"
ctrzap "sigs.k8s.io/controller-runtime/pkg/log/zap"
"sigs.k8s.io/controller-runtime/pkg/predicate"
mdbv1 "github.com/mongodb/mongodb-atlas-kubernetes/pkg/api/v1"
"github.com/mongodb/mongodb-atlas-kubernetes/pkg/controller/atlas"
"github.com/mongodb/mongodb-atlas-kubernetes/pkg/controller/atlascluster"
"github.com/mongodb/mongodb-atlas-kubernetes/pkg/controller/atlasdatabaseuser"
"github.com/mongodb/mongodb-atlas-kubernetes/pkg/controller/atlasproject"
"github.com/mongodb/mongodb-atlas-kubernetes/pkg/controller/connectionsecret"
"github.com/mongodb/mongodb-atlas-kubernetes/pkg/controller/watch"
"github.com/mongodb/mongodb-atlas-kubernetes/pkg/util/kube"
// +kubebuilder:scaffold:imports
)
var (
scheme = runtime.NewScheme()
setupLog = ctrl.Log.WithName("setup")
// Set by the linker during link time.
version = "unknown"
)
func init() {
utilruntime.Must(clientgoscheme.AddToScheme(scheme))
utilruntime.Must(mdbv1.AddToScheme(scheme))
// +kubebuilder:scaffold:scheme
atlas.ProductVersion = version
}
func main() {
// controller-runtime/pkg/log/zap is a wrapper over zap that implements logr
// logr looks quite limited in functionality so we better use Zap directly.
// Though we still need the controller-runtime library and go-logr/zapr as they are used in controller-runtime
// logging
logger := ctrzap.NewRaw(ctrzap.UseDevMode(true), ctrzap.StacktraceLevel(zap.ErrorLevel))
config := parseConfiguration(logger.Sugar())
ctrl.SetLogger(zapr.NewLogger(logger))
logger.Sugar().Infof("MongoDB Atlas Operator version %s", version)
syncPeriod := time.Hour * 3
mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{
Scheme: scheme,
MetricsBindAddress: config.MetricsAddr,
Port: 9443,
Namespace: config.Namespace,
HealthProbeBindAddress: config.ProbeAddr,
LeaderElection: config.EnableLeaderElection,
LeaderElectionID: "06d035fb.mongodb.com",
SyncPeriod: &syncPeriod,
NewCache: cache.BuilderWithOptions(cache.Options{
SelectorsByObject: cache.SelectorsByObject{
&corev1.Secret{}: {
Label: labels.SelectorFromSet(labels.Set{
connectionsecret.TypeLabelKey: connectionsecret.CredLabelVal,
}),
},
},
}),
})
if err != nil {
setupLog.Error(err, "unable to start manager")
os.Exit(1)
}
// globalPredicates should be used for general controller Predicates
// that should be applied to all controllers in order to limit the
// resources they receive events for.
globalPredicates := []predicate.Predicate{
watch.CommonPredicates(), // ignore spurious changes. status changes etc.
watch.SelectNamespacesPredicate(config.WatchedNamespaces), // select only desired namespaces
}
if err = (&atlascluster.AtlasClusterReconciler{
Client: mgr.GetClient(),
Log: logger.Named("controllers").Named("AtlasCluster").Sugar(),
Scheme: mgr.GetScheme(),
AtlasDomain: config.AtlasDomain,
GlobalAPISecret: config.GlobalAPISecret,
GlobalPredicates: globalPredicates,
EventRecorder: mgr.GetEventRecorderFor("AtlasCluster"),
}).SetupWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "AtlasCluster")
os.Exit(1)
}
if err = (&atlasproject.AtlasProjectReconciler{
Client: mgr.GetClient(),
Log: logger.Named("controllers").Named("AtlasProject").Sugar(),
Scheme: mgr.GetScheme(),
AtlasDomain: config.AtlasDomain,
ResourceWatcher: watch.NewResourceWatcher(),
GlobalAPISecret: config.GlobalAPISecret,
GlobalPredicates: globalPredicates,
EventRecorder: mgr.GetEventRecorderFor("AtlasProject"),
}).SetupWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "AtlasProject")
os.Exit(1)
}
if err = (&atlasdatabaseuser.AtlasDatabaseUserReconciler{
Client: mgr.GetClient(),
Log: logger.Named("controllers").Named("AtlasDatabaseUser").Sugar(),
Scheme: mgr.GetScheme(),
AtlasDomain: config.AtlasDomain,
ResourceWatcher: watch.NewResourceWatcher(),
GlobalAPISecret: config.GlobalAPISecret,
GlobalPredicates: globalPredicates,
EventRecorder: mgr.GetEventRecorderFor("AtlasDatabaseUser"),
}).SetupWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "AtlasDatabaseUser")
os.Exit(1)
}
// +kubebuilder:scaffold:builder
if err := mgr.AddHealthzCheck("health", healthz.Ping); err != nil {
setupLog.Error(err, "unable to set up health check")
os.Exit(1)
}
if err := mgr.AddReadyzCheck("check", healthz.Ping); err != nil {
setupLog.Error(err, "unable to set up ready check")
os.Exit(1)
}
setupLog.Info("starting manager")
if err := mgr.Start(ctrl.SetupSignalHandler()); err != nil {
setupLog.Error(err, "problem running manager")
os.Exit(1)
}
}
type Config struct {
AtlasDomain string
EnableLeaderElection bool
MetricsAddr string
Namespace string
WatchedNamespaces map[string]bool
ProbeAddr string
GlobalAPISecret client.ObjectKey
}
// ParseConfiguration fills the 'OperatorConfig' from the flags passed to the program
func parseConfiguration(log *zap.SugaredLogger) Config {
var globalAPISecretName string
config := Config{}
flag.StringVar(&config.AtlasDomain, "atlas-domain", "https://cloud.mongodb.com/", "the Atlas URL domain name (with slash in the end).")
flag.StringVar(&config.MetricsAddr, "metrics-bind-address", ":8080", "The address the metric endpoint binds to.")
flag.StringVar(&config.ProbeAddr, "health-probe-bind-address", ":8081", "The address the probe endpoint binds to.")
flag.StringVar(&globalAPISecretName, "global-api-secret-name", "", "The name of the Secret that contains Atlas API keys. "+
"It is used by the Operator if AtlasProject configuration doesn't contain API key reference. Defaults to <deployment_name>-api-key.")
flag.BoolVar(&config.EnableLeaderElection, "leader-elect", false,
"Enable leader election for controller manager. "+
"Enabling this will ensure there is only one active controller manager.")
flag.Parse()
config.GlobalAPISecret = operatorGlobalKeySecretOrDefault(globalAPISecretName)
// dev note: we pass the watched namespace as the env variable to use the Kubernetes Downward API. Unfortunately
// there is no way to use it for container arguments
watchedNamespace := os.Getenv("WATCH_NAMESPACE")
config.WatchedNamespaces = make(map[string]bool)
for _, namespace := range strings.Split(watchedNamespace, ",") {
namespace = strings.TrimSpace(namespace)
log.Infof("The Operator is watching the namespace %s", namespace)
config.WatchedNamespaces[namespace] = true
}
if len(config.WatchedNamespaces) == 1 {
config.Namespace = watchedNamespace
}
return config
}
func operatorGlobalKeySecretOrDefault(secretNameOverride string) client.ObjectKey {
secretName := secretNameOverride
if secretName == "" {
operatorPodName := os.Getenv("OPERATOR_POD_NAME")
if operatorPodName == "" {
log.Fatal(`"OPERATOR_POD_NAME" environment variable must be set!`)
}
deploymentName, err := kube.ParseDeploymentNameFromPodName(operatorPodName)
if err != nil {
log.Fatalf(`Failed to get Operator Deployment name from "OPERATOR_POD_NAME" environment variable: %s`, err.Error())
}
secretName = deploymentName + "-api-key"
}
operatorNamespace := os.Getenv("OPERATOR_NAMESPACE")
if operatorNamespace == "" {
log.Fatal(`"OPERATOR_NAMESPACE" environment variable must be set!`)
}
return client.ObjectKey{Namespace: operatorNamespace, Name: secretName}
}
| [
"\"WATCH_NAMESPACE\"",
"\"OPERATOR_POD_NAME\"",
"\"OPERATOR_NAMESPACE\""
] | [] | [
"OPERATOR_NAMESPACE",
"WATCH_NAMESPACE",
"OPERATOR_POD_NAME"
] | [] | ["OPERATOR_NAMESPACE", "WATCH_NAMESPACE", "OPERATOR_POD_NAME"] | go | 3 | 0 | |
python/src/disorder_annotators.py | #!/usr/bin/env python
"""
Classes designed to obtain MobiDB-Lite disorder annotations for all proteins in a specified fasta file.
Annotations are either calculated locally (LocalDisorderAnnotator), or retrieved from MobiDB
through the API (APIDisorderAnnotator). The former is written specifically to function in the MobiDB-Lite Docker created
from the image at https://github.com/BioComputingUP/MobiDB-lite_docker.
Author: Max Verbiest
Contact: max.verbiest@zhaw.ch
"""
import subprocess
import os
import json
import urllib.request
import urllib.error
try:
from Bio import SeqIO
except ModuleNotFoundError:
print("WARNING: Could not load Bio.SeqIO -> can only perform local disorder annotations")
__all__ = [
"DisorderAnnotator",
"APIDisorderAnnotator",
"LocalDisorderAnnotator",
]
class DisorderAnnotator(object):
"""Abstract class to outline functionality.
Subclasses implement methods for annotating disorder in protein sequences, extracted from
a specified fasta file.
"""
def __init__(self, fasta, out_file):
"""
Parameters
fasta (str): path to fasta file to extract protein sequences from
out_file (str): path where output file will be created (directory structure must exist already)
"""
self.fasta = fasta
self.out_file = self.check_output_dir(out_file)
def check_output_dir(self, out_file):
"""Check whether the directory where the output file will be generated exists. If not -> FileNotFoundError"""
out_dir = os.path.join(*out_file.split("/")[:-1])
if not os.path.isdir(out_dir):
raise FileNotFoundError("Directory for output file does not exist")
return out_file
def get_disorder_annotations(self):
"""Implemented in child classes"""
pass
class APIDisorderAnnotator(DisorderAnnotator):
"""
Class to query MobiDB for all proteins in a specified fasta file. Protein identifiers must be in standard
UniProt/ SwissProt format. Protein IDs are queried to MobiDB and predicted disordered regions (from MobiDB-Lite)
are extracted and written to an output file.
For information on MobiDB API, see:
https://mobidb.bio.unipd.it/help/apidoc
and
https://mobidb.bio.unipd.it/about/mobidb
"""
def __init__(self, fasta, out_file, curated=False):
"""
Parameters
curated (bool): (Not implemented!) Should curated information from
MobiDB be incorporated in output? (default:False)
"""
super().__init__(fasta, out_file)
self.fasta = SeqIO.parse(fasta, "fasta")
self.base_url = "https://mobidb.bio.unipd.it/api/download?acc={}{}&format=json"
self.filter = "&projection=prediction-disorder-mobidb_lite"
if curated:
# self.filter += ",curated-disorder-priority"
raise NotImplementedError("Handling of curated MobiDB annotations is not yet supported")
def query_mobidb(self, prot_id):
"""Construct url for current protein id and filter, query MobiDB
Parameters
prot_id (str): UniProt identifier of protein of interest
Returns
disorder_dict (dict):
Dictionary containing all information available for protein entry in MobiDB after filter.
If only part of this information is of interest, it can be extracted from the dictionary later
"""
prot_url = self.base_url.format(prot_id, self.filter)
with urllib.request.urlopen(prot_url) as response:
disorder = response.read().decode("utf-8")
disorder_dict = json.loads(disorder)
return disorder_dict
def get_disorder_annotations(self):
""" Retrieve MobiDB-Lite annotations through MobiDB web API.
Implements method DisorderAnnotator.get_disorder_annotations(). Output is generated to mimic MobiDB-Lite output
when run with the '-f interpro' and '-sf' options, and is written to an output file.
"""
with open(self.out_file, "w") as o:
for record in self.fasta:
prot_id = record.id.split("|")[1]
print("Started work on sequence '{}'...".format(prot_id))
try:
disorder_dict = self.query_mobidb(prot_id)
except urllib.error.URLError:
print("{} was not found in MobiDB".format(prot_id))
continue
try:
disorder_regions = [(i[0], i[1]) for i in
disorder_dict["prediction-disorder-mobidb_lite"]["regions"]]
except KeyError:
print("No disorder predicted".format(prot_id))
continue
print("Predicted disordered regions: {}".format(disorder_regions))
for coords in disorder_regions:
o.write("{}\t{}\t{}\n".format(record.id, coords[0], coords[1]))
class LocalDisorderAnnotator(DisorderAnnotator):
"""
Class to run MobiDB-lite disorder annotations locally. Will only work using the docker image provided
on https://github.com/BioComputingUP/MobiDB-lite_docker
"""
def __init__(self, fasta, out_file, out_format="interpro", silence_sf=True):
"""
Parameters
out_format (str): Output format, define output detail (MobiDB-lite gitbub for details). Accepted values
are: "interpro (default)", "fasta", "caid", "mobidb4"
silence_sf (bool): If True (default), sequence features (e.g. polar, polyampholyte) will be silenced in output
"""
super().__init__(fasta, out_file)
# path to mobidb-lite in the docker
self.out_format = self.check_out_format(out_format)
self.silence_sf = silence_sf
self.mobidb_path = "/usr/src/mobidb/mobidb_lite.py"
def check_out_format(self, format):
"""Check whether the specified output format is supported by MobiDB-lite"""
if not format in {"interpro", "fasta", "caid", "mobidb4"}:
raise ValueError("Please pick one of the following output formats: interpro, fasta, caid, mobidb4")
return format
def run_mobidb(self, threads=1, env=os.environ.copy()):
"""Run MobiDB-Lite script, method taken from:
https://github.com/BioComputingUP/MobiDB-lite_docker/blob/master/test.ipynb
Parameters:
threads (int): Number of threads involved in disordered regions computation range between 1(default) and 7
env (dict): Environmental variables (e.g. python path) which must be set in order
to correctly run MobiDB Lite script
"""
# Call subprocess
return subprocess.run(
check=True, # Check command execution
encoding='utf-8', # Set stdout/stderr encoding
env=env, # Set environmental variables
stdout=subprocess.PIPE, # Capture stdout
stderr=subprocess.PIPE, # Capture stderr
# Command line arguments
args=[
# Run script with Python 3
'python3', self.mobidb_path,
# Set output file format
'-f', '{:s}'.format(self.out_format),
# Set output file
'-o', '{:s}'.format(self.out_file),
# Set number of threads, if any
*(['-t', '{:d}'.format(threads)] if threads else []),
# Silence sequence features, if desired
*(['{:s}'.format("-sf")] if self.silence_sf else []),
# Set input file path
'{:s}'.format(self.fasta)
]
)
def get_disorder_annotations(self, threads=1):
"""Run MobiDB-Lite locally and report output/ errors
Implements method DisorderAnnotator.get_disorder_annotations() Annotations are written to output file.
Parameters
threads (int): How many threads MobiDB-Lite should use: range between 1(default) and 7
"""
try:
# Run MobiDB Lite
ran = self.run_mobidb(threads)
print('MobiDB Lite succesfully completed')
# If annotations were not written to file: retrieve stdout and stderr
if ran.stdout:
print('stdout:')
print(ran.stdout)
if ran.stderr:
print('stderr:')
print(ran.stderr)
print()
except subprocess.CalledProcessError as err:
# Show error
print('MobiDB Lite exited with code', err.returncode)
print('command:')
print(err.cmd)
print('stdout:')
print(err.stdout)
print('stderr:')
print(err.stderr)
print()
| [] | [] | [] | [] | [] | python | 0 | 0 | |
Source/Controller/controller.go | package main
import (
"github.com/rs/cors"
"log"
"net/http"
)
func main() {
log.Println("Starting DConsole Controller")
//runtime.GOMAXPROCS(2)
router := createRouter()
handler := cors.Default().Handler(router)
//log.Fatal(http.ListenAndServe(":"+os.Getenv("PORT"), handler))
srv := &http.Server{
Handler: handler,
Addr: "127.0.0.1:8080",
// Good practice: enforce timeouts for servers you create!
}
log.Fatal(srv.ListenAndServe())
}
| [
"\"PORT\""
] | [] | [
"PORT"
] | [] | ["PORT"] | go | 1 | 0 | |
main.go | package main
import (
"fmt"
"github.com/line/line-bot-sdk-go/linebot"
"log"
"math/rand"
"net/http"
"os"
"strconv"
"strings"
"time"
)
const (
imageURL = "https://avatars1.githubusercontent.com/u/6083986"
)
type config struct {
HostPort string `default:":8080"`
IsDebug bool `env:"DEBUG"`
Secret string `default:"xx"`
Token string `default:"xx"`
Tipshost string `default:"https://bowwow.tips"`
Timeout time.Duration
}
func random(min, mac int) int {
rand.Seed(time.Now().Unix())
return rand.Intn(mac-min) + min
}
func main() {
cfg := new(config)
err := env.Fill(cfg)
cfg.Secret = os.Getenv("LineSecret")
cfg.Token = os.Getenv("LineToken")
fmt.Println("Port:", cfg.HostPort)
fmt.Println("Secret:", cfg.Secret)
fmt.Println("Token:", cfg.Token)
fmt.Println("Tipshost:", cfg.Tipshost)
cl, err := linebot.New(
cfg.Secret,
cfg.Token,
)
if err != nil {
log.Fatal(err)
}
template := linebot.NewCarouselTemplate(
linebot.NewCarouselColumn(
imageURL, "bowwow.tips", "bowwow lin",
linebot.NewURIAction("bowwow", cfg.Tipshost),
),
)
http.HandleFunc("/callback", func(w http.ResponseWriter, req *http.Request) {
res, err := cl.ParseRequest(req)
if err != nil {
log.Fatal(err)
}
for _, re := range res {
if re.Type == linebot.EventTypeJoin {
cl.ReplyMessage(re.ReplyToken, linebot.NewTextMessage("早上好!\n 請打「help」")).Do()
}
if re.Type == linebot.EventTypeFollow {
n := time.Now()
NowT := timeutil.Strftime(&n, "%Y年%m月%d日%H時%M分%S秒")
p, _ := cl.GetProfile(re.Source.UserID).Do()
cl.ReplyMessage(re.ReplyToken, linebot.NewTextMessage("謝謝你!\n"+p.DisplayName+"呃\n\n"+NowT)).Do()
log.Println("DisplayName:" + p.DisplayName)
}
if re.Type == linebot.EventTypeMessage {
switch msg := re.Message.(type) {
case *linebot.TextMessage:
if msg.Text == "test" {
cl.ReplyMessage(re.ReplyToken, linebot.NewTextMessage("success")).Do()
} else if msg.Text == "groupid" {
cl.ReplyMessage(re.ReplyToken, linebot.NewTextMessage(string(re.Source.GroupID))).Do()
} else if msg.Text == "byebye" {
cl.ReplyMessage(re.ReplyToken, linebot.NewStickerMessage("3", "187")).Do()
_, err := cl.LeaveGroup(re.Source.GroupID).Do()
if err != nil {
cl.LeaveRoom(re.Source.RoomID).Do()
}
} else if msg.Text == "help" {
cl.ReplyMessage(re.ReplyToken, linebot.NewTextMessage("help\n・[image:画像url]=從圖片網址發送圖片\n・[speed]=測回話速度\n・[groupid]=發送GroupID\n・[roomid]=發送RoomID\n・[byebye]=取消訂閱\n・[about]=作者\n・[me]=發送發件人信息\n・[test]=test bowwow是否正常\n・[now]=現在時間\n・[mid]=mid\n・[sticker]=隨機圖片\n\n[其他機能]\n位置測試\n捉貼圖ID\n加入時發送消息")).Do()
} else if msg.Text == "check" {
fmt.Println(msg)
} else if msg.Text == "now" {
n := time.Now()
NowT := timeutil.Strftime(&n, "%Y年%m月%d日%H時%M分%S秒")
cl.ReplyMessage(re.ReplyToken, linebot.NewTextMessage(NowT)).Do()
} else if msg.Text == "mid" {
cl.ReplyMessage(re.ReplyToken, linebot.NewTextMessage(re.Source.UserID)).Do()
} else if msg.Text == "roomid" {
cl.ReplyMessage(re.ReplyToken, linebot.NewTextMessage(re.Source.RoomID)).Do()
} else if msg.Text == "hidden" {
cl.ReplyMessage(re.ReplyToken, linebot.NewTextMessage("hidden")).Do()
} else if msg.Text == "bowwow" {
_, err := cl.ReplyMessage(re.ReplyToken, linebot.NewImageMessage(imageURL, imageURL)).Do()
if err != nil {
log.Fatal(err)
}
} else if msg.Text == "sticker" {
stid := random(180, 259)
stidx := strconv.Itoa(stid)
_, err := cl.ReplyMessage(re.ReplyToken, linebot.NewStickerMessage("3", stidx)).Do()
if err != nil {
log.Fatal(err)
}
} else if msg.Text == "me" {
mid := re.Source.UserID
p, err := cl.GetProfile(mid).Do()
if err != nil {
cl.ReplyMessage(re.ReplyToken, linebot.NewTextMessage("新增同意"))
}
cl.ReplyMessage(re.ReplyToken, linebot.NewTextMessage("mid:"+mid+"\nname:"+p.DisplayName+"\nstatusMessage:"+p.StatusMessage)).Do()
} else if msg.Text == "speed" {
replytoken := re.ReplyToken
start := time.Now()
cl.ReplyMessage(replytoken, linebot.NewTextMessage("..")).Do()
end := time.Now()
result := fmt.Sprintf("%f [sec]", (end.Sub(start)).Seconds())
_, err := cl.PushMessage(re.Source.GroupID, linebot.NewTextMessage(result)).Do()
if err != nil {
_, err := cl.PushMessage(re.Source.RoomID, linebot.NewTextMessage(result)).Do()
if err != nil {
_, err := cl.PushMessage(re.Source.UserID, linebot.NewTextMessage(result)).Do()
if err != nil {
log.Fatal(err)
}
}
}
} else if res := strings.Contains(msg.Text, "hello"); res == true {
cl.ReplyMessage(re.ReplyToken, linebot.NewTextMessage("hello!"), linebot.NewTextMessage("my name is bowwow")).Do()
} else if res := strings.Contains(msg.Text, "image:"); res == true {
image_url := strings.Replace(msg.Text, "image:", "", -1)
cl.ReplyMessage(re.ReplyToken, linebot.NewImageMessage(image_url, image_url)).Do()
} else if msg.Text == "about" {
_, err := cl.ReplyMessage(re.ReplyToken, linebot.NewTemplateMessage("hi", template)).Do()
if err != nil {
log.Println(err)
}
}
case *linebot.StickerMessage:
cl.ReplyMessage(re.ReplyToken, linebot.NewTextMessage("StickerId:"+msg.StickerID+"\nPackageId:"+msg.PackageID)).Do()
case *linebot.LocationMessage:
cl.ReplyMessage(re.ReplyToken, linebot.NewLocationMessage(
msg.Title,
msg.Address,
msg.Latitude,
msg.Longitude)).Do()
}
}
}
})
if err := http.ListenAndServe(cfg.HostPort, nil); err != nil {
log.Fatal(err)
}
}
| [
"\"LineSecret\"",
"\"LineToken\""
] | [] | [
"LineToken",
"LineSecret"
] | [] | ["LineToken", "LineSecret"] | go | 2 | 0 | |
pkg/cmd/sctool/root.go | // Copyright (C) 2017 ScyllaDB
package main
import (
"crypto/tls"
"net/http"
"os"
"github.com/pkg/errors"
"github.com/scylladb/scylla-manager/pkg"
"github.com/scylladb/scylla-manager/pkg/command/flag"
"github.com/scylladb/scylla-manager/pkg/managerclient"
"github.com/scylladb/scylla-manager/pkg/util/cfgutil"
"github.com/spf13/cobra"
)
type rootCommand struct {
cobra.Command
client *managerclient.Client
apiURL string
apiCertFile string
apiKeyFile string
}
func newRootCommand(client *managerclient.Client) *cobra.Command {
cmd := &rootCommand{
Command: cobra.Command{
Use: "sctool",
Short: "Scylla Manager " + pkg.Version(),
Long: "Scylla Manager " + pkg.Version() + ".\n\nDocumentation is available online at https://manager.docs.scylladb.com/.",
},
client: client,
}
cmd.init()
cmd.PersistentPreRunE = func(_ *cobra.Command, args []string) error {
return cmd.preRun()
}
return &cmd.Command
}
func (cmd *rootCommand) init() {
w := flag.Wrap(cmd.PersistentFlags())
w.GlobalAPIURL(&cmd.apiURL, apiURL())
w.GlobalAPICertFile(&cmd.apiCertFile)
w.GlobalAPIKeyFile(&cmd.apiKeyFile)
}
func (cmd *rootCommand) preRun() error {
if cmd.IsAdditionalHelpTopicCommand() {
return nil
}
if cmd.apiCertFile != "" && cmd.apiKeyFile == "" {
return errors.New("missing --api-key-file flag")
}
if cmd.apiKeyFile != "" && cmd.apiCertFile == "" {
return errors.New("missing --api-cert-file flag")
}
var opts []managerclient.Option
if cmd.apiCertFile != "" {
cert, err := tls.LoadX509KeyPair(cmd.apiCertFile, cmd.apiKeyFile)
if err != nil {
return errors.Wrap(err, "load client certificate")
}
opts = append(opts, func(c *http.Client) {
t := c.Transport.(*http.Transport)
t.TLSClientConfig.Certificates = []tls.Certificate{cert}
})
}
c, err := managerclient.NewClient(cmd.apiURL, opts...)
if err != nil {
return err
}
*cmd.client = c
return nil
}
func apiURL() string {
if v := os.Getenv("SCYLLA_MANAGER_API_URL"); v != "" {
return v
}
c := &struct {
HTTP string `yaml:"http"`
HTTPS string `yaml:"https"`
}{}
if err := cfgutil.PermissiveParseYAML(&c, "/etc/scylla-manager/scylla-manager.yaml"); err == nil {
if v := baseURL(c.HTTP, c.HTTPS); v != "" {
return v
}
}
return "http://127.0.0.1:5080/api/v1"
}
| [
"\"SCYLLA_MANAGER_API_URL\""
] | [] | [
"SCYLLA_MANAGER_API_URL"
] | [] | ["SCYLLA_MANAGER_API_URL"] | go | 1 | 0 | |
models/search_test.go | package models
import (
"database/sql"
"log"
"os"
"testing"
_ "github.com/lib/pq"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/suite"
)
type SearchSuite struct {
suite.Suite
db *sql.DB
accDB AccountDB
txnDB TransactionDB
}
func (ss *SearchSuite) SetupSuite() {
t := ss.T()
databaseURL := os.Getenv("TEST_DATABASE_URL")
assert.NotEmpty(t, databaseURL)
db, err := sql.Open("postgres", databaseURL)
if err != nil {
log.Panic("Unable to connect to Database:", err)
} else {
log.Println("Successfully established connection to database.")
ss.db = db
}
log.Println("Successfully established connection to database.")
ss.accDB = NewAccountDB(db)
ss.txnDB = NewTransactionDB(db)
// Create test accounts
acc1 := &Account{
ID: "acc1",
Data: map[string]interface{}{
"customer_id": "C1",
"status": "active",
"created": "2017-01-01",
},
}
err = ss.accDB.CreateAccount(acc1)
assert.Equal(t, nil, err, "Error creating test account")
acc2 := &Account{
ID: "acc2",
Data: map[string]interface{}{
"customer_id": "C2",
"status": "inactive",
"created": "2017-06-30",
},
}
err = ss.accDB.CreateAccount(acc2)
assert.Equal(t, nil, err, "Error creating test account")
// Create test transactions
txn1 := &Transaction{
ID: "txn1",
Lines: []*TransactionLine{
&TransactionLine{
AccountID: "acc1",
Delta: 1000,
},
&TransactionLine{
AccountID: "acc2",
Delta: -1000,
},
},
Data: map[string]interface{}{
"action": "setcredit",
"expiry": "2018-01-01",
"months": []string{"jan", "feb", "mar"},
},
}
ok := ss.txnDB.Transact(txn1)
assert.Equal(t, true, ok, "Error creating test transaction")
txn2 := &Transaction{
ID: "txn2",
Lines: []*TransactionLine{
&TransactionLine{
AccountID: "acc1",
Delta: 100,
},
&TransactionLine{
AccountID: "acc2",
Delta: -100,
},
},
Data: map[string]interface{}{
"action": "setcredit",
"expiry": "2018-01-15",
"months": []string{"apr", "may", "jun"},
},
}
ok = ss.txnDB.Transact(txn2)
assert.Equal(t, true, ok, "Error creating test transaction")
txn3 := &Transaction{
ID: "txn3",
Lines: []*TransactionLine{
&TransactionLine{
AccountID: "acc1",
Delta: 400,
},
&TransactionLine{
AccountID: "acc2",
Delta: -400,
},
},
Data: map[string]interface{}{
"action": "setcredit",
"expiry": "2018-01-30",
"months": []string{"jul", "aug", "sep"},
},
}
ok = ss.txnDB.Transact(txn3)
assert.Equal(t, true, ok, "Error creating test transaction")
}
func (ss *SearchSuite) TestSearchAccountsWithBothMustAndShould() {
t := ss.T()
engine, _ := NewSearchEngine(ss.db, "accounts")
query := `{
"query": {
"must": {
"fields": [
{"id": {"eq": "acc1"}}
],
"terms": [
{"status": "active"}
]
},
"should": {
"terms": [
{"customer_id": "C1"}
],
"ranges": [
{"created": {"gte": "2018-01-01", "lte": "2018-01-30"}}
]
}
}
}`
results, err := engine.Query(query)
assert.Equal(t, nil, err, "Error in building search query")
accounts, _ := results.([]*AccountResult)
assert.Equal(t, 1, len(accounts), "Account count doesn't match")
assert.Equal(t, "acc1", accounts[0].ID, "Account ID doesn't match")
}
func (ss *SearchSuite) TestSearchTransactionsWithBothMustAndShould() {
t := ss.T()
engine, _ := NewSearchEngine(ss.db, "transactions")
query := `{
"query": {
"must": {
"fields": [
{"id": {"eq": "txn1"}}
],
"terms": [
{"action": "setcredit"}
]
},
"should": {
"terms": [
{"months": ["jan", "feb", "mar"]},
{"months": ["apr", "may", "jun"]},
{"months": ["jul", "aug", "sep"]}
],
"ranges": [
{"expiry": {"gte": "2018-01-01", "lte": "2018-01-30"}}
]
}
}
}`
results, err := engine.Query(query)
assert.Equal(t, nil, err, "Error in building search query")
transactions, _ := results.([]*TransactionResult)
assert.Equal(t, 1, len(transactions), "Transaction count doesn't match")
assert.Equal(t, "txn1", transactions[0].ID, "Transaction ID doesn't match")
}
func (ss *SearchSuite) TearDownSuite() {
log.Println("Cleaning up the test database")
t := ss.T()
_, err := ss.db.Exec(`DELETE FROM lines`)
if err != nil {
t.Fatal("Error deleting lines:", err)
}
_, err = ss.db.Exec(`DELETE FROM transactions`)
if err != nil {
t.Fatal("Error deleting transactions:", err)
}
_, err = ss.db.Exec(`DELETE FROM accounts`)
if err != nil {
t.Fatal("Error deleting accounts:", err)
}
}
func TestSearchSuite(t *testing.T) {
suite.Run(t, new(SearchSuite))
}
| [
"\"TEST_DATABASE_URL\""
] | [] | [
"TEST_DATABASE_URL"
] | [] | ["TEST_DATABASE_URL"] | go | 1 | 0 | |
pulsar-io/elastic-search/src/test/java/org/apache/pulsar/io/elasticsearch/ElasticSearchSinkTests.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.pulsar.io.elasticsearch;
import org.apache.pulsar.client.api.PulsarClientException;
import org.apache.pulsar.client.api.Schema;
import org.apache.pulsar.client.api.schema.GenericObject;
import org.apache.pulsar.client.api.schema.GenericRecord;
import org.apache.pulsar.client.api.schema.GenericSchema;
import org.apache.pulsar.common.schema.KeyValue;
import org.apache.pulsar.common.schema.KeyValueEncodingType;
import org.apache.pulsar.common.schema.SchemaType;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.testng.Assert.assertEquals;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.apache.pulsar.functions.api.Record;
import org.apache.pulsar.io.core.SinkContext;
import org.apache.pulsar.io.elasticsearch.data.UserProfile;
import org.mockito.Mock;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.opensearch.client.Node;
import org.opensearch.client.RestHighLevelClient;
import org.testcontainers.elasticsearch.ElasticsearchContainer;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.Locale;
import static org.testng.Assert.assertNull;
public class ElasticSearchSinkTests {
public static final String ELASTICSEARCH_IMAGE = Optional.ofNullable(System.getenv("ELASTICSEARCH_IMAGE"))
.orElse("docker.elastic.co/elasticsearch/elasticsearch:7.16.3-amd64");
private static ElasticsearchContainer container;
@Mock
protected Record<GenericObject> mockRecord;
@Mock
protected SinkContext mockSinkContext;
protected Map<String, Object> map;
protected ElasticSearchSink sink;
static Schema kvSchema;
static Schema<UserProfile> valueSchema;
static GenericSchema<GenericRecord> genericSchema;
static GenericRecord userProfile;
@BeforeClass
public static final void initBeforeClass() {
container = new ElasticsearchContainer(ELASTICSEARCH_IMAGE);
valueSchema = Schema.JSON(UserProfile.class);
genericSchema = Schema.generic(valueSchema.getSchemaInfo());
userProfile = genericSchema.newRecordBuilder()
.set("name", "bob")
.set("userName", "boby")
.set("email", "bob@bob.com")
.build();
kvSchema = Schema.KeyValue(Schema.STRING, genericSchema, KeyValueEncodingType.SEPARATED);
}
@AfterClass
public static void closeAfterClass() {
container.close();
}
@SuppressWarnings("unchecked")
@BeforeMethod
public final void setUp() throws Exception {
container.start();
map = new HashMap<String, Object> ();
map.put("elasticSearchUrl", "http://"+container.getHttpHostAddress());
map.put("schemaEnable", "true");
map.put("createIndexIfNeeded", "true");
sink = new ElasticSearchSink();
mockRecord = mock(Record.class);
mockSinkContext = mock(SinkContext.class);
when(mockRecord.getKey()).thenAnswer(new Answer<Optional<String>>() {
long sequenceCounter = 0;
public Optional<String> answer(InvocationOnMock invocation) throws Throwable {
return Optional.of( "key-" + sequenceCounter++);
}});
when(mockRecord.getValue()).thenAnswer(new Answer<GenericObject>() {
public GenericObject answer(InvocationOnMock invocation) throws Throwable {
return new GenericObject() {
@Override
public SchemaType getSchemaType() {
return SchemaType.KEY_VALUE;
}
@Override
public Object getNativeObject() {
return new KeyValue<String, GenericObject>((String) userProfile.getField("name"), userProfile);
}
};
}});
when(mockRecord.getSchema()).thenAnswer(new Answer<Schema<KeyValue<String,UserProfile>>>() {
public Schema<KeyValue<String,UserProfile>> answer(InvocationOnMock invocation) throws Throwable {
return kvSchema;
}});
}
@AfterMethod(alwaysRun = true)
public final void tearDown() throws Exception {
if (sink != null) {
sink.close();
}
}
@Test
public final void multiNodesClientTest() throws Exception {
map.put("indexName", "myindex");
map.put("typeName", "doc");
map.put("username", "racerX");
map.put("password", "go-speedie-go");
map.put("elasticSearchUrl", "http://node1:90902,https://node2:90902,http://node3:90902");
sink.open(map, mockSinkContext);
RestHighLevelClient client = sink.getElasticsearchClient().getClient();
List<Node> nodeList = client.getLowLevelClient().getNodes();
assertEquals(nodeList.size(), 3);
}
@Test(expectedExceptions = IllegalArgumentException.class)
public final void invalidIndexNameTest() throws Exception {
map.put("indexName", "myIndex");
map.put("createIndexIfNeeded", "true");
sink.open(map, mockSinkContext);
}
@Test
public final void createIndexTest() throws Exception {
map.put("indexName", "test-index");
sink.open(map, mockSinkContext);
send(1);
}
@Test
public final void singleRecordTest() throws Exception {
map.put("indexName", "test-index");
sink.open(map, mockSinkContext);
send(1);
verify(mockRecord, times(1)).ack();
}
@Test
public final void send100Test() throws Exception {
map.put("indexName", "test-index");
sink.open(map, mockSinkContext);
send(100);
verify(mockRecord, times(100)).ack();
}
@Test
public final void sendKeyIgnoreSingleField() throws Exception {
final String index = "testkeyignore";
map.put("indexName", index);
map.put("keyIgnore", "true");
map.put("primaryFields", "name");
sink.open(map, mockSinkContext);
send(1);
verify(mockRecord, times(1)).ack();
assertEquals(sink.getElasticsearchClient().totalHits(index), 1L);
assertEquals(sink.getElasticsearchClient().search(index).getHits().getHits()[0].getId(), "bob");
}
@Test
public final void sendKeyIgnoreMultipleFields() throws Exception {
final String index = "testkeyignore2";
map.put("indexName", index);
map.put("keyIgnore", "true");
map.put("primaryFields", "name,userName");
sink.open(map, mockSinkContext);
send(1);
verify(mockRecord, times(1)).ack();
assertEquals(sink.getElasticsearchClient().totalHits(index), 1L);
assertEquals(sink.getElasticsearchClient().search(index).getHits().getHits()[0].getId(), "[\"bob\",\"boby\"]");
}
protected final void send(int numRecords) throws Exception {
for (int idx = 0; idx < numRecords; idx++) {
sink.write(mockRecord);
}
}
static class MockRecordNullValue implements Record<GenericObject> {
@Override
public Schema getSchema() {
return kvSchema;
}
@Override
public Optional<String> getKey() {
return Optional.of((String)userProfile.getField("name"));
}
@Override
public GenericObject getValue() {
return new GenericObject() {
@Override
public SchemaType getSchemaType() {
return SchemaType.KEY_VALUE;
}
@Override
public Object getNativeObject() {
return new KeyValue<>((String)userProfile.getField("name"), null);
}
};
}
}
@Test
public void testStripNullNodes() throws Exception {
map.put("stripNulls", true);
sink.open(map, mockSinkContext);
GenericRecord genericRecord = genericSchema.newRecordBuilder()
.set("name", null)
.set("userName", "boby")
.set("email", null)
.build();
String json = sink.stringifyValue(valueSchema, genericRecord);
assertEquals(json, "{\"userName\":\"boby\"}");
}
@Test
public void testKeepNullNodes() throws Exception {
map.put("stripNulls", false);
sink.open(map, mockSinkContext);
GenericRecord genericRecord = genericSchema.newRecordBuilder()
.set("name", null)
.set("userName", "boby")
.set("email", null)
.build();
String json = sink.stringifyValue(valueSchema, genericRecord);
assertEquals(json, "{\"name\":null,\"userName\":\"boby\",\"email\":null}");
}
@Test(expectedExceptions = PulsarClientException.InvalidMessageException.class)
public void testNullValueFailure() throws Exception {
String index = "testnullvaluefail";
map.put("indexName", index);
map.put("keyIgnore", "false");
map.put("nullValueAction", "FAIL");
sink.open(map, mockSinkContext);
MockRecordNullValue mockRecordNullValue = new MockRecordNullValue();
sink.write(mockRecordNullValue);
}
@Test
public void testNullValueIgnore() throws Exception {
testNullValue(ElasticSearchConfig.NullValueAction.IGNORE);
}
@Test
public void testNullValueDelete() throws Exception {
testNullValue(ElasticSearchConfig.NullValueAction.DELETE);
}
private void testNullValue(ElasticSearchConfig.NullValueAction action) throws Exception {
String index = "testnullvalue" + action.toString().toLowerCase(Locale.ROOT);
map.put("indexName", index);
map.put("keyIgnore", "false");
map.put("nullValueAction", action.name());
sink.open(map, mockSinkContext);
send(1);
verify(mockRecord, times(1)).ack();
sink.write(new Record<GenericObject>() {
@Override
public Schema<GenericObject> getSchema() {
return kvSchema;
}
@Override
public Optional<String> getKey() {
return Optional.of((String)userProfile.getField("name"));
}
@Override
public GenericObject getValue() {
return new GenericObject() {
@Override
public SchemaType getSchemaType() {
return SchemaType.KEY_VALUE;
}
@Override
public Object getNativeObject() {
return new KeyValue<String, GenericRecord>((String)userProfile.getField("name"), userProfile);
}
};
}
});
assertEquals(sink.getElasticsearchClient().totalHits(index), 1L);
sink.write(new MockRecordNullValue());
assertEquals(sink.getElasticsearchClient().totalHits(index), action.equals(ElasticSearchConfig.NullValueAction.DELETE) ? 0L : 1L);
assertNull(sink.getElasticsearchClient().irrecoverableError.get());
}
}
| [
"\"ELASTICSEARCH_IMAGE\""
] | [] | [
"ELASTICSEARCH_IMAGE"
] | [] | ["ELASTICSEARCH_IMAGE"] | java | 1 | 0 | |
go-apps/meep-virt-engine/server/virt-engine.go | /*
* Copyright (c) 2019 InterDigital Communications, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package server
import (
"encoding/json"
"os"
"strings"
"github.com/InterDigitalInc/AdvantEDGE/go-apps/meep-virt-engine/helm"
model "github.com/InterDigitalInc/AdvantEDGE/go-packages/meep-ctrl-engine-model"
log "github.com/InterDigitalInc/AdvantEDGE/go-packages/meep-logger"
redis "github.com/InterDigitalInc/AdvantEDGE/go-packages/meep-redis"
watchdog "github.com/InterDigitalInc/AdvantEDGE/go-packages/meep-watchdog"
)
const moduleCtrlEngine string = "ctrl-engine"
const typeActive string = "active"
const channelCtrlActive string = moduleCtrlEngine + "-" + typeActive
var activeScenarioName string = ""
var watchdogClient *watchdog.Pingee
var rc *redis.Connector
const activeScenarioEventKey string = moduleCtrlEngine + ":" + typeActive
const redisAddr string = "localhost:30379"
// VirtEngineInit - Initialize virtualization engine
func VirtEngineInit() (err error) {
log.Debug("Initializing MEEP Virtualization Engine")
// Connect to Redis DB
rc, err = redis.NewConnector(redisAddr, 0)
if err != nil {
log.Error("Failed connection to Redis DB. Error: ", err)
return err
}
log.Info("Connected to Redis DB")
// Subscribe to Pub-Sub events for MEEP Controller
// NOTE: Current implementation is RedisDB Pub-Sub
err = rc.Subscribe(channelCtrlActive)
if err != nil {
log.Error("Failed to subscribe to Pub/Sub events. Error: ", err)
return err
}
log.Info("Subscribed to Redis Events")
// Setup for liveness monitoring
watchdogClient, err = watchdog.NewPingee(redisAddr, "meep-virt-engine")
if err != nil {
log.Error("Failed to initialize pigner. Error: ", err)
return err
}
err = watchdogClient.Start()
if err != nil {
log.Error("Failed watchdog client listen. Error: ", err)
return err
}
return nil
}
// ListenEvents - Redis DB event listener
func ListenEvents() {
// Listen for subscribed events. Provide event handler method.
_ = rc.Listen(eventHandler)
}
func eventHandler(channel string, payload string) {
// Handle Message according to Rx Channel
switch channel {
// MEEP Ctrl Engine active scenario update event
case channelCtrlActive:
log.Debug("Event received on channel: ", channel)
processActiveScenarioUpdate()
default:
log.Warn("Unsupported channel event: ", channel)
}
}
func processActiveScenarioUpdate() {
// Retrieve active scenario from DB
jsonScenario, err := rc.JSONGetEntry(activeScenarioEventKey, ".")
log.Debug("Scenario Event:", jsonScenario)
if err != nil {
terminateScenario(activeScenarioName)
activeScenarioName = ""
} else {
activateScenario(jsonScenario)
}
}
func unmarshallScenario(jsonScenario string) (model.Scenario, error) {
log.Debug("unmarshallScenario")
var scenario model.Scenario
//readAndPrintRequest(r)
err := json.Unmarshal([]byte(jsonScenario), &scenario)
if err != nil {
log.Error(err.Error())
return scenario, err
}
return scenario, nil
}
func activateScenario(jsonScenario string) {
scenario, err := unmarshallScenario(jsonScenario)
if err != nil {
log.Error("Error unmarshalling scenario: ", jsonScenario)
return
}
activeScenarioName = scenario.Name
err = CreateYamlScenarioFile(scenario)
if err != nil {
log.Error("Error creating scenario charts: ", err)
return
}
}
func terminateScenario(name string) {
// Make sure scenario name is valid
if name == "" {
log.Warn("Trying to terminate empty scenario")
return
}
// Retrieve list of releases
rels, _ := helm.GetReleasesName()
var toDelete []helm.Chart
for _, rel := range rels {
if strings.Contains(rel.Name, name) {
// just keep releases related to the current scenario
var c helm.Chart
c.ReleaseName = rel.Name
toDelete = append(toDelete, c)
}
}
// Delete releases
if len(toDelete) > 0 {
err := helm.DeleteReleases(toDelete)
log.Debug(err)
}
// Then delete charts
homePath := os.Getenv("HOME")
path := homePath + "/.meep/active/" + name
if _, err := os.Stat(path); err == nil {
log.Debug("Removing charts ", path)
os.RemoveAll(path)
}
}
| [
"\"HOME\""
] | [] | [
"HOME"
] | [] | ["HOME"] | go | 1 | 0 | |
main.py | from requests_oauthlib import OAuth2Session
from flask import Flask, request, redirect, session, url_for, render_template
from flask.json import jsonify
from dotenv import load_dotenv
import os
load_dotenv()
app = Flask(__name__)
app.secret_key = os.urandom(24)
# This information is obtained upon registration of a new GitHub OAuth
# application here: https://github.com/settings/applications/new
client_id = os.environ.get("CLIENT_ID")
client_secret = os.environ.get("CLIENT_SECRET")
authorization_base_url = 'https://github.com/login/oauth/authorize'
token_url = 'https://github.com/login/oauth/access_token'
@app.route('/')
def index():
login_status = False
avatar = None
if 'gh_id' in session and 'avatar' in session:
login_status = True
avatar = session['avatar']
return render_template('index.html', login=login_status,avatar=avatar)
@app.route("/login")
def gh_login():
"""Step 1: User Authorization.
Redirect the user/resource owner to the OAuth provider (i.e. Github)
using an URL with a few key OAuth parameters.
"""
github = OAuth2Session(client_id)
authorization_url, state = github.authorization_url(authorization_base_url)
# State is used to prevent CSRF, keep this for later.
session['oauth_state'] = state
return redirect(authorization_url)
# Step 2: User authorization, this happens on the provider.
@app.route("/gh-callback", methods=["GET"])
def callback():
""" Step 3: Retrieving an access token.
The user has been redirected back from the provider to your registered
callback URL. With this redirection comes an authorization code included
in the redirect URL. We will use that to obtain an access token.
"""
github = OAuth2Session(client_id, state=session['oauth_state'])
token = github.fetch_token(token_url, client_secret=client_secret,
authorization_response=request.url)
# At this point you can fetch protected resources but lets save
# the token to be able to reuse later
session['oauth_token'] = token
# Save some basic profile info and avatar image in the session
github = OAuth2Session(client_id, token=session['oauth_token'])
profile_data = github.get('https://api.github.com/user').json()
session['gh_id'] = profile_data['id']
session['gh_login'] = profile_data['login']
session['avatar'] = profile_data['avatar_url']
session['is_admin'] = False
# Crude way to set admin for additional functionality
if session['gh_id'] in ['1474512']:
session['is_admin'] = True
return redirect(url_for('.index'))
@app.route("/profile", methods=["GET"])
def profile():
"""Fetching and displaying profile data using an OAuth 2 token.
"""
github = OAuth2Session(client_id, token=session['oauth_token'])
profile_data = github.get('https://api.github.com/user').json()
return render_template('profile.html',data=profile_data,avatar=profile_data['avatar_url'])
@app.route("/logout", methods=["GET"])
def logout():
"""Log out the user. This will not clear the given GitHub authorization for this app.
"""
session.clear()
return redirect(url_for('.index'))
if __name__ == "__main__":
# This allows us to use a plain HTTP callback
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = "1"
app.run(debug=True)
| [] | [] | [
"CLIENT_SECRET",
"OAUTHLIB_INSECURE_TRANSPORT",
"CLIENT_ID"
] | [] | ["CLIENT_SECRET", "OAUTHLIB_INSECURE_TRANSPORT", "CLIENT_ID"] | python | 3 | 0 | |
NaschpunkteDP/NaschpunkteDP/wsgi.py | """
WSGI config for NaschpunkteDP project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "NaschpunkteDP.settings")
application = get_wsgi_application()
| [] | [] | [] | [] | [] | python | 0 | 0 | |
examples/cvm/v20170312/describe_zones.go | package main
import (
"fmt"
"os"
"github.com/iftechio/tencentcloud-sdk-go/tencentcloud/common"
"github.com/iftechio/tencentcloud-sdk-go/tencentcloud/common/errors"
"github.com/iftechio/tencentcloud-sdk-go/tencentcloud/common/profile"
cvm "github.com/iftechio/tencentcloud-sdk-go/tencentcloud/cvm/v20170312"
)
func main() {
// 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey
// 这里采用的是从环境变量读取的方式,需要在环境变量中先设置这两个值
credential := common.NewCredential(
os.Getenv("TENCENTCLOUD_SECRET_ID"),
os.Getenv("TENCENTCLOUD_SECRET_KEY"),
)
// 实例化一个客户端配置对象,可以指定超时时间等配置
cpf := profile.NewClientProfile()
cpf.HttpProfile.ReqMethod = "GET"
cpf.HttpProfile.ReqTimeout = 5
cpf.Debug = true
// 实例化要请求产品(以cvm为例)的client对象
client, _ := cvm.NewClient(credential, "ap-beijing", cpf)
// 实例化一个请求对象,根据调用的接口和实际情况,可以进一步设置请求参数
request := cvm.NewDescribeZonesRequest()
// 通过client对象调用想要访问的接口,需要传入请求对象
response, err := client.DescribeZones(request)
// 处理异常
if _, ok := err.(*errors.TencentCloudSDKError); ok {
fmt.Printf("An API error has returned: %s", err)
return
}
// unexpected errors
if err != nil {
panic(err)
}
// 打印返回的json字符串
fmt.Printf("%s", response.ToJsonString())
}
| [
"\"TENCENTCLOUD_SECRET_ID\"",
"\"TENCENTCLOUD_SECRET_KEY\""
] | [] | [
"TENCENTCLOUD_SECRET_ID",
"TENCENTCLOUD_SECRET_KEY"
] | [] | ["TENCENTCLOUD_SECRET_ID", "TENCENTCLOUD_SECRET_KEY"] | go | 2 | 0 | |
py/scripts/nightly_gfa_redux.py | #!/usr/bin/env python
import os
import glob
from astropy.table import Table
import astropy.io.fits as fits
import numpy as np
import random
import argparse
from gfa_reduce.common import expid_from_filename
import gfa_reduce.gfa_red as gfa_red
out_basedir = 'gfa_redux'
basedir = os.environ['DESI_SPECTRO_DATA']
lostfound = os.environ['DESI_LOST_FOUND']
def _search_dirs():
return [basedir, lostfound]
def _spectro_list(night):
# night should be a string
search_dirs = _search_dirs()
result = []
for _basedir in search_dirs:
dir = os.path.join(_basedir, night)
if not os.path.exists(dir):
continue
pattern = dir + '/' + '????????' + '/desi-????????.fits.fz'
flist = glob.glob(pattern)
result = result + flist
return result
# this is the list of guide-????????.fits.fz files corresponding to a
# desi-????????.fits.fz spectro file
def _guider_list(spectro_flist):
flist_pred = [s.replace('desi-', 'guide-') for s in spectro_flist]
result = []
search_dirs = _search_dirs()
spectro_flist_matched = []
for i, f in enumerate(flist_pred):
if os.path.exists(f):
result.append(f)
spectro_flist_matched.append(spectro_flist[i])
elif os.path.exists(f.replace(search_dirs[0], search_dirs[1])):
result.append(f.replace(search_dirs[0], search_dirs[1]))
spectro_flist_matched.append(spectro_flist[i])
elif os.path.exists(f.replace(search_dirs[1], search_dirs[0])):
result.append(f.replace(search_dirs[1], search_dirs[0]))
spectro_flist_matched.append(spectro_flist[i])
if len(result) == 0:
print('no guide cubes with corresponding spectra ???')
assert(len(spectro_flist_matched) == len(result))
return result, spectro_flist_matched
def _acq_list(night):
# night should be a string
search_dirs = _search_dirs()
result = []
for _basedir in search_dirs:
dir = os.path.join(_basedir, night)
if not os.path.exists(dir):
continue
pattern = dir + '/' + '????????' + '/guide-????????-0000.fits.fz'
flist = glob.glob(pattern)
result = result + flist
return result
def _one_command(fname, night, out_basedir=out_basedir,
background=False, mjdrange=None, fieldmodel=False,
pmgstars=True, make_exp_outdir=True,
log_prefix='coadd', acq=False):
# assume that if mjdrange is not None, then it will be a two element list
# [mjdmin, mjdmax]
assert(os.path.exists(fname))
assert(os.path.exists(out_basedir))
expid = expid_from_filename(fname)
outdir = os.path.join(out_basedir, night + '/' + str(expid).zfill(8))
if make_exp_outdir:
if not os.path.exists(outdir):
os.mkdir(outdir)
cmd = 'python -u ' + gfa_red.__file__ + ' ' + fname + ' --outdir ' + \
outdir + ' --skip_image_outputs'
if not acq:
cmd += ' --cube_index -1 '
else:
cmd += ' '
if mjdrange is not None:
_extra = '--mjdmin ' + str(mjdrange[0]) + ' --mjdmax ' + \
str(mjdrange[1]) + ' '
cmd += _extra
if fieldmodel:
cmd += '--fieldmodel '
if pmgstars:
cmd += '--pmgstars '
cmd += '&> ' + log_prefix + '-' + str(expid).zfill(8) + '.log'
return cmd
def _all_coadd_commands(flist, flist_spectro, night, out_basedir=out_basedir,
background=False, match_spectro_mjd=True,
fieldmodel=False, pmgstars=True,
make_exp_outdirs=True):
# just loop over _one_command
cmds = []
for i, f in enumerate(flist):
if match_spectro_mjd:
fname_spectro = flist_spectro[i]
assert(os.path.exists(fname_spectro))
h = fits.getheader(fname_spectro, extname='SPEC')
if (h['MJD-OBS'] is None) or (h['EXPTIME'] is None):
continue
mjdmin = h['MJD-OBS']
mjdmax = h['MJD-OBS'] + h['EXPTIME']/(3600.0*24.0)
mjdrange = [mjdmin, mjdmax]
else:
mjdrange = None
cmd = _one_command(f, night, out_basedir=out_basedir,
background=background, mjdrange=mjdrange,
fieldmodel=fieldmodel, pmgstars=pmgstars,
make_exp_outdir=make_exp_outdirs)
cmds.append(cmd)
return cmds
def _gen_acq_commands(night='20201214', out_basedir=out_basedir,
background=False, fieldmodel=False,
make_exp_outdirs=True):
flist_acq = _acq_list(night)
if len(flist_acq) == 0:
print('no acquisition images to process')
return []
cmds = []
for f in flist_acq:
cmd = _one_command(f, night, out_basedir=out_basedir,
background=background,
fieldmodel=fieldmodel, pmgstars=False,
make_exp_outdir=make_exp_outdirs,
log_prefix='acq', acq=True)
cmds.append(cmd)
return cmds
def _gen_coadd_commands(night='20201214', out_basedir=out_basedir,
background=False, match_spectro_mjd=True,
fieldmodel=False, pmgstars=True,
make_exp_outdirs=True):
flist_spectro = _spectro_list(night)
flist, flist_spectro_matched = _guider_list(flist_spectro)
night_dir = os.path.join(out_basedir, night)
if not os.path.exists(night_dir):
print('attempting to make nightly subdirectory ' + \
night_dir)
os.mkdir(night_dir)
cmds = _all_coadd_commands(flist, flist_spectro_matched, night,
match_spectro_mjd=match_spectro_mjd,
out_basedir=out_basedir, fieldmodel=fieldmodel,
pmgstars=pmgstars,
make_exp_outdirs=make_exp_outdirs)
return cmds
def _launch_scripts(night, match_spectro_mjd=True, out_basedir=out_basedir,
fieldmodel=False, pmgstars=True, make_exp_outdirs=True):
if not os.path.exists(out_basedir):
print('the base output directory ' + out_basedir + \
' does not exist, will attempt to create it now')
# might be good to check that out_basedir is a one-element string
os.mkdir(out_basedir)
cmds = _gen_coadd_commands(night=night, match_spectro_mjd=match_spectro_mjd,
out_basedir=out_basedir, fieldmodel=fieldmodel,
pmgstars=pmgstars,
make_exp_outdirs=make_exp_outdirs)
print(str(len(cmds)) + ' matched coadd jobs to run')
cmds_acq = _gen_acq_commands(night=night, out_basedir=out_basedir,
fieldmodel=fieldmodel,
make_exp_outdirs=make_exp_outdirs)
print(str(len(cmds_acq)) + ' acquisition images to run')
cmds = cmds + cmds_acq
random.seed(99)
random.shuffle(cmds)
# number of concurrent processes to run on one Cori node
# could consider pushing this higher
n_scripts_max = 20
chunksize = int(np.ceil(float(len(cmds))/float(n_scripts_max)))
print('packaging ' + str(chunksize) + ' jobs per worker')
n_scripts = int(np.ceil(float(len(cmds))/float(chunksize)))
fnames = []
for i in range(n_scripts):
fname = 'chunk_' + str(i).zfill(3) + '_' + night + '.sh'
assert(not os.path.exists(fname))
indstart = i*chunksize
indend = min((i + 1)*chunksize, len(cmds))
with open(fname, 'wb') as f:
print('writing chunk script ' + str(i+1) + ' ' +
' of ' + str(n_scripts) + ' ' + fname)
for cmd in cmds[indstart:indend]:
f.write((cmd + '\n').encode('ascii'))
f.close()
fnames.append(fname)
# create the launch script
launch_name = 'launch_' + night + '.sh'
with open(launch_name, 'wb') as f:
print('writing overall launch script ' + launch_name)
for fname in fnames:
cmd = './' + fname + ' &\n'
f.write(cmd.encode('ascii'))
f.close()
for f in fnames:
os.system('chmod a+rx ' + f)
os.system('chmod a+rx ' + launch_name)
if __name__ == "__main__":
descr = 'generate nightly gfa_reduce processing launch scripts'
parser = argparse.ArgumentParser(description=descr)
parser.add_argument('night', type=str, nargs=1,
help="observing night")
parser.add_argument('--out_basedir', default=out_basedir, type=str,
help='base output directory')
parser.add_argument('--fieldmodel', default=False, action='store_true',
help='fit desimeter FieldModel')
parser.add_argument('--skip_exp_outdirs', default=False,
action='store_true',
help="don't pre-generate per EXPID output directories")
parser.add_argument('--skip_pmgstars', default=False, action='store_true',
help="skip PMGSTARS forced photometry")
args = parser.parse_args()
make_exp_outdirs = not args.skip_exp_outdirs
pmgstars = not args.skip_pmgstars
_launch_scripts(args.night[0], match_spectro_mjd=True,
out_basedir=args.out_basedir,
fieldmodel=args.fieldmodel, pmgstars=pmgstars,
make_exp_outdirs=make_exp_outdirs)
| [] | [] | [
"DESI_LOST_FOUND",
"DESI_SPECTRO_DATA"
] | [] | ["DESI_LOST_FOUND", "DESI_SPECTRO_DATA"] | python | 2 | 0 | |
src/firestone_engine/calculate.py | # -*- coding: utf-8 -*-
"""
This is a skeleton file that can serve as a starting point for a Python
console script. To run this script uncomment the following lines in the
[options.entry_points] section in setup.cfg:
console_scripts =
firerock = firestone_engine.calculate:run
Then run `python setup.py install` which will install the command `firerock`
inside your current environment.
Besides console scripts, the header (i.e. until _logger...) of this file can
also be used as template for Python modules.
Note: This skeleton file can be safely removed if not needed!
"""
import os
# import ptvsd
import argparse
import sys
import time
import logging
from logging.handlers import TimedRotatingFileHandler
from firestone_engine.Trader import Trader
from firestone_engine import __version__
__author__ = "aqua"
__copyright__ = "aqua"
__license__ = "mit"
_logger = logging.getLogger(__name__)
def calculate(tradeId, is_mock, ignore_trade, date, hours, minutes, seconds):
"""execute the trade
Args:
codes: tradeId
Returns:
trade result
"""
if(seconds is None):
seconds = '2,5,8,11,14,17,20,23,26,29,32,35,38,41,44,47,50,53,56,59'
if(hours is None):
trader = Trader(tradeId, is_mock, ignore_trade, date, seconds=seconds)
else:
trader = Trader(tradeId, is_mock, ignore_trade, date, hours=hours, minutes=minutes, seconds=seconds)
trader.start()
try:
while(not trader.is_finsih()):
time.sleep(100)
except KeyboardInterrupt:
pass
finally:
trader.stop()
def parse_args(args):
"""Parse command line parameters
Args:
args ([str]): command line parameters as list of strings
Returns:
:obj:`argparse.Namespace`: command line parameters namespace
"""
parser = argparse.ArgumentParser(
description="strategy engine for firestone")
parser.add_argument(
"--version",
action="version",
version="firestone-engine {ver}".format(ver=__version__))
parser.add_argument(
dest="tradeId",
help="the tradeId, i.e. 5db4fa20ea3ae4a6ff26a3d1",
metavar="tradeId")
parser.add_argument(
"-m",
"--mock",
dest="mock",
help="use mock trade",
action="store_true")
parser.add_argument(
"-v",
"--verbose",
dest="loglevel",
help="set loglevel to INFO",
action="store_const",
const=logging.INFO)
parser.add_argument(
"-vv",
"--very-verbose",
dest="loglevel",
help="set loglevel to DEBUG",
action="store_const",
const=logging.DEBUG)
parser.add_argument(
"-d",
"--debug",
dest="debug",
help="set to debug mode use vscode",
action="store_true")
parser.add_argument(
"-t",
"--test",
dest="test",
help="set environment as test, the db will be firestone-test",
action="store_true")
parser.add_argument(
"-i"
"--ignoreTrade",
dest="ignore_trade",
help="ignore trade part, no trade will happen",
action="store_true")
parser.add_argument(
"--date",
dest="date",
help="get data date")
parser.add_argument(
"--hours",
dest="hours",
help="i.e. 9 11 10,13-14",
nargs='+',
metavar="hour")
parser.add_argument(
"--minutes",
dest="minutes",
help="i.e. 30-59 0-29 *",
nargs='+',
metavar="minute")
parser.add_argument(
"--seconds",
dest="seconds",
help="i.e. 2,5,8,11,14,17,20,23,26,29,32,35,38,41,44,47,50,53,56,59",
metavar="second")
return parser.parse_args(args)
def setup_logging(tradeId, loglevel):
"""Setup basic logging
Args:
loglevel (int): minimum loglevel for emitting messages
"""
logformat = "[%(asctime)s] %(levelname)s:%(name)s:%(message)s"
handler = TimedRotatingFileHandler(f'logs/firerock-{tradeId}.log', when='D', interval=1, backupCount=10 ,encoding='UTF-8')
logging.basicConfig(level=loglevel, format=logformat, datefmt="%Y-%m-%d %H:%M:%S", handlers=[handler])
def main(args):
"""Main entry point allowing external calls
Args:
args ([str]): command line parameter list
"""
args = parse_args(args)
# if(args.debug):
# # 5678 is the default attach port in the VS Code debug configurations
# print("start debug on port 5678")
# ptvsd.enable_attach(address=('localhost', 5678), redirect_output=True)
# ptvsd.wait_for_attach()
if(args.test):
os.environ['FR_DB'] = 'firestone-test'
else:
os.environ['FR_DB'] = 'firestone'
setup_logging(args.tradeId, args.loglevel)
calculate(args.tradeId, args.mock, args.ignore_trade, args.date, args.hours, args.minutes, args.seconds)
def run():
"""Entry point for console_scripts
"""
main(sys.argv[1:])
if __name__ == "__main__":
run()
| [] | [] | [
"FR_DB"
] | [] | ["FR_DB"] | python | 1 | 0 | |
server/database/mysql.go | package database
import (
"aske-w/itu-minitwit/models"
"fmt"
"log"
"os"
"time"
// Sqlite driver based on GGO
// "github.com/glebarez/sqlite" // Pure go SQLite driver, checkout https://github.com/glebarez/sqlite for details
"gorm.io/driver/mysql"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"gorm.io/plugin/prometheus"
)
// github.com/mattn/go-sqlite3
func ConnectMySql(mode string) (*gorm.DB, error) {
newLogger := logger.New(
log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
logger.Config{
SlowThreshold: time.Second, // Slow SQL threshold
LogLevel: logger.Error, // Log level
IgnoreRecordNotFoundError: false, // Ignore ErrRecordNotFound error for logger
Colorful: true, // Disable color
},
)
user := os.Getenv("MYSQL_USER")
password := os.Getenv("MYSQL_PASSWORD")
address := os.Getenv("MYSQL_ADDRESS")
port := os.Getenv("MYSQL_PORT")
db_name := os.Getenv("MYSQL_DATABASE")
var db *gorm.DB
var err error
if mode == "production" {
dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", user, password, address, port, db_name)
db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
Logger: newLogger,
})
db.Use(prometheus.New(prometheusConfiguration(db_name)))
} else {
db, err = gorm.Open(sqlite.Open("file::memory:"), &gorm.Config{
Logger: newLogger,
})
}
if err != nil {
return nil, err
}
db.AutoMigrate(&models.User{})
db.AutoMigrate(&models.Message{})
db.AutoMigrate(&models.Latest{})
return db, nil
}
func prometheusConfiguration(dbName string) prometheus.Config {
return prometheus.Config{
DBName: dbName,
RefreshInterval: 60,
HTTPServerPort: 8080, // Use the port as the Iris server
MetricsCollector: []prometheus.MetricsCollector{
&prometheus.MySQL{
VariableNames: []string{"Threads_running", "Slow_queries", "Uptime"},
},
}, // user defined metrics
}
}
| [
"\"MYSQL_USER\"",
"\"MYSQL_PASSWORD\"",
"\"MYSQL_ADDRESS\"",
"\"MYSQL_PORT\"",
"\"MYSQL_DATABASE\""
] | [] | [
"MYSQL_PASSWORD",
"MYSQL_USER",
"MYSQL_ADDRESS",
"MYSQL_PORT",
"MYSQL_DATABASE"
] | [] | ["MYSQL_PASSWORD", "MYSQL_USER", "MYSQL_ADDRESS", "MYSQL_PORT", "MYSQL_DATABASE"] | go | 5 | 0 | |
scripts/west_commands/build.py | # Copyright (c) 2018 Foundries.io
#
# SPDX-License-Identifier: Apache-2.0
import argparse
import os
from west import log
from west.configuration import config
from zcmake import DEFAULT_CMAKE_GENERATOR, run_cmake, run_build, CMakeCache
from build_helpers import is_zephyr_build, find_build_dir, \
FIND_BUILD_DIR_DESCRIPTION
from zephyr_ext_common import Forceable
_ARG_SEPARATOR = '--'
BUILD_USAGE = '''\
west build [-h] [-b BOARD] [-d BUILD_DIR]
[-t TARGET] [-p {auto, always, never}] [-c] [--cmake-only]
[-n] [-o BUILD_OPT] [-f]
[source_dir] -- [cmake_opt [cmake_opt ...]]
'''
BUILD_DESCRIPTION = '''\
Convenience wrapper for building Zephyr applications.
positional arguments:
source_dir Use this path as the source directory
cmake_opt Extra options to pass to CMake; implies -c
'''
def _banner(msg):
log.inf('-- west build: ' + msg, colorize=True)
def config_get(option, fallback):
return config.get('build', option, fallback=fallback)
def config_getboolean(option, fallback):
return config.getboolean('build', option, fallback=fallback)
class AlwaysIfMissing(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
setattr(namespace, self.dest, values or 'always')
class Build(Forceable):
def __init__(self):
super(Build, self).__init__(
'build',
# Keep this in sync with the string in west-commands.yml.
'compile a Zephyr application',
BUILD_DESCRIPTION,
accepts_unknown_args=True)
self.source_dir = None
'''Source directory for the build, or None on error.'''
self.build_dir = None
'''Final build directory used to run the build, or None on error.'''
self.created_build_dir = False
'''True if the build directory was created; False otherwise.'''
self.run_cmake = False
'''True if CMake was run; False otherwise.
Note: this only describes CMake runs done by this command. The
build system generated by CMake may also update itself due to
internal logic.'''
self.cmake_cache = None
'''Final parsed CMake cache for the build, or None on error.'''
def do_add_parser(self, parser_adder):
parser = parser_adder.add_parser(
self.name,
help=self.help,
formatter_class=argparse.RawDescriptionHelpFormatter,
description=self.description,
usage=BUILD_USAGE)
# Remember to update scripts/west-completion.bash if you add or remove
# flags
parser.add_argument('-b', '--board', help='Board to build for')
# Hidden option for backwards compatibility
parser.add_argument('-s', '--source-dir', help=argparse.SUPPRESS)
parser.add_argument('-d', '--build-dir',
help='Build directory. ' +
FIND_BUILD_DIR_DESCRIPTION +
" Otherwise the default build directory is " +
"created and used.")
parser.add_argument('-t', '--target',
help='''Build system target to run''')
parser.add_argument('-p', '--pristine', choices=['auto', 'always',
'never'], action=AlwaysIfMissing, nargs='?',
help='''Control whether the build folder is made
pristine before running CMake. --pristine is the
same as --pristine=always. If 'auto', it will
be made pristine only if needed.''')
parser.add_argument('-c', '--cmake', action='store_true',
help='Force CMake to run')
parser.add_argument('--cmake-only', action='store_true',
help="Just run CMake; don't build. Implies -c.")
parser.add_argument('-n', '--just-print', '--dry-run', '--recon',
dest='dry_run', action='store_true',
help='''Just print the build commands; don't run
them''')
parser.add_argument('-o', '--build-opt', default=[], action='append',
help='''Options to pass to the build tool.
May be given more than once to append multiple
values.''')
self.add_force_arg(parser)
return parser
def do_run(self, args, remainder):
self.args = args # Avoid having to pass them around
self.config_board = config_get('board', None)
log.dbg('args: {} remainder: {}'.format(args, remainder),
level=log.VERBOSE_EXTREME)
# Store legacy -s option locally
source_dir = self.args.source_dir
self._parse_remainder(remainder)
if source_dir:
if self.args.source_dir:
log.die("source directory specified twice:({} and {})".format(
source_dir, self.args.source_dir))
self.args.source_dir = source_dir
log.dbg('source_dir: {} cmake_opts: {}'.format(self.args.source_dir,
self.args.cmake_opts),
level=log.VERBOSE_EXTREME)
self._sanity_precheck()
self._setup_build_dir()
if args.pristine is not None:
pristine = args.pristine
else:
# Load the pristine={auto, always, never} configuration value
pristine = config_get('pristine', 'never')
if pristine not in ['auto', 'always', 'never']:
log.wrn(
'treating unknown build.pristine value "{}" as "never"'.
format(pristine))
pristine = 'never'
self.auto_pristine = (pristine == 'auto')
log.dbg('pristine: {} auto_pristine: {}'.format(pristine,
self.auto_pristine),
level=log.VERBOSE_VERY)
if is_zephyr_build(self.build_dir):
if pristine == 'always':
self._run_pristine()
self.run_cmake = True
else:
self._update_cache()
if (self.args.cmake or self.args.cmake_opts or
self.args.cmake_only):
self.run_cmake = True
else:
self.run_cmake = True
self.source_dir = self._find_source_dir()
self._sanity_check()
board, origin = self._find_board()
self._run_cmake(board, origin, self.args.cmake_opts)
if args.cmake_only:
return
self._sanity_check()
self._update_cache()
self._run_build(args.target)
def _find_board(self):
board, origin = None, None
if self.cmake_cache:
board, origin = (self.cmake_cache.get('CACHED_BOARD'),
'CMakeCache.txt')
elif self.args.board:
board, origin = self.args.board, 'command line'
elif 'BOARD' in os.environ:
board, origin = os.environ['BOARD'], 'env'
elif self.config_board is not None:
board, origin = self.config_board, 'configfile'
return board, origin
def _parse_remainder(self, remainder):
self.args.source_dir = None
self.args.cmake_opts = None
try:
# Only one source_dir is allowed, as the first positional arg
if remainder[0] != _ARG_SEPARATOR:
self.args.source_dir = remainder[0]
remainder = remainder[1:]
# Only the first argument separator is consumed, the rest are
# passed on to CMake
if remainder[0] == _ARG_SEPARATOR:
remainder = remainder[1:]
if remainder:
self.args.cmake_opts = remainder
except IndexError:
return
def _sanity_precheck(self):
app = self.args.source_dir
if app:
self.check_force(
os.path.isdir(app),
'source directory {} does not exist'.format(app))
self.check_force(
'CMakeLists.txt' in os.listdir(app),
"{} doesn't contain a CMakeLists.txt".format(app))
def _update_cache(self):
try:
self.cmake_cache = CMakeCache.from_build_dir(self.build_dir)
except FileNotFoundError:
pass
def _setup_build_dir(self):
# Initialize build_dir and created_build_dir attributes.
# If we created the build directory, we must run CMake.
log.dbg('setting up build directory', level=log.VERBOSE_EXTREME)
# The CMake Cache has not been loaded yet, so this is safe
board, _ = self._find_board()
source_dir = self._find_source_dir()
app = os.path.split(source_dir)[1]
build_dir = find_build_dir(self.args.build_dir, board=board,
source_dir=source_dir, app=app)
if not build_dir:
log.die('Unable to determine a default build folder. Check '
'your build.dir-fmt configuration option')
if os.path.exists(build_dir):
if not os.path.isdir(build_dir):
log.die('build directory {} exists and is not a directory'.
format(build_dir))
else:
os.makedirs(build_dir, exist_ok=False)
self.created_build_dir = True
self.run_cmake = True
self.build_dir = build_dir
def _find_source_dir(self):
# Initialize source_dir attribute, either from command line argument,
# implicitly from the build directory's CMake cache, or using the
# default (current working directory).
log.dbg('setting up source directory', level=log.VERBOSE_EXTREME)
if self.args.source_dir:
source_dir = self.args.source_dir
elif self.cmake_cache:
source_dir = self.cmake_cache.get('CMAKE_HOME_DIRECTORY')
if not source_dir:
# This really ought to be there. The build directory
# must be corrupted somehow. Let's see what we can do.
log.die('build directory', self.build_dir,
'CMake cache has no CMAKE_HOME_DIRECTORY;',
'please give a source_dir')
else:
source_dir = os.getcwd()
return os.path.abspath(source_dir)
def _sanity_check_source_dir(self):
if self.source_dir == self.build_dir:
# There's no forcing this.
log.die('source and build directory {} cannot be the same; '
'use --build-dir {} to specify a build directory'.
format(self.source_dir, self.build_dir))
srcrel = os.path.relpath(self.source_dir)
self.check_force(
not is_zephyr_build(self.source_dir),
'it looks like {srcrel} is a build directory: '
'did you mean --build-dir {srcrel} instead?'.
format(srcrel=srcrel))
self.check_force(
'CMakeLists.txt' in os.listdir(self.source_dir),
'source directory "{srcrel}" does not contain '
'a CMakeLists.txt; is this really what you '
'want to build? (Use -s SOURCE_DIR to specify '
'the application source directory)'.
format(srcrel=srcrel))
def _sanity_check(self):
# Sanity check the build configuration.
# Side effect: may update cmake_cache attribute.
log.dbg('sanity checking the build', level=log.VERBOSE_EXTREME)
self._sanity_check_source_dir()
if not self.cmake_cache:
return # That's all we can check without a cache.
cached_app = self.cmake_cache.get('APPLICATION_SOURCE_DIR')
log.dbg('APPLICATION_SOURCE_DIR:', cached_app,
level=log.VERBOSE_EXTREME)
source_abs = (os.path.abspath(self.args.source_dir)
if self.args.source_dir else None)
cached_abs = os.path.abspath(cached_app) if cached_app else None
log.dbg('pristine:', self.auto_pristine, level=log.VERBOSE_EXTREME)
# If the build directory specifies a source app, make sure it's
# consistent with --source-dir.
apps_mismatched = (source_abs and cached_abs and
source_abs != cached_abs)
self.check_force(
not apps_mismatched or self.auto_pristine,
'Build directory "{}" is for application "{}", but source '
'directory "{}" was specified; please clean it, use --pristine, '
'or use --build-dir to set another build directory'.
format(self.build_dir, cached_abs, source_abs))
if apps_mismatched:
self.run_cmake = True # If they insist, we need to re-run cmake.
# If CACHED_BOARD is not defined, we need some other way to
# find the board.
cached_board = self.cmake_cache.get('CACHED_BOARD')
log.dbg('CACHED_BOARD:', cached_board, level=log.VERBOSE_EXTREME)
# If apps_mismatched and self.auto_pristine are true, we will
# run pristine on the build, invalidating the cached
# board. In that case, we need some way of getting the board.
self.check_force((cached_board and
not (apps_mismatched and self.auto_pristine))
or self.args.board or self.config_board or
os.environ.get('BOARD'),
'Cached board not defined, please provide it '
'(provide --board, set default with '
'"west config build.board <BOARD>", or set '
'BOARD in the environment)')
# Check consistency between cached board and --board.
boards_mismatched = (self.args.board and cached_board and
self.args.board != cached_board)
self.check_force(
not boards_mismatched or self.auto_pristine,
'Build directory {} targets board {}, but board {} was specified. '
'(Clean the directory, use --pristine, or use --build-dir to '
'specify a different one.)'.
format(self.build_dir, cached_board, self.args.board))
if self.auto_pristine and (apps_mismatched or boards_mismatched):
self._run_pristine()
self.cmake_cache = None
log.dbg('run_cmake:', True, level=log.VERBOSE_EXTREME)
self.run_cmake = True
# Tricky corner-case: The user has not specified a build folder but
# there was one in the CMake cache. Since this is going to be
# invalidated, reset to CWD and re-run the basic tests.
if ((boards_mismatched and not apps_mismatched) and
(not source_abs and cached_abs)):
self.source_dir = self._find_source_dir()
self._sanity_check_source_dir()
def _run_cmake(self, board, origin, cmake_opts):
_banner(
'''build configuration:
source directory: {}
build directory: {}{}
BOARD: {}'''.
format(self.source_dir, self.build_dir,
' (created)' if self.created_build_dir else '',
('{} (origin: {})'.format(board, origin) if board
else 'UNKNOWN')))
if board is None and config_getboolean('board_warn', True):
log.wrn('This looks like a fresh build and BOARD is unknown;',
"so it probably won't work. To fix, use",
'--board=<your-board>.')
log.inf('Note: to silence the above message, run',
"'west config build.board_warn false'")
if not self.run_cmake:
log.dbg('Not generating a build system; one is present.')
return
_banner('generating a build system')
if board is not None and origin != 'CMakeCache.txt':
cmake_opts = ['-DBOARD={}'.format(board)]
else:
cmake_opts = []
if self.args.cmake_opts:
cmake_opts.extend(self.args.cmake_opts)
# Invoke CMake from the current working directory using the
# -S and -B options (officially introduced in CMake 3.13.0).
# This is important because users expect invocations like this
# to Just Work:
#
# west build -- -DOVERLAY_CONFIG=relative-path.conf
final_cmake_args = ['-B{}'.format(self.build_dir),
'-S{}'.format(self.source_dir),
'-G{}'.format(config_get('generator',
DEFAULT_CMAKE_GENERATOR))]
if cmake_opts:
final_cmake_args.extend(cmake_opts)
run_cmake(final_cmake_args, dry_run=self.args.dry_run)
def _run_pristine(self):
_banner('making build dir {} pristine'.format(self.build_dir))
zb = os.environ.get('ZEPHYR_BASE')
if not zb:
log.die('Internal error: ZEPHYR_BASE not set in the environment, '
'and should have been by the main script')
if not is_zephyr_build(self.build_dir):
log.die('Refusing to run pristine on a folder that is not a '
'Zephyr build system')
cmake_args = ['-P', '{}/cmake/pristine.cmake'.format(zb)]
run_cmake(cmake_args, cwd=self.build_dir, dry_run=self.args.dry_run)
def _run_build(self, target):
if target:
_banner('running target {}'.format(target))
else:
_banner('building application')
extra_args = ['--target', target] if target else []
if self.args.build_opt:
extra_args.append('--')
extra_args.extend(self.args.build_opt)
if self.args.verbose:
self._append_verbose_args(extra_args,
not bool(self.args.build_opt))
run_build(self.build_dir, extra_args=extra_args,
dry_run=self.args.dry_run)
def _append_verbose_args(self, extra_args, add_dashes):
# These hacks are only needed for CMake versions earlier than
# 3.14. When Zephyr's minimum version is at least that, we can
# drop this nonsense and just run "cmake --build BUILD -v".
self._update_cache()
if not self.cmake_cache:
return
generator = self.cmake_cache.get('CMAKE_GENERATOR')
if not generator:
return
# Substring matching is for things like "Eclipse CDT4 - Ninja".
if 'Ninja' in generator:
if add_dashes:
extra_args.append('--')
extra_args.append('-v')
elif generator == 'Unix Makefiles':
if add_dashes:
extra_args.append('--')
extra_args.append('VERBOSE=1')
| [] | [] | [
"BOARD",
"ZEPHYR_BASE"
] | [] | ["BOARD", "ZEPHYR_BASE"] | python | 2 | 0 | |
train_tromis.py | #!/usr/bin/env python3
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
os.environ['TF_FORCE_GPU_ALLOW_GROWTH'] = 'true'
import tensorflow as tf
import tensorflow.keras as keras
tf.get_logger().setLevel('ERROR')
from rl.games import tromis
from rl.agents import dqn
from rl.memory import uniqmemory
from rl.callbacks import history
width, height = 7, 10
nb_frames = 1
game = tromis.Tromis(width, height, max_turn=512)
inp = keras.layers.Input(shape=(nb_frames, height, width, 3))
x = keras.layers.Conv3D(32,5,padding='same',strides=1,activation='relu')(inp)
x = keras.layers.AveragePooling3D(padding='same')(x)
x = keras.layers.Conv3D(64,3,padding='same',strides=1,activation='relu')(x)
x = keras.layers.GlobalAveragePooling3D()(x)
x = keras.layers.Dense(128, activation='relu')(x)
act = keras.layers.Dense(game.nb_actions, activation='linear')(x)
model = keras.models.Model(inputs=inp, outputs=act)
model.compile(keras.optimizers.RMSprop(), keras.losses.LogCosh())
model.summary()
params = {
'batch_size': 256,
'epochs': 200,
'episodes': 100,
'train_freq': 32,
'target_sync': 512,
'epsilon_start': 0.5,
'epsilon_decay': 0.75,
'epsilon_final': 0.0,
'gamma': 0.92,
'reset_memory': False,
'observe': 100
}
rlparams = {
'rl.memory': 'UniqMemory',
'rl.memory_size': 65536,
'rl.optimizer': 'RMSprop',
'rl.with_target': True,
'rl.nb_frames': nb_frames
}
gameparams = {
'game.width': game.width,
'game.height': game.height,
'game.max_turn': game.max_turn
}
memory = uniqmemory.UniqMemory(memory_size=rlparams['rl.memory_size'])
agent = dqn.Agent(model, memory, with_target=rlparams['rl.with_target'])
#history = history.HistoryLog("tromis", {**params, **rlparams, **gameparams})
agent.train(game, verbose=1, callbacks=[], **params)
| [] | [] | [
"TF_FORCE_GPU_ALLOW_GROWTH",
"TF_CPP_MIN_LOG_LEVEL"
] | [] | ["TF_FORCE_GPU_ALLOW_GROWTH", "TF_CPP_MIN_LOG_LEVEL"] | python | 2 | 0 | |
vendor/github.com/mozillazg/go-cos/examples/object/initiateMultipartUpload.go | package main
import (
"context"
"fmt"
"net/url"
"os"
"time"
"net/http"
"github.com/mozillazg/go-cos"
"github.com/mozillazg/go-cos/examples"
)
func main() {
u, _ := url.Parse("https://test-1253846586.cn-north.myqcloud.com")
b := &cos.BaseURL{BucketURL: u}
c := cos.NewClient(b, &http.Client{
Transport: &cos.AuthorizationTransport{
SecretID: os.Getenv("COS_SECRETID"),
SecretKey: os.Getenv("COS_SECRETKEY"),
Transport: &examples.DebugRequestTransport{
RequestHeader: true,
RequestBody: true,
ResponseHeader: true,
ResponseBody: true,
},
},
})
name := "test_multipart" + time.Now().Format(time.RFC3339)
v, _, err := c.Object.InitiateMultipartUpload(context.Background(), name, nil)
if err != nil {
panic(err)
}
fmt.Printf("%s\n", v.UploadID)
}
| [
"\"COS_SECRETID\"",
"\"COS_SECRETKEY\""
] | [] | [
"COS_SECRETKEY",
"COS_SECRETID"
] | [] | ["COS_SECRETKEY", "COS_SECRETID"] | go | 2 | 0 | |
cfgov/cfgov/settings/test.py | from .local import *
# A test database may be specified through use of the TEST_DATABASE_URL
# environment variable. If not provided, unit tests will be run against an
# in-memory SQLite database.
TEST_DATABASE_URL = os.getenv('TEST_DATABASE_URL')
if TEST_DATABASE_URL:
TEST_DATABASE = dj_database_url.parse(TEST_DATABASE_URL)
else:
TEST_DATABASE = {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
'TEST': {
'NAME': ':memory:',
},
}
DATABASES = {'default': TEST_DATABASE}
EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend'
TEST_RUNNER = os.environ.get('TEST_RUNNER', 'cfgov.test.TestRunner')
INSTALLED_APPS += (
'wagtail.contrib.settings',
'wagtail.tests.testapp',
)
WAGTAILADMIN_RICH_TEXT_EDITORS = {
'default': {
'WIDGET': 'wagtail.wagtailadmin.rich_text.HalloRichTextArea',
},
'custom': {
'WIDGET': 'wagtail.tests.testapp.rich_text.CustomRichTextArea',
},
}
GOVDELIVERY_API = 'core.govdelivery.MockGovDelivery'
STATICFILES_FINDERS += [
'core.testutils.mock_staticfiles.MockStaticfilesFinder',
]
STATICFILES_DIRS += [
PROJECT_ROOT.child('core', 'testutils', 'staticfiles'),
]
MOCK_STATICFILES_PATTERNS = {
'icons/*.svg': 'icons/placeholder.svg',
}
FLAG_SOURCES = (
'flags.sources.SettingsFlagsSource',
)
# We use a custom MEDIA_ROOT for testing so that tests that create images and
# other files don't write them to the local development media directory. The
# test runner cleans up this directory after the tests run.
MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'cfgov', 'tests', 'test-media')
| [] | [] | [
"TEST_DATABASE_URL",
"TEST_RUNNER"
] | [] | ["TEST_DATABASE_URL", "TEST_RUNNER"] | python | 2 | 0 | |
cmd/virtualroutermanager/main.go | /*
Copyright 2017 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"flag"
"os"
"time"
kubeinformers "k8s.io/client-go/informers"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/klog/v2"
// Uncomment the following line to load the gcp plugin (only required to authenticate against GKE clusters).
// _ "k8s.io/client-go/plugin/pkg/client/auth/gcp"
clientset "github.com/tmax-cloud/virtualrouter-controller/internal/utils/pkg/generated/clientset/versioned"
informers "github.com/tmax-cloud/virtualrouter-controller/internal/utils/pkg/generated/informers/externalversions"
"github.com/tmax-cloud/virtualrouter-controller/internal/utils/pkg/signals"
c1 "github.com/tmax-cloud/virtualrouter-controller/internal/virtualroutermanager"
)
var (
masterURL string
kubeconfig string
)
func main() {
klog.InitFlags(nil)
flag.Parse()
// set up signals so we handle the first shutdown signal gracefully
stopCh := signals.SetupSignalHandler()
cfg, err := rest.InClusterConfig()
// ToDo: find out more graceful method
namespace := os.Getenv("POD_NAMESPACE")
// cfg, err := clientcmd.BuildConfigFromFlags(masterURL, kubeconfig)
// if err != nil {
// klog.Fatalf("Error building kubeconfig: %s", err.Error())
// }
kubeClient, err := kubernetes.NewForConfig(cfg)
if err != nil {
klog.Fatalf("Error building kubernetes clientset: %s", err.Error())
}
exampleClient, err := clientset.NewForConfig(cfg)
if err != nil {
klog.Fatalf("Error building example clientset: %s", err.Error())
}
kubeInformerFactory := kubeinformers.NewSharedInformerFactory(kubeClient, time.Second*30)
// exampleInformerFactory := informers.NewSharedInformerFactory(exampleClient, time.Second*30)
exampleInformerFactory := informers.NewFilteredSharedInformerFactory(exampleClient, time.Second*30, namespace, nil)
controller := c1.NewController(kubeClient, exampleClient,
kubeInformerFactory.Apps().V1().Deployments(),
exampleInformerFactory.Tmax().V1().VirtualRouters())
// notice that there is no need to run Start methods in a separate goroutine. (i.e. go kubeInformerFactory.Start(stopCh)
// Start method is non-blocking and runs all registered informers in a dedicated goroutine.
kubeInformerFactory.Start(stopCh)
exampleInformerFactory.Start(stopCh)
if err = controller.Run(2, stopCh); err != nil {
klog.Fatalf("Error running controller: %s", err.Error())
}
}
func init() {
flag.StringVar(&kubeconfig, "kubeconfig", "", "Path to a kubeconfig. Only required if out-of-cluster.")
flag.StringVar(&masterURL, "master", "", "The address of the Kubernetes API server. Overrides any value in kubeconfig. Only required if out-of-cluster.")
}
| [
"\"POD_NAMESPACE\""
] | [] | [
"POD_NAMESPACE"
] | [] | ["POD_NAMESPACE"] | go | 1 | 0 | |
pgxs/pgx.go | package pgxs
import (
"crypto/tls"
"fmt"
"github.com/jackc/pgconn"
"github.com/jackc/pgx/v4/pgxpool"
"go.uber.org/zap"
"os"
)
type Config struct {
DbUri string `json:"db_uri" yaml:"db_uri"`
MigrationsPath string `json:"migration_schemas" yaml:"migration_schemas"`
DataDir string `json:"data_dir" yaml:"data_dir"`
Host string `json:"host" yaml:"host"`
Port string `json:"port" yaml:"port"`
Name string `json:"name" yaml:"name"`
User string `json:"user" yaml:"user"`
Password string `json:"password" yaml:"password"`
SslMode string `json:"ssl_mode" yaml:"ssl_mode"`
TLS SSL `json:"tls" yaml:"tls"`
TLSConfig *tls.Config `json:"-" yaml:"-"`
}
type SSL struct {
Enabled bool `json:"enabled" yaml:"enabled"`
Verify bool `json:"verify" yaml:"verify"`
CaPath string `json:"ca" yaml:"ca"`
KeyPath string `json:"key" yaml:"key"`
CertPath string `json:"cert" yaml:"cert"`
}
func (c *Config) GetConnString() string {
dbUrl := os.Getenv("DB_URL")
if len(dbUrl) > 0 {
return dbUrl
}
connString := fmt.Sprintf("host=%s port=%s database=%s user=%s password=%s sslmode=%s",
c.Host,
c.Port,
c.Name,
c.User,
c.Password,
c.SslMode,
)
if len(c.TLS.CaPath) > 0 {
connString += fmt.Sprintf(" sslrootcert=%s", c.TLS.CaPath)
}
if len(c.TLS.CertPath) > 0 {
connString += fmt.Sprintf(" sslcert=%s", c.TLS.CertPath)
}
if len(c.TLS.KeyPath) > 0 {
connString += fmt.Sprintf(" sslkey=%s", c.TLS.KeyPath)
}
return connString
}
type Repo struct {
Logger *zap.SugaredLogger `json:"-" yaml:"-"`
Pool *pgxpool.Pool `json:"-" yaml:"-"`
Config *Config `json:"-" yaml:"-"`
}
func (db *Repo) GetConnConfig() (*pgconn.Config, error) {
c, err := pgconn.ParseConfig(db.Config.GetConnString())
if err != nil {
return nil, fmt.Errorf("pgxs: unable to parse pgx config: %s", err)
}
return c, nil
}
func (db *Repo) GetPoolConfig() (*pgxpool.Config, error) {
c, err := pgxpool.ParseConfig(db.Config.GetConnString())
if err != nil {
return nil, fmt.Errorf("pgxs: unable to parse pgx config: %s", err)
}
return c, nil
}
func (db *Repo) GracefulShutdown() {
if db.Pool != nil {
db.Pool.Close()
db.Logger.Infof("Successfully closed postgreSQL connection pool")
}
}
| [
"\"DB_URL\""
] | [] | [
"DB_URL"
] | [] | ["DB_URL"] | go | 1 | 0 | |
contrib/devtools/security-check.py | #!/usr/bin/env python
# Copyright (c) 2015-2018 The Bitcoin Core developers
# Copyright (c) 2017 The Raven Core developers
# Copyright (c) 2018 The Kimora Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
'''
Perform basic ELF security checks on a series of executables.
Exit status will be 0 if successful, and the program will be silent.
Otherwise the exit status will be 1 and it will log which executables failed which checks.
Needs `readelf` (for ELF) and `objdump` (for PE).
'''
from __future__ import division,print_function,unicode_literals
import subprocess
import sys
import os
READELF_CMD = os.getenv('READELF', '/usr/bin/readelf')
OBJDUMP_CMD = os.getenv('OBJDUMP', '/usr/bin/objdump')
NONFATAL = {'HIGH_ENTROPY_VA'} # checks which are non-fatal for now but only generate a warning
def check_ELF_PIE(executable):
'''
Check for position independent executable (PIE), allowing for address space randomization.
'''
p = subprocess.Popen([READELF_CMD, '-h', '-W', executable], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
(stdout, stderr) = p.communicate()
if p.returncode:
raise IOError('Error opening file')
ok = False
for line in stdout.split(b'\n'):
line = line.split()
if len(line)>=2 and line[0] == b'Type:' and line[1] == b'DYN':
ok = True
return ok
def get_ELF_program_headers(executable):
'''Return type and flags for ELF program headers'''
p = subprocess.Popen([READELF_CMD, '-l', '-W', executable], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
(stdout, stderr) = p.communicate()
if p.returncode:
raise IOError('Error opening file')
in_headers = False
count = 0
headers = []
for line in stdout.split(b'\n'):
if line.startswith(b'Program Headers:'):
in_headers = True
if line == b'':
in_headers = False
if in_headers:
if count == 1: # header line
ofs_typ = line.find(b'Type')
ofs_offset = line.find(b'Offset')
ofs_flags = line.find(b'Flg')
ofs_align = line.find(b'Align')
if ofs_typ == -1 or ofs_offset == -1 or ofs_flags == -1 or ofs_align == -1:
raise ValueError('Cannot parse elfread -lW output')
elif count > 1:
typ = line[ofs_typ:ofs_offset].rstrip()
flags = line[ofs_flags:ofs_align].rstrip()
headers.append((typ, flags))
count += 1
return headers
def check_ELF_NX(executable):
'''
Check that no sections are writable and executable (including the stack)
'''
have_wx = False
have_gnu_stack = False
for (typ, flags) in get_ELF_program_headers(executable):
if typ == b'GNU_STACK':
have_gnu_stack = True
if b'W' in flags and b'E' in flags: # section is both writable and executable
have_wx = True
return have_gnu_stack and not have_wx
def check_ELF_RELRO(executable):
'''
Check for read-only relocations.
GNU_RELRO program header must exist
Dynamic section must have BIND_NOW flag
'''
have_gnu_relro = False
for (typ, flags) in get_ELF_program_headers(executable):
# Note: not checking flags == 'R': here as linkers set the permission differently
# This does not affect security: the permission flags of the GNU_RELRO program header are ignored, the PT_LOAD header determines the effective permissions.
# However, the dynamic linker need to write to this area so these are RW.
# Glibc itself takes care of mprotecting this area R after relocations are finished.
# See also http://permalink.gmane.org/gmane.comp.gnu.binutils/71347
if typ == b'GNU_RELRO':
have_gnu_relro = True
have_bindnow = False
p = subprocess.Popen([READELF_CMD, '-d', '-W', executable], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
(stdout, stderr) = p.communicate()
if p.returncode:
raise IOError('Error opening file')
for line in stdout.split(b'\n'):
tokens = line.split()
if len(tokens)>1 and tokens[1] == b'(BIND_NOW)' or (len(tokens)>2 and tokens[1] == b'(FLAGS)' and b'BIND_NOW' in tokens[2]):
have_bindnow = True
return have_gnu_relro and have_bindnow
def check_ELF_Canary(executable):
'''
Check for use of stack canary
'''
p = subprocess.Popen([READELF_CMD, '--dyn-syms', '-W', executable], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
(stdout, stderr) = p.communicate()
if p.returncode:
raise IOError('Error opening file')
ok = False
for line in stdout.split(b'\n'):
if b'__stack_chk_fail' in line:
ok = True
return ok
def get_PE_dll_characteristics(executable):
'''
Get PE DllCharacteristics bits.
Returns a tuple (arch,bits) where arch is 'i386:x86-64' or 'i386'
and bits is the DllCharacteristics value.
'''
p = subprocess.Popen([OBJDUMP_CMD, '-x', executable], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
(stdout, stderr) = p.communicate()
if p.returncode:
raise IOError('Error opening file')
arch = ''
bits = 0
for line in stdout.split('\n'):
tokens = line.split()
if len(tokens)>=2 and tokens[0] == 'architecture:':
arch = tokens[1].rstrip(',')
if len(tokens)>=2 and tokens[0] == 'DllCharacteristics':
bits = int(tokens[1],16)
return (arch,bits)
IMAGE_DLL_CHARACTERISTICS_HIGH_ENTROPY_VA = 0x0020
IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE = 0x0040
IMAGE_DLL_CHARACTERISTICS_NX_COMPAT = 0x0100
def check_PE_DYNAMIC_BASE(executable):
'''PIE: DllCharacteristics bit 0x40 signifies dynamicbase (ASLR)'''
(arch,bits) = get_PE_dll_characteristics(executable)
reqbits = IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE
return (bits & reqbits) == reqbits
# On 64 bit, must support high-entropy 64-bit address space layout randomization in addition to DYNAMIC_BASE
# to have secure ASLR.
def check_PE_HIGH_ENTROPY_VA(executable):
'''PIE: DllCharacteristics bit 0x20 signifies high-entropy ASLR'''
(arch,bits) = get_PE_dll_characteristics(executable)
if arch == 'i386:x86-64':
reqbits = IMAGE_DLL_CHARACTERISTICS_HIGH_ENTROPY_VA
else: # Unnecessary on 32-bit
assert(arch == 'i386')
reqbits = 0
return (bits & reqbits) == reqbits
def check_PE_NX(executable):
'''NX: DllCharacteristics bit 0x100 signifies nxcompat (DEP)'''
(arch,bits) = get_PE_dll_characteristics(executable)
return (bits & IMAGE_DLL_CHARACTERISTICS_NX_COMPAT) == IMAGE_DLL_CHARACTERISTICS_NX_COMPAT
CHECKS = {
'ELF': [
('PIE', check_ELF_PIE),
('NX', check_ELF_NX),
('RELRO', check_ELF_RELRO),
('Canary', check_ELF_Canary)
],
'PE': [
('DYNAMIC_BASE', check_PE_DYNAMIC_BASE),
('HIGH_ENTROPY_VA', check_PE_HIGH_ENTROPY_VA),
('NX', check_PE_NX)
]
}
def identify_executable(executable):
with open(filename, 'rb') as f:
magic = f.read(4)
if magic.startswith(b'MZ'):
return 'PE'
elif magic.startswith(b'\x7fELF'):
return 'ELF'
return None
if __name__ == '__main__':
retval = 0
for filename in sys.argv[1:]:
try:
etype = identify_executable(filename)
if etype is None:
print('%s: unknown format' % filename)
retval = 1
continue
failed = []
warning = []
for (name, func) in CHECKS[etype]:
if not func(filename):
if name in NONFATAL:
warning.append(name)
else:
failed.append(name)
if failed:
print('%s: failed %s' % (filename, ' '.join(failed)))
retval = 1
if warning:
print('%s: warning %s' % (filename, ' '.join(warning)))
except IOError:
print('%s: cannot open' % filename)
retval = 1
sys.exit(retval)
| [] | [] | [
"OBJDUMP",
"READELF"
] | [] | ["OBJDUMP", "READELF"] | python | 2 | 0 | |
libs/mosquitto-1.4.14/test/lib/08-ssl-connect-no-auth.py | #!/usr/bin/env python
# Test whether a client produces a correct connect and subsequent disconnect when using SSL.
# The client should connect to port 1888 with keepalive=60, clean session set,
# and client id 08-ssl-connect-no-auth
# It should use the CA certificate ssl/test-ca.crt for verifying the server.
# The test will send a CONNACK message to the client with rc=0. Upon receiving
# the CONNACK and verifying that rc=0, the client should send a DISCONNECT
# message. If rc!=0, the client should exit with an error.
import inspect
import os
import socket
import ssl
import sys
# From http://stackoverflow.com/questions/279237/python-import-a-module-from-a-folder
cmd_subfolder = os.path.realpath(os.path.abspath(os.path.join(os.path.split(inspect.getfile( inspect.currentframe() ))[0],"..")))
if cmd_subfolder not in sys.path:
sys.path.insert(0, cmd_subfolder)
import mosq_test
if sys.version < '2.7':
print("WARNING: SSL not supported on Python 2.6")
exit(0)
rc = 1
keepalive = 60
connect_packet = mosq_test.gen_connect("08-ssl-connect-no-auth", keepalive=keepalive)
connack_packet = mosq_test.gen_connack(rc=0)
disconnect_packet = mosq_test.gen_disconnect()
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
ssock = ssl.wrap_socket(sock, ca_certs="../ssl/all-ca.crt", keyfile="../ssl/server.key", certfile="../ssl/server.crt", server_side=True, ssl_version=ssl.PROTOCOL_TLSv1)
ssock.settimeout(10)
ssock.bind(('', 1888))
ssock.listen(5)
client_args = sys.argv[1:]
env = dict(os.environ)
env['LD_LIBRARY_PATH'] = '../../lib:../../lib/cpp'
try:
pp = env['PYTHONPATH']
except KeyError:
pp = ''
env['PYTHONPATH'] = '../../lib/python:'+pp
client = mosq_test.start_client(filename=sys.argv[1].replace('/', '-'), cmd=client_args, env=env)
try:
(conn, address) = ssock.accept()
conn.settimeout(100)
if mosq_test.expect_packet(conn, "connect", connect_packet):
conn.send(connack_packet)
if mosq_test.expect_packet(conn, "disconnect", disconnect_packet):
rc = 0
conn.close()
finally:
client.terminate()
client.wait()
ssock.close()
exit(rc)
| [] | [] | [] | [] | [] | python | 0 | 0 | |
lang/einstein_v2.py | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import os
import re
import copy
import json
import numpy as np
# Tensor name: the first charactor must be lower case letter, and the following charactors must be within [a-zA-Z_]
# Axis name: the first charactor must be upper case letter, and the following charactors must be within [a-zA-Z]
full_tensor_dict = None
explicit_range = None
class OpTensor:
@staticmethod
def parse(other, output_dtype=None):
if isinstance(other, OpTensor):
return other.cast(output_dtype)
if output_dtype is not None:
return OpTensor('const', other, output_dtype)
if isinstance(other, int):
return OpTensor('const', other, 'int32')
if isinstance(other, float):
return OpTensor('const', other, 'float32')
raise Exception("Unrecognized const node type: %s" % type(other))
@staticmethod
def merge_dtype(first, second):
dtypes = (first._dtype, second._dtype)
ordered_dtypes = ['float64', 'float32', 'int32', 'int16', 'int8']
for _dtype in ordered_dtypes:
if _dtype in dtypes:
return _dtype
return first._dtype
def dtype(self):
return self._dtype
def val(self):
assert self._op == 'axis', "Only axis op can support value fetch for its range."
return OpTensor('axis_range', self._value, 'int32')
def __init__(self, _op, _value, _dtype):
self._op = _op
self._value = _value
self._dtype = _dtype
def __repr__(self):
return 'OpTensor{"%s", "%s", "%s"}' % (self._op, self._value, self._dtype)
def __getitem__(self, key):
if self._op != 'tensor':
raise Exception("The instance to access its dim values must be a tensor array.")
key = list(key if isinstance(key, tuple) else (key, ))
for i in range(len(key)):
key[i] = OpTensor.parse(key[i])
it = key[i]
if it._op == 'axis' and explicit_range[it._value] is None:
explicit_range[it._value] = full_tensor_dict[self._value]['shape'][i]
return OpTensor('get_item', {"tensor": self, "index": key}, self._dtype)
# Calculation Ops
def __mul__(self, other):
other = OpTensor.parse(other)
output_dtype = OpTensor.merge_dtype(self, other)
if other._op == 'const' and other._value == 1:
return self.cast(output_dtype)
if self._op == 'const' and self._value == 1:
return other.cast(output_dtype)
return OpTensor('op', {"name": "*", "inputs": [self.cast(output_dtype), other.cast(output_dtype)]}, output_dtype)
def __rmul__(self, other):
other = OpTensor.parse(other)
return other.__mul__(self)
def __truediv__(self, other):
other = OpTensor.parse(other)
op_name = '//' if self._dtype == 'int32' and other._dtype == 'int32' else '/'
output_dtype = OpTensor.merge_dtype(self, other)
if other._op == 'const' and other._value == 1:
return self.cast(output_dtype)
if other._op == 'const' and self._op == 'axis':
if self._value in explicit_range and explicit_range[self._value] is not None:
if op_name == '//' and explicit_range[self._value] < other._value:
return OpTensor.parse(0, output_dtype)
return OpTensor('op', {"name": op_name, "inputs": [self, other]}, output_dtype)
def __rtruediv__(self, other):
other = OpTensor.parse(other)
return other.__truediv__(self)
def __floordiv__(self, other):
other = OpTensor.parse(other)
return self.__truediv__(other)
def __rfloordiv__(self, other):
other = OpTensor.parse(other)
return other.__floordiv__(self)
def __mod__(self, other):
other = OpTensor.parse(other)
if other._op == 'const':
assert other._dtype == 'int32'
if other._value == 1:
return OpTensor.parse(0, self._dtype)
if self._op == 'axis':
assert self._value in explicit_range and explicit_range[self._value] is not None
if explicit_range[self._value] <= other._value:
return self
return OpTensor('op', {"name": "%", "inputs": [self, other]}, self._dtype)
def __add__(self, other):
other = OpTensor.parse(other)
output_dtype = OpTensor.merge_dtype(self, other)
if other._op == 'const' and other._value == 0:
return self.cast(output_dtype)
if self._op == 'const' and self._value == 0:
return other.cast(output_dtype)
return OpTensor('op', {"name": "+", "inputs": [self.cast(output_dtype), other.cast(output_dtype)]}, output_dtype)
def __radd__(self, other):
other = OpTensor.parse(other)
return other.__add__(self)
def __sub__(self, other):
other = OpTensor.parse(other)
output_dtype = OpTensor.merge_dtype(self, other)
if other._op == 'const' and other._value == 0:
return self.cast(output_dtype)
return OpTensor('op', {"name": "-", "inputs": [self.cast(output_dtype), other.cast(output_dtype)]}, output_dtype)
def __rsub__(self, other):
other = OpTensor.parse(other)
return other.__sub__(self)
def __neg__(self):
return OpTensor.parse(0, self._dtype).__sub__(self)
# Relation Ops
def __lt__ (self, other):
other = OpTensor.parse(other)
return OpTensor('op', {"name": "<", "inputs": [self, other]}, 'int8')
def __le__ (self, other):
other = OpTensor.parse(other)
return OpTensor('op', {"name": "<=", "inputs": [self, other]}, 'int8')
def __gt__ (self, other):
other = OpTensor.parse(other)
return OpTensor('op', {"name": "<", "inputs": [other, self]}, 'int8')
def __ge__ (self, other):
other = OpTensor.parse(other)
return OpTensor('op', {"name": "<=", "inputs": [other, self]}, 'int8')
def __eq__ (self, other):
other = OpTensor.parse(other)
return OpTensor('op', {"name": "==", "inputs": [self, other]}, 'int8')
def __ne__ (self, other):
other = OpTensor.parse(other)
return OpTensor('op', {"name": "!=", "inputs": [self, other]}, 'int8')
def __and__(self, other):
other = OpTensor.parse(other)
return OpTensor('op', {"name": "&", "inputs": [self, other]}, 'int8')
def __or__(self, other):
other = OpTensor.parse(other)
return OpTensor('op', {"name": "|", "inputs": [self, other]}, 'int8')
def __invert__(self):
return OpTensor('op', {"name": "~", "inputs": [self]}, 'int8')
# Special Ops
def cast(self, output_dtype):
if output_dtype is None or self._dtype == output_dtype:
return self
return OpTensor('cast', {"inputs": [self]}, output_dtype)
def call(self, func_name, others=None, output_dtype=None):
if others is None:
others = []
for i in range(len(others)):
others[i] = OpTensor.parse(others[i])
if output_dtype is None:
output_dtype = self._dtype
return OpTensor('call', {"name": func_name, "inputs": [self] + others}, output_dtype)
def when(self, conditions, other, merge_op='all'):
other = OpTensor.parse(other)
assert self._dtype == other._dtype or '@' in self._dtype or '@' in other._dtype, "Conditional true and false values must have same datatype (%s v.s. %s)" % (self._dtype, other._dtype)
conditions = conditions if isinstance(conditions, list) else [conditions]
for cond in conditions:
assert cond._dtype == 'int8', 'Each condition in when statement must be boolean(int8) type, get: %s' % cond._dtype
return OpTensor('when', {"if": conditions, "true": self, "false": other, "merge_op": merge_op}, self._dtype)
def parse_to_ast(expr):
global full_tensor_dict
expr = expr.strip().replace('`', '"').replace('\'', '"')
if re.search('\[ *\]', expr):
expr = re.sub('\[ *\]', '[0]', expr)
if expr.rfind('where') == -1:
expr += ' where Scaler in 1'
else:
expr += ', Scaler in 1'
at_index = expr.rfind(' where ')
if at_index != -1:
range_desc = expr[at_index + len(' where '):]
expr = expr[:at_index]
else:
range_desc = ''
# Parse compute axes & init axis nodes
global explicit_range
explicit_range = {}
brac_st = False
for i in range(len(expr)):
if expr[i] == '"':
brac_st = not brac_st
continue
if i < 1 or brac_st:
continue
if expr[i].isupper() and (not expr[i - 1].isalpha()) and (not expr[i - 1].isdigit()) and (expr[i - 1] != '_'):
for j in range(i, len(expr) + 1):
if j == len(expr) or (not expr[j].isalpha() and not expr[j].isdigit()):
ax_name = expr[i:j]
break
if ax_name not in explicit_range:
explicit_range[ax_name] = None
exec("_id = OpTensor('axis', '_id', 'int32')")
for k in explicit_range:
exec("%s = OpTensor('axis', k, 'int32')" % k)
# Parse where clause
for x in range_desc.split(','):
x = x.strip()
if not x:
continue
k, v = x.split(' in ')
explicit_range[k.strip()] = int(v.strip())
# Parse compute set-op, get lval & rval
props = {'data_axes': [], 'reduce_axes': [], 'input_dict': None, 'output_name': None, 'reduce_type': None}
at_index = expr.find('=')
if expr[at_index - 1] != ' ':
if expr[at_index - 1] in ('<', '>', '+'):
props['reduce_type'] = expr[at_index - 1]
lval = expr[:at_index - 1].strip()
else:
blank_index = expr.find(' ', 0, at_index)
assert blank_index > 0, "Illegal reduce naming in equation near: `L-value <reduce_type>=`"
props['reduce_type'] = expr[blank_index + 1:at_index]
lval = expr[:blank_index].strip()
else:
lval = expr[:at_index].strip()
if expr[at_index + 1] == '!':
assert(props['reduce_type'] is not None)
rval = expr[at_index + 2:].strip()
else:
rval = expr[at_index + 1:].strip()
# Distinguish data/reduce axes according to lval
for x in lval[lval.index('[') + 1:lval.rindex(']')].split(','):
x = x.strip()
if x == '0':
x = 'Scaler'
props['data_axes'].append(x)
for x in explicit_range:
if x not in props['data_axes']:
props['reduce_axes'].append(x)
for input_name in full_tensor_dict:
if not input_name[0].islower():
raise Exception("Tensor variable name must start with lower case letter: %s" % input_name)
exec('%s = OpTensor("tensor", input_name, "%s")' % (input_name, full_tensor_dict[input_name]["dtype"]))
# Build ast according to rval & fill uncertain axis range
_root = eval(rval)
for x in explicit_range:
if explicit_range[x] is None:
raise Exception("The range of axis `%s` is undeterminzed, please use `where` clause to set the range explicitly." % x)
# Collect output inferences
props['data_axes'] = [{'name': x, 'range': explicit_range[x]} for x in props['data_axes']]
props['reduce_axes'] = [{'name': x, 'range': explicit_range[x]} for x in props['reduce_axes']]
output_name = lval[:lval.index('[')].strip()
props['output_name'] = output_name
ast = {'props': props, 'root': _root}
input_names = set()
def scan_items(root, ancestor, input_names):
if root._op != 'get_item':
return
input_names.add(root._value['tensor']._value)
walk_in_ast(ast, 'root', scan_items, [input_names,])
local_input_dict = {}
for name in input_names:
local_input_dict[name] = full_tensor_dict[name]
props['input_dict'] = local_input_dict
return ast
def const(other):
return OpTensor.parse(other)
def warp_axis(ax_name):
assert(ax_name[0].isupper() or ax_name == '_id')
return ax_name
def emit_antares_ir(ast, primal=False, tensor_remap=dict()):
primal_ids = {"axis_id": 0, "tensor_id": 0}
axis_dict, tensor_dict = {}, {}
dummy_range = set()
def _emit(node):
if node._op == 'const':
return 'const(%s)' % node._value
elif node._op == 'axis':
_value = node._value
if primal:
if _value not in axis_dict:
axis_dict[_value] = '$X%d' % primal_ids['axis_id']
primal_ids['axis_id'] += 1
_value = axis_dict[_value]
if hasattr(node, '_func'):
return node._func(_value)
return _value
elif node._op == 'op':
if len(node._value['inputs']) == 2:
return '(%s %s %s)' % (_emit(node._value['inputs'][0]), node._value['name'], _emit(node._value['inputs'][1]))
raise
elif node._op == 'get_item':
_value = node._value['tensor']._value
_value = tensor_remap.get(_value, _value)
if primal:
if _value not in tensor_dict:
tensor_dict[_value] = '$i%d' % primal_ids['tensor_id']
primal_ids['tensor_id'] += 1
_value = tensor_dict[_value]
for i, ch in enumerate(node._value['index']):
if ch._op != 'axis':
continue
input_size = ast['props']['input_dict'][node._value['tensor']._value]['shape'][i]
access_size = [x['range'] for x in (ast['props']['data_axes'] + ast['props']['reduce_axes']) if x['name'] == ch._value][0]
if input_size == access_size:
dummy_range.add(ch._value)
return '%s[%s]' % (_value, ', '.join([_emit(x) for x in node._value['index']]))
elif node._op == 'call':
if len(node._value['inputs']) == 1:
return '(%s).call(`%s`, dtype=`%s`)' % (_emit(node._value['inputs'][0]), node._value['name'], node._dtype)
return '(%s).call(`%s`, [%s], dtype=`%s`)' % (_emit(node._value['inputs'][0]), node._value['name'], ', '.join([_emit(x) for x in node._value['inputs'][1:]]), node._dtype)
elif node._op == 'when':
if len(node._value['if']) == 0:
return '(%s)' % _emit(node._value['true'])
return '(%s).when([%s], %s, merge_op="%s")' % (_emit(node._value['true']), ', '.join([_emit(x) for x in node._value['if']]), _emit(node._value['false']), node._value['merge_op'])
elif node._op == 'cast':
return '(%s).cast(`%s`)' % (_emit(node._value['inputs'][0]), node._dtype)
else:
raise Exception("Emit Antares IR: Unhanled reverse-emit op type: %s" % node._op)
_value = ast['props']['output_name']
_value = tensor_remap.get(_value, _value)
output_name = '$o0' if primal else _value
lval = '%s[%s]' % (output_name, ', '.join([x['name'] for x in ast['props']['data_axes']]))
body = _emit(ast['root'])
comp_type = '%s=%s' % (ast['props']['reduce_type'] if ast['props']['reduce_type'] else '', '!' if ast['props']['reduce_type'] else '')
explicit_axes = [x for x in ast['props']['data_axes'] + ast['props']['reduce_axes'] if x['name'] not in dummy_range]
if len(explicit_axes) > 0:
return '%s %s %s where %s' % (lval, comp_type, body, ', '.join(['%s in %d' % (x['name'], x['range']) for x in explicit_axes]))
else:
return '%s %s %s' % (lval, comp_type, body)
def emit_tvm_body(node, props):
if node._op == 'const':
return 'tir.const(%s, dtype="%s")' % (node._value, node._dtype)
elif node._op == 'axis_range':
return 'tir.const(%s, dtype="%s")' % (explicit_range[node._value], node._dtype)
elif node._op == 'get_item':
tensor = node._value['tensor']
index = node._value['index']
_str = tensor._value + '['
if len(index) > 0:
for i, it in enumerate(index):
_str += emit_tvm_body(it, props) + ', '
_str = _str[:-2] + ']'
return _str
elif node._op == 'axis':
axis_name = warp_axis(node._value)
if hasattr(node, '_func'):
axis_name = node._func(axis_name)
return axis_name
elif node._op == 'op':
op_name = node._value["name"]
op_input_size = len(node._value["inputs"])
if op_name in ('&', '|', '~'):
if op_name == '&':
return 'te.all(' + emit_tvm_body(node._value["inputs"][0], props) + '.astype("bool"), ' + emit_tvm_body(node._value["inputs"][1], props) + '.astype("bool"))'
elif op_name == '|':
return 'te.any(' + emit_tvm_body(node._value["inputs"][0], props) + '.astype("bool"), ' + emit_tvm_body(node._value["inputs"][1], props) + '.astype("bool"))'
else:
return '(' + emit_tvm_body(node._value["inputs"][0], props) + ' == 0)'
elif op_input_size == 2:
return '(' + emit_tvm_body(node._value["inputs"][0], props) + ' ' + op_name + ' ' + emit_tvm_body(node._value["inputs"][1], props) + ')'
elif op_input_size == 1:
return '(' + op_name + emit_tvm_body(node._value["inputs"][0], props) + ')'
else:
raise Exception('Unrecognized op type: %s[%d]' % (op_name, op_input_size))
elif node._op == 'cast':
return '%s.astype(cast_dtype("%s"))' % (emit_tvm_body(node._value["inputs"][0], props), node._dtype)
elif node._op == 'call':
return 'tir.call_pure_extern(cast_dtype("%s"), "%s", %s)' % (node._dtype, node._value['name'], ', '.join([emit_tvm_body(x, props) for x in node._value["inputs"]]))
elif node._op == 'when':
all_conds = [emit_tvm_body(cond, props) for cond in node._value['if']]
return 'tir.if_then_else(te.%s(' % node._value['merge_op'] + ', '.join(all_conds) + '), t=' + emit_tvm_body(node._value['true'], props) + ', f=' + emit_tvm_body(node._value['false'], props) + ')'
else:
raise Exception('Unrecognized node type: %s' % node._op)
def walk_in_ast(parent, attr_id, func, args):
node = getattr(parent, attr_id) if isinstance(parent, OpTensor) else parent[attr_id]
def _walk(node, parent, attr_id):
updated_node = func(node, (parent, attr_id), *args)
if updated_node is not None:
if isinstance(updated_node, str) and updated_node == '':
return
updated_node = copy.deepcopy(updated_node)
if isinstance(parent, OpTensor):
setattr(parent, attr_id, updated_node)
else:
parent[attr_id] = updated_node
return
if node._op == 'get_item':
for i, ch in enumerate(node._value['index']):
_walk(ch, node._value['index'], i)
elif node._op in ['op', 'call', 'cast']:
for i, ch in enumerate(node._value['inputs']):
_walk(ch, node._value['inputs'], i)
elif node._op == 'when':
for i, ch in enumerate(node._value['if']):
_walk(ch, node._value['if'], i)
_walk(node._value['true'], node._value, 'true')
_walk(node._value['false'], node._value, 'false')
elif node._op in ['axis', 'const', 'axis_range']:
pass
else:
raise Exception('Unhandled node type in walk_in_ast(): %s' % node._op)
_walk(node, parent, attr_id)
def ir_graph_parser(exprss, input_dict, extra_outputs):
statements = [s_.strip() for s_ in exprss.split(';')]
global full_tensor_dict
full_tensor_dict = copy.deepcopy(input_dict)
output_dict = {}
ast_seq = []
for s in statements:
if not s:
continue
ast = parse_to_ast(s)
k = ast['props']['output_name']
ast_outputs_dict = {k: {"shape": [x['range'] for x in ast['props']['data_axes']], "dtype": ast['root']._dtype}}
full_tensor_dict[k] = ast_outputs_dict[k]
if k in extra_outputs:
output_dict[k] = ast_outputs_dict[k]
ast_seq.append(ast)
os.environ['MEDIATE_TENSORS'] = json.dumps(full_tensor_dict)
# Also include the last output
if k not in extra_outputs:
output_dict[k] = ast_outputs_dict[k]
# Registry Global Argument Properties
arg_props = {'_in': [], '_out': []}
for k in input_dict:
prop = copy.deepcopy(input_dict[k])
prop['name'] = k
arg_props['_in'].append(prop)
for k in output_dict:
prop = copy.deepcopy(output_dict[k])
prop['name'] = k
arg_props['_out'].append(prop)
arg_props['_in'].sort(key=lambda x: x['name'])
arg_props['_out'].sort(key=lambda x: x['name'])
from antares.common import AntaresGlobal
AntaresGlobal.global_arg_pros = arg_props
import importlib
passes = os.listdir('lang/pass')
passes.sort()
for pas in passes:
if pas.endswith('.py'):
pass_stage = importlib.import_module('lang.pass.%s' % pas[:-3])
pass_stage.run_pass_v2(ast_seq, input_dict, output_dict)
from antares.common import AntaresGlobal
AntaresGlobal.compute_graph = ast_seq, input_dict, output_dict
# Generate LL_IR body for ast_seq
def emit_input_body(input_dict):
input_body = '_id = input("_id", [1], dtype="int32")[0]; '
for key in input_dict:
input_info = input_dict[key]
input_body += '%s = input("%s", %s, dtype="%s"); ' % (key, key, input_info['shape'], input_info['dtype'])
return input_body
def emit_reduce_body(ast):
reduce_body, reduce_set = '', []
props = ast['props']
if props['reduce_axes']:
for x in props['reduce_axes']:
axis_name = warp_axis(x['name'])
reduce_set.append(axis_name)
reduce_body += '%s = loop(%d, name="%s"); ' % (axis_name, x['range'], axis_name)
reduce_maps = {'+': 'te.sum', '>': 'te.max', '<': 'te.min'}
if props['reduce_type'] in reduce_maps:
reduce_func = reduce_maps[props['reduce_type']]
else:
spec_idx = props['reduce_type'].find('(')
if spec_idx >= 0:
reduce_func = 'common_reduce("%s", %s)' % (props['reduce_type'][:spec_idx], props['reduce_type'][spec_idx:])
else:
reduce_func = 'common_reduce("%s")' % props['reduce_type']
reduce_pattern = '%s(' % reduce_func + '%s' + ', axis=[%s])' % ', '.join(reduce_set)
else:
reduce_pattern = '%s'
return reduce_body, reduce_pattern
def emit_output_body(ast, reduce_pattern):
root, props = ast['root'], ast['props']
output_shape = [x['range'] for x in props['data_axes']]
output_name = props['output_name']
output_begin = '%s = output(shape=%s, func=lambda %s: ' % (output_name, output_shape, ', '.join([warp_axis(x['name']) for x in props['data_axes']]))
basic_body = emit_tvm_body(root, props)
output_end = ', dtype="%s", tag="%s", name="%s", final_output=%s); ' % (root._dtype, '', output_name, output_name in output_dict)
return output_begin + reduce_pattern % basic_body + output_end
ll_irs = [emit_input_body(input_dict)]
for ast in ast_seq:
loops_def, pattern = emit_reduce_body(ast)
ll_irs.append(loops_def + emit_output_body(ast, pattern))
return '\n'.join(ll_irs)
| [] | [] | [
"MEDIATE_TENSORS"
] | [] | ["MEDIATE_TENSORS"] | python | 1 | 0 | |
script/release/uploaders/upload.py | #!/usr/bin/env python3
from __future__ import print_function
import argparse
import datetime
import hashlib
import json
import mmap
import os
import shutil
import subprocess
from struct import Struct
import sys
sys.path.append(
os.path.abspath(os.path.dirname(os.path.abspath(__file__)) + "/../.."))
from zipfile import ZipFile
from lib.config import PLATFORM, get_target_arch, \
get_zip_name, enable_verbose_mode, get_platform_key
from lib.util import get_electron_branding, execute, get_electron_version, \
store_artifact, get_electron_exec, get_out_dir, \
SRC_DIR, ELECTRON_DIR, TS_NODE
ELECTRON_VERSION = get_electron_version()
PROJECT_NAME = get_electron_branding()['project_name']
PRODUCT_NAME = get_electron_branding()['product_name']
OUT_DIR = get_out_dir()
DIST_NAME = get_zip_name(PROJECT_NAME, ELECTRON_VERSION)
SYMBOLS_NAME = get_zip_name(PROJECT_NAME, ELECTRON_VERSION, 'symbols')
DSYM_NAME = get_zip_name(PROJECT_NAME, ELECTRON_VERSION, 'dsym')
DSYM_SNAPSHOT_NAME = get_zip_name(PROJECT_NAME, ELECTRON_VERSION,
'dsym-snapshot')
PDB_NAME = get_zip_name(PROJECT_NAME, ELECTRON_VERSION, 'pdb')
DEBUG_NAME = get_zip_name(PROJECT_NAME, ELECTRON_VERSION, 'debug')
TOOLCHAIN_PROFILE_NAME = get_zip_name(PROJECT_NAME, ELECTRON_VERSION,
'toolchain-profile')
CXX_OBJECTS_NAME = get_zip_name(PROJECT_NAME, ELECTRON_VERSION,
'libcxx_objects')
def main():
args = parse_args()
if args.verbose:
enable_verbose_mode()
if args.upload_to_storage:
utcnow = datetime.datetime.utcnow()
args.upload_timestamp = utcnow.strftime('%Y%m%d')
build_version = get_electron_build_version()
if not ELECTRON_VERSION.startswith(build_version):
error = 'Tag name ({0}) should match build version ({1})\n'.format(
ELECTRON_VERSION, build_version)
sys.stderr.write(error)
sys.stderr.flush()
return 1
tag_exists = False
release = get_release(args.version)
if not release['draft']:
tag_exists = True
if not args.upload_to_storage:
assert release['exists'], \
'Release does not exist; cannot upload to GitHub!'
assert tag_exists == args.overwrite, \
'You have to pass --overwrite to overwrite a published release'
# Upload Electron files.
# Rename dist.zip to get_zip_name('electron', version, suffix='')
electron_zip = os.path.join(OUT_DIR, DIST_NAME)
shutil.copy2(os.path.join(OUT_DIR, 'dist.zip'), electron_zip)
upload_electron(release, electron_zip, args)
if get_target_arch() != 'mips64el':
symbols_zip = os.path.join(OUT_DIR, SYMBOLS_NAME)
shutil.copy2(os.path.join(OUT_DIR, 'symbols.zip'), symbols_zip)
upload_electron(release, symbols_zip, args)
if PLATFORM == 'darwin':
if get_platform_key() == 'darwin' and get_target_arch() == 'x64':
api_path = os.path.join(ELECTRON_DIR, 'electron-api.json')
upload_electron(release, api_path, args)
ts_defs_path = os.path.join(ELECTRON_DIR, 'electron.d.ts')
upload_electron(release, ts_defs_path, args)
dsym_zip = os.path.join(OUT_DIR, DSYM_NAME)
shutil.copy2(os.path.join(OUT_DIR, 'dsym.zip'), dsym_zip)
upload_electron(release, dsym_zip, args)
dsym_snaphot_zip = os.path.join(OUT_DIR, DSYM_SNAPSHOT_NAME)
shutil.copy2(os.path.join(OUT_DIR, 'dsym-snapshot.zip'), dsym_snaphot_zip)
upload_electron(release, dsym_snaphot_zip, args)
elif PLATFORM == 'win32':
pdb_zip = os.path.join(OUT_DIR, PDB_NAME)
shutil.copy2(os.path.join(OUT_DIR, 'pdb.zip'), pdb_zip)
upload_electron(release, pdb_zip, args)
elif PLATFORM == 'linux':
debug_zip = os.path.join(OUT_DIR, DEBUG_NAME)
shutil.copy2(os.path.join(OUT_DIR, 'debug.zip'), debug_zip)
upload_electron(release, debug_zip, args)
# Upload libcxx_objects.zip for linux only
libcxx_objects = get_zip_name('libcxx-objects', ELECTRON_VERSION)
libcxx_objects_zip = os.path.join(OUT_DIR, libcxx_objects)
shutil.copy2(os.path.join(OUT_DIR, 'libcxx_objects.zip'),
libcxx_objects_zip)
upload_electron(release, libcxx_objects_zip, args)
# Upload headers.zip and abi_headers.zip as non-platform specific
if get_target_arch() == "x64":
cxx_headers_zip = os.path.join(OUT_DIR, 'libcxx_headers.zip')
upload_electron(release, cxx_headers_zip, args)
abi_headers_zip = os.path.join(OUT_DIR, 'libcxxabi_headers.zip')
upload_electron(release, abi_headers_zip, args)
# Upload free version of ffmpeg.
ffmpeg = get_zip_name('ffmpeg', ELECTRON_VERSION)
ffmpeg_zip = os.path.join(OUT_DIR, ffmpeg)
ffmpeg_build_path = os.path.join(SRC_DIR, 'out', 'ffmpeg', 'ffmpeg.zip')
shutil.copy2(ffmpeg_build_path, ffmpeg_zip)
upload_electron(release, ffmpeg_zip, args)
chromedriver = get_zip_name('chromedriver', ELECTRON_VERSION)
chromedriver_zip = os.path.join(OUT_DIR, chromedriver)
shutil.copy2(os.path.join(OUT_DIR, 'chromedriver.zip'), chromedriver_zip)
upload_electron(release, chromedriver_zip, args)
mksnapshot = get_zip_name('mksnapshot', ELECTRON_VERSION)
mksnapshot_zip = os.path.join(OUT_DIR, mksnapshot)
if get_target_arch().startswith('arm') and PLATFORM != 'darwin':
# Upload the x64 binary for arm/arm64 mksnapshot
mksnapshot = get_zip_name('mksnapshot', ELECTRON_VERSION, 'x64')
mksnapshot_zip = os.path.join(OUT_DIR, mksnapshot)
shutil.copy2(os.path.join(OUT_DIR, 'mksnapshot.zip'), mksnapshot_zip)
upload_electron(release, mksnapshot_zip, args)
if PLATFORM == 'linux' and get_target_arch() == 'x64':
# Upload the hunspell dictionaries only from the linux x64 build
hunspell_dictionaries_zip = os.path.join(
OUT_DIR, 'hunspell_dictionaries.zip')
upload_electron(release, hunspell_dictionaries_zip, args)
if not tag_exists and not args.upload_to_storage:
# Upload symbols to symbol server.
run_python_upload_script('upload-symbols.py')
if PLATFORM == 'win32':
run_python_upload_script('upload-node-headers.py', '-v', args.version)
if PLATFORM == 'win32':
toolchain_profile_zip = os.path.join(OUT_DIR, TOOLCHAIN_PROFILE_NAME)
with ZipFile(toolchain_profile_zip, 'w') as myzip:
myzip.write(
os.path.join(OUT_DIR, 'windows_toolchain_profile.json'),
'toolchain_profile.json')
upload_electron(release, toolchain_profile_zip, args)
return 0
def parse_args():
parser = argparse.ArgumentParser(description='upload distribution file')
parser.add_argument('-v', '--version', help='Specify the version',
default=ELECTRON_VERSION)
parser.add_argument('-o', '--overwrite',
help='Overwrite a published release',
action='store_true')
parser.add_argument('-p', '--publish-release',
help='Publish the release',
action='store_true')
parser.add_argument('-s', '--upload_to_storage',
help='Upload assets to azure bucket',
dest='upload_to_storage',
action='store_true',
default=False,
required=False)
parser.add_argument('--verbose',
action='store_true',
help='Mooooorreee logs')
return parser.parse_args()
def run_python_upload_script(script, *args):
script_path = os.path.join(
ELECTRON_DIR, 'script', 'release', 'uploaders', script)
print(execute([sys.executable, script_path] + list(args)))
def get_electron_build_version():
if get_target_arch().startswith('arm') or 'CI' in os.environ:
# In CI we just build as told.
return ELECTRON_VERSION
electron = get_electron_exec()
return subprocess.check_output([electron, '--version']).strip()
class NonZipFileError(ValueError):
"""Raised when a given file does not appear to be a zip"""
def zero_zip_date_time(fname):
""" Wrap strip-zip zero_zip_date_time within a file opening operation """
try:
with open(fname, 'r+b') as f:
_zero_zip_date_time(f)
except Exception:
# pylint: disable=W0707
raise NonZipFileError(fname)
def _zero_zip_date_time(zip_):
def purify_extra_data(mm, offset, length, compressed_size=0):
extra_header_struct = Struct("<HH")
# 0. id
# 1. length
STRIPZIP_OPTION_HEADER = 0xFFFF
EXTENDED_TIME_DATA = 0x5455
# Some sort of extended time data, see
# ftp://ftp.info-zip.org/pub/infozip/src/zip30.zip ./proginfo/extrafld.txt
# fallthrough
UNIX_EXTRA_DATA = 0x7875
# Unix extra data; UID / GID stuff, see
# ftp://ftp.info-zip.org/pub/infozip/src/zip30.zip ./proginfo/extrafld.txt
ZIP64_EXTRA_HEADER = 0x0001
zip64_extra_struct = Struct("<HHQQ")
# ZIP64.
# When a ZIP64 extra field is present his 8byte length
# will override the 4byte length defined in canonical zips.
# This is in the form:
# - 0x0001 (header_id)
# - 0x0010 [16] (header_length)
# - ... (8byte uncompressed_length)
# - ... (8byte compressed_length)
mlen = offset + length
while offset < mlen:
values = list(extra_header_struct.unpack_from(mm, offset))
_, header_length = values
extra_struct = Struct("<HH" + "B" * header_length)
values = list(extra_struct.unpack_from(mm, offset))
header_id, header_length = values[:2]
if header_id in (EXTENDED_TIME_DATA, UNIX_EXTRA_DATA):
values[0] = STRIPZIP_OPTION_HEADER
for i in range(2, len(values)):
values[i] = 0xff
extra_struct.pack_into(mm, offset, *values)
if header_id == ZIP64_EXTRA_HEADER:
assert header_length == 16
values = list(zip64_extra_struct.unpack_from(mm, offset))
header_id, header_length, _, compressed_size = values
offset += extra_header_struct.size + header_length
return compressed_size
FILE_HEADER_SIGNATURE = 0x04034b50
CENDIR_HEADER_SIGNATURE = 0x02014b50
archive_size = os.fstat(zip_.fileno()).st_size
signature_struct = Struct("<L")
local_file_header_struct = Struct("<LHHHHHLLLHH")
# 0. L signature
# 1. H version_needed
# 2. H gp_bits
# 3. H compression_method
# 4. H last_mod_time
# 5. H last_mod_date
# 6. L crc32
# 7. L compressed_size
# 8. L uncompressed_size
# 9. H name_length
# 10. H extra_field_length
central_directory_header_struct = Struct("<LHHHHHHLLLHHHHHLL")
# 0. L signature
# 1. H version_made_by
# 2. H version_needed
# 3. H gp_bits
# 4. H compression_method
# 5. H last_mod_time
# 6. H last_mod_date
# 7. L crc32
# 8. L compressed_size
# 9. L uncompressed_size
# 10. H file_name_length
# 11. H extra_field_length
# 12. H file_comment_length
# 13. H disk_number_start
# 14. H internal_attr
# 15. L external_attr
# 16. L rel_offset_local_header
offset = 0
mm = mmap.mmap(zip_.fileno(), 0)
while offset < archive_size:
if signature_struct.unpack_from(mm, offset) != (FILE_HEADER_SIGNATURE,):
break
values = list(local_file_header_struct.unpack_from(mm, offset))
compressed_size, _, name_length, extra_field_length = values[7:11]
# reset last_mod_time
values[4] = 0
# reset last_mod_date
values[5] = 0x21
local_file_header_struct.pack_into(mm, offset, *values)
offset += local_file_header_struct.size + name_length
if extra_field_length != 0:
compressed_size = purify_extra_data(mm, offset, extra_field_length,
compressed_size)
offset += compressed_size + extra_field_length
while offset < archive_size:
if signature_struct.unpack_from(mm, offset) != (CENDIR_HEADER_SIGNATURE,):
break
values = list(central_directory_header_struct.unpack_from(mm, offset))
file_name_length, extra_field_length, file_comment_length = values[10:13]
# reset last_mod_time
values[5] = 0
# reset last_mod_date
values[6] = 0x21
central_directory_header_struct.pack_into(mm, offset, *values)
offset += central_directory_header_struct.size
offset += file_name_length + extra_field_length + file_comment_length
if extra_field_length != 0:
purify_extra_data(mm, offset - extra_field_length, extra_field_length)
if offset == 0:
raise NonZipFileError(zip_.name)
def upload_electron(release, file_path, args):
filename = os.path.basename(file_path)
# Strip zip non determinism before upload, in-place operation
try:
zero_zip_date_time(file_path)
except NonZipFileError:
pass
# if upload_to_storage is set, skip github upload.
# todo (vertedinde): migrate this variable to upload_to_storage
if args.upload_to_storage:
key_prefix = 'release-builds/{0}_{1}'.format(args.version,
args.upload_timestamp)
store_artifact(os.path.dirname(file_path), key_prefix, [file_path])
upload_sha256_checksum(args.version, file_path, key_prefix)
return
# Upload the file.
upload_io_to_github(release, filename, file_path, args.version)
# Upload the checksum file.
upload_sha256_checksum(args.version, file_path)
def upload_io_to_github(release, filename, filepath, version):
print('Uploading %s to Github' % \
(filename))
script_path = os.path.join(
ELECTRON_DIR, 'script', 'release', 'uploaders', 'upload-to-github.ts')
execute([TS_NODE, script_path, filepath, filename, str(release['id']),
version])
def upload_sha256_checksum(version, file_path, key_prefix=None):
checksum_path = '{}.sha256sum'.format(file_path)
if key_prefix is None:
key_prefix = 'checksums-scratchpad/{0}'.format(version)
sha256 = hashlib.sha256()
with open(file_path, 'rb') as f:
sha256.update(f.read())
filename = os.path.basename(file_path)
with open(checksum_path, 'w') as checksum:
checksum.write('{} *{}'.format(sha256.hexdigest(), filename))
store_artifact(os.path.dirname(checksum_path), key_prefix, [checksum_path])
def get_release(version):
script_path = os.path.join(
ELECTRON_DIR, 'script', 'release', 'find-github-release.js')
release_info = execute(['node', script_path, version])
release = json.loads(release_info)
return release
if __name__ == '__main__':
sys.exit(main())
| [] | [] | [] | [] | [] | python | 0 | 0 | |
plugins/registry/gossip/gossip_test.go | package gossip
import (
"os"
"sync"
"testing"
"time"
"github.com/google/uuid"
"github.com/hashicorp/memberlist"
"go-micro.dev/v4/registry"
)
func newMemberlistConfig() *memberlist.Config {
mc := memberlist.DefaultLANConfig()
mc.DisableTcpPings = false
mc.GossipVerifyIncoming = false
mc.GossipVerifyOutgoing = false
mc.EnableCompression = false
mc.PushPullInterval = 3 * time.Second
mc.LogOutput = os.Stderr
mc.ProtocolVersion = 4
mc.Name = uuid.New().String()
return mc
}
func newRegistry(opts ...registry.Option) registry.Registry {
options := []registry.Option{
ConnectRetry(true),
ConnectTimeout(60 * time.Second),
}
options = append(options, opts...)
r := NewRegistry(options...)
return r
}
func TestGossipRegistryBroadcast(t *testing.T) {
if tr := os.Getenv("TRAVIS"); len(tr) > 0 {
t.Skip()
}
mc1 := newMemberlistConfig()
r1 := newRegistry(Config(mc1), Address("127.0.0.1:54321"))
mc2 := newMemberlistConfig()
r2 := newRegistry(Config(mc2), Address("127.0.0.1:54322"), registry.Addrs("127.0.0.1:54321"))
defer r1.(*gossipRegistry).Stop()
defer r2.(*gossipRegistry).Stop()
svc1 := ®istry.Service{Name: "service.1", Version: "0.0.0.1"}
svc2 := ®istry.Service{Name: "service.2", Version: "0.0.0.2"}
if err := r1.Register(svc1, registry.RegisterTTL(10*time.Second)); err != nil {
t.Fatal(err)
}
if err := r2.Register(svc2, registry.RegisterTTL(10*time.Second)); err != nil {
t.Fatal(err)
}
var found bool
svcs, err := r1.ListServices()
if err != nil {
t.Fatal(err)
}
for _, svc := range svcs {
if svc.Name == "service.2" {
found = true
}
}
if !found {
t.Fatalf("[gossip registry] service.2 not found in r1, broadcast not work")
}
found = false
svcs, err = r2.ListServices()
if err != nil {
t.Fatal(err)
}
for _, svc := range svcs {
if svc.Name == "service.1" {
found = true
}
}
if !found {
t.Fatalf("[gossip registry] broadcast failed: service.1 not found in r2")
}
if err := r1.Deregister(svc1); err != nil {
t.Fatal(err)
}
if err := r2.Deregister(svc2); err != nil {
t.Fatal(err)
}
}
func TestGossipRegistryRetry(t *testing.T) {
if tr := os.Getenv("TRAVIS"); len(tr) > 0 {
t.Skip()
}
mc1 := newMemberlistConfig()
r1 := newRegistry(Config(mc1), Address("127.0.0.1:54321"))
mc2 := newMemberlistConfig()
r2 := newRegistry(Config(mc2), Address("127.0.0.1:54322"), registry.Addrs("127.0.0.1:54321"))
defer r1.(*gossipRegistry).Stop()
defer r2.(*gossipRegistry).Stop()
svc1 := ®istry.Service{Name: "service.1", Version: "0.0.0.1"}
svc2 := ®istry.Service{Name: "service.2", Version: "0.0.0.2"}
var mu sync.Mutex
ch := make(chan struct{})
ticker := time.NewTicker(1 * time.Second)
defer ticker.Stop()
go func() {
for {
select {
case <-ticker.C:
mu.Lock()
if r1 != nil {
r1.Register(svc1, registry.RegisterTTL(2*time.Second))
}
if r2 != nil {
r2.Register(svc2, registry.RegisterTTL(2*time.Second))
}
if ch != nil {
close(ch)
ch = nil
}
mu.Unlock()
}
}
}()
<-ch
var found bool
svcs, err := r2.ListServices()
if err != nil {
t.Fatal(err)
}
for _, svc := range svcs {
if svc.Name == "service.1" {
found = true
}
}
if !found {
t.Fatalf("[gossip registry] broadcast failed: service.1 not found in r2")
}
if err = r1.(*gossipRegistry).Stop(); err != nil {
t.Fatalf("[gossip registry] failed to stop registry: %v", err)
}
mu.Lock()
r1 = nil
mu.Unlock()
<-time.After(3 * time.Second)
found = false
svcs, err = r2.ListServices()
if err != nil {
t.Fatal(err)
}
for _, svc := range svcs {
if svc.Name == "service.1" {
found = true
}
}
if found {
t.Fatalf("[gossip registry] service.1 found in r2")
}
r1 = newRegistry(Config(mc1), Address("127.0.0.1:54321"))
<-time.After(2 * time.Second)
found = false
svcs, err = r2.ListServices()
if err != nil {
t.Fatal(err)
}
for _, svc := range svcs {
if svc.Name == "service.1" {
found = true
}
}
if !found {
t.Fatalf("[gossip registry] connect retry failed: service.1 not found in r2")
}
if err := r1.Deregister(svc1); err != nil {
t.Fatal(err)
}
if err := r2.Deregister(svc2); err != nil {
t.Fatal(err)
}
r1.(*gossipRegistry).Stop()
r2.(*gossipRegistry).Stop()
}
| [
"\"TRAVIS\"",
"\"TRAVIS\""
] | [] | [
"TRAVIS"
] | [] | ["TRAVIS"] | go | 1 | 0 | |
providers/intercom/intercom_test.go | package intercom_test
import (
"encoding/json"
"fmt"
"github.com/gorilla/pat"
"github.com/floatingghost/goth"
"github.com/floatingghost/goth/providers/intercom"
"github.com/stretchr/testify/assert"
"net/http"
"net/http/httptest"
"os"
"testing"
)
type fetchUserPayload struct {
ID string `json:"id"`
Email string `json:"email"`
Name string `json:"name"`
Link string `json:"link"`
EmailVerified bool `json:"email_verified"`
Avatar struct {
URL string `json:"image_url"`
} `json:"avatar"`
}
func Test_New(t *testing.T) {
t.Parallel()
a := assert.New(t)
provider := intercomProvider()
a.Equal(provider.ClientKey, os.Getenv("INTERCOM_KEY"))
a.Equal(provider.Secret, os.Getenv("INTERCOM_SECRET"))
a.Equal(provider.CallbackURL, "/foo")
}
func Test_Implements_Provider(t *testing.T) {
t.Parallel()
a := assert.New(t)
a.Implements((*goth.Provider)(nil), intercomProvider())
}
func Test_BeginAuth(t *testing.T) {
t.Parallel()
a := assert.New(t)
provider := intercomProvider()
session, err := provider.BeginAuth("test_state")
s := session.(*intercom.Session)
a.NoError(err)
a.Contains(s.AuthURL, "https://app.intercom.io/oauth")
a.Contains(s.AuthURL, fmt.Sprintf("client_id=%s", os.Getenv("INTERCOM_KEY")))
a.Contains(s.AuthURL, "state=test_state")
}
func Test_SessionFromJSON(t *testing.T) {
t.Parallel()
a := assert.New(t)
provider := intercomProvider()
s, err := provider.UnmarshalSession(`{"AuthURL":"https://app.intercom.io/oauth","AccessToken":"1234567890"}`)
a.NoError(err)
session := s.(*intercom.Session)
a.Equal(session.AuthURL, "https://app.intercom.io/oauth")
a.Equal(session.AccessToken, "1234567890")
}
func intercomProvider() *intercom.Provider {
return intercom.New(os.Getenv("INTERCOM_KEY"), os.Getenv("INTERCOM_SECRET"), "/foo", "basic")
}
func Test_FetchUser(t *testing.T) {
a := assert.New(t)
u := fetchUserPayload{}
u.ID = "1"
u.Email = "wash@serenity.now"
u.Name = "Hoban Washburne"
u.EmailVerified = true
u.Avatar.URL = "http://avatarURL"
mockIntercomFetchUser(&u, func(ts *httptest.Server) {
provider := intercomProvider()
session := &intercom.Session{AccessToken: "token"}
user, err := provider.FetchUser(session)
a.NoError(err)
a.Equal("1", user.UserID)
a.Equal("wash@serenity.now", user.Email)
a.Equal("Hoban Washburne", user.Name)
a.Equal("Hoban", user.FirstName)
a.Equal("Washburne", user.LastName)
a.Equal("http://avatarURL", user.AvatarURL)
a.Equal(true, user.RawData["email_verified"])
a.Equal("token", user.AccessToken)
})
}
func Test_FetchUnverifiedUser(t *testing.T) {
a := assert.New(t)
u := fetchUserPayload{}
u.ID = "1"
u.Email = "wash@serenity.now"
u.Name = "Hoban Washburne"
u.EmailVerified = false
u.Avatar.URL = "http://avatarURL"
mockIntercomFetchUser(&u, func(ts *httptest.Server) {
provider := intercomProvider()
session := &intercom.Session{AccessToken: "token"}
user, err := provider.FetchUser(session)
a.NoError(err)
a.Equal("1", user.UserID)
a.Equal("wash@serenity.now", user.Email)
a.Equal("Hoban Washburne", user.Name)
a.Equal("Hoban", user.FirstName)
a.Equal("Washburne", user.LastName)
a.Equal("http://avatarURL", user.AvatarURL)
a.Equal(false, user.RawData["email_verified"])
a.Equal("token", user.AccessToken)
})
}
func mockIntercomFetchUser(fetchUserPayload *fetchUserPayload, f func(*httptest.Server)) {
p := pat.New()
p.Get("/me", func(res http.ResponseWriter, req *http.Request) {
json.NewEncoder(res).Encode(fetchUserPayload)
})
ts := httptest.NewServer(p)
defer ts.Close()
originalUserURL := intercom.UserURL
intercom.UserURL = ts.URL + "/me"
f(ts)
intercom.UserURL = originalUserURL
}
| [
"\"INTERCOM_KEY\"",
"\"INTERCOM_SECRET\"",
"\"INTERCOM_KEY\"",
"\"INTERCOM_KEY\"",
"\"INTERCOM_SECRET\""
] | [] | [
"INTERCOM_SECRET",
"INTERCOM_KEY"
] | [] | ["INTERCOM_SECRET", "INTERCOM_KEY"] | go | 2 | 0 | |
Gecko/scripts/seed/GraphReconstructionKarateClub.py | import matplotlib
#matplotlib.use('GTKAgg')
import os
os.environ["THEANO_FLAGS"]="mode=FAST_RUN,device=gpu,floatX=float32"
import matplotlib.pyplot as plt
from gem.utils import graph_util, plot_util
from gem.evaluation import visualize_embedding as viz
from gem.evaluation import evaluate_graph_reconstruction as gr
from time import time
from gem.embedding.gf import GraphFactorization
from gem.embedding.hope import HOPE
from gem.embedding.lap import LaplacianEigenmaps
from gem.embedding.lle import LocallyLinearEmbedding
#from gem.embedding.node2vec import node2vec
#from gem.embedding.sdne import SDNE
# File that contains the edges. Format: source target
# Optionally, you can add weights as third column: source target weight
edge_f = 'data/karate.edgelist'
# Specify whether the edges are directed
isDirected = True
# Load graph
G = graph_util.loadGraphFromEdgeListTxt(edge_f, directed=isDirected)
G = G.to_directed()
models = []
# You can comment out the methods you don't want to run
models.append(GraphFactorization(d=2, max_iter=100000, eta=1*10**-4, regu=1.0))
models.append(HOPE(d=4, beta=0.01))
models.append(LaplacianEigenmaps(d=2))
models.append(LocallyLinearEmbedding(d=2))
#models.append(node2vec(d=2, max_iter=1, walk_len=80, num_walks=10, con_size=10, ret_p=1, inout_p=1))
#models.append(SDNE(d=2, beta=5, alpha=1e-5, nu1=1e-6, nu2=1e-6, K=3,n_units=[50, 15,], rho=0.3, n_iter=50, xeta=0.01,n_batch=500,
# modelfile=['./intermediate/enc_model.json', './intermediate/dec_model.json'],
# weightfile=['./intermediate/enc_weights.hdf5', './intermediate/dec_weights.hdf5']))
for embedding in models:
print ('Num nodes: %d, num edges: %d' % (G.number_of_nodes(), G.number_of_edges()))
t1 = time()
# Learn embedding - accepts a networkx graph or file with edge list
Y, t = embedding.learn_embedding(graph=G, edge_f=None, is_weighted=True, no_python=True)
print (embedding._method_name+':\n\tTraining time: %f' % (time() - t1))
# Evaluate on graph reconstruction
MAP, prec_curv, err, err_baseline = gr.evaluateStaticGraphReconstruction(G, embedding, Y, None)
#---------------------------------------------------------------------------------
print(("\tMAP: {} \t precision curve: {}\n\n\n\n"+'-'*100).format(MAP,prec_curv[:5]))
#---------------------------------------------------------------------------------
# Visualize
viz.plot_embedding2D(embedding.get_embedding(), di_graph=G, node_colors=None)
plt.show()
| [] | [] | [
"THEANO_FLAGS"
] | [] | ["THEANO_FLAGS"] | python | 1 | 0 | |
keras/utils/tf_utils_test.py | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for Keras TF utils."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow.compat.v2 as tf
from absl.testing import parameterized
import keras
from keras import combinations
from keras.utils import tf_utils
try:
import attr # pylint:disable=g-import-not-at-top
except ImportError:
attr = None
@combinations.generate(combinations.combine(mode=['graph', 'eager']))
class TestIsSymbolicTensor(tf.test.TestCase, parameterized.TestCase):
def test_default_behavior(self):
if tf.executing_eagerly():
self.assertFalse(tf_utils.is_symbolic_tensor(
tf.Variable(name='blah', initial_value=0.)))
self.assertFalse(
tf_utils.is_symbolic_tensor(
tf.convert_to_tensor(0.)))
self.assertFalse(tf_utils.is_symbolic_tensor(
tf.SparseTensor(
indices=[[0, 0], [1, 2]], values=[1, 2], dense_shape=[3, 4])))
else:
self.assertTrue(tf_utils.is_symbolic_tensor(
tf.Variable(name='blah', initial_value=0.)))
self.assertTrue(
tf_utils.is_symbolic_tensor(
tf.convert_to_tensor(0.)))
self.assertTrue(tf_utils.is_symbolic_tensor(
tf.SparseTensor(
indices=[[0, 0], [1, 2]], values=[1, 2], dense_shape=[3, 4])))
def test_works_with_registered(self):
class CustomClass(object):
def value(self):
return tf.convert_to_tensor(42.)
tf.register_tensor_conversion_function(
CustomClass, lambda value, **_: value.value())
tf_utils.register_symbolic_tensor_type(CustomClass)
if tf.executing_eagerly():
self.assertFalse(tf_utils.is_symbolic_tensor(
tf.Variable(name='blah', initial_value=0.)))
self.assertFalse(
tf_utils.is_symbolic_tensor(
tf.convert_to_tensor(0.)))
self.assertFalse(tf_utils.is_symbolic_tensor(
tf.SparseTensor(
indices=[[0, 0], [1, 2]], values=[1, 2], dense_shape=[3, 4])))
self.assertFalse(tf_utils.is_symbolic_tensor(CustomClass()))
else:
self.assertTrue(tf_utils.is_symbolic_tensor(
tf.Variable(name='blah', initial_value=0.)))
self.assertTrue(
tf_utils.is_symbolic_tensor(
tf.convert_to_tensor(0.)))
self.assertTrue(tf_utils.is_symbolic_tensor(
tf.SparseTensor(
indices=[[0, 0], [1, 2]], values=[1, 2], dense_shape=[3, 4])))
self.assertTrue(tf_utils.is_symbolic_tensor(CustomClass()))
def test_enables_nontensor_plumbing(self):
if tf.executing_eagerly():
self.skipTest('`compile` functionality changed.')
# Setup.
class Foo(object):
def __init__(self, input_):
self._input = input_
self.value = tf.convert_to_tensor([[42.]])
@property
def dtype(self):
return self.value.dtype
tf.register_tensor_conversion_function(
Foo, lambda x, *args, **kwargs: x.value)
tf_utils.register_symbolic_tensor_type(Foo)
class PlumbingLayer(keras.layers.Lambda):
def __init__(self, fn, **kwargs):
def _fn(*fargs, **fkwargs):
d = fn(*fargs, **fkwargs)
x = tf.convert_to_tensor(d)
d.shape = x.shape
d.get_shape = x.get_shape
return d, x
super(PlumbingLayer, self).__init__(_fn, **kwargs)
self._enter_dunder_call = False
def __call__(self, inputs, *args, **kwargs):
self._enter_dunder_call = True
d, _ = super(PlumbingLayer, self).__call__(inputs, *args, **kwargs)
self._enter_dunder_call = False
return d
def call(self, inputs, *args, **kwargs):
d, v = super(PlumbingLayer, self).call(inputs, *args, **kwargs)
if self._enter_dunder_call:
return d, v
return d
# User-land.
model = keras.Sequential([
keras.layers.InputLayer((1,)),
PlumbingLayer(Foo), # Makes a `Foo` object.
])
# Let's ensure Keras graph history is preserved by composing the models.
model = keras.Model(model.inputs, model(model.outputs))
# Now we instantiate the model and verify we have a `Foo` object, not a
# `Tensor`.
y = model(tf.convert_to_tensor([[7.]]))
self.assertIsInstance(y, Foo)
# Confirm that (custom) loss sees `Foo` instance, not Tensor.
obtained_prediction_box = [None]
def custom_loss(y_obs, y_pred):
del y_obs
obtained_prediction_box[0] = y_pred
return y_pred
# Apparently `compile` calls the loss function enough to trigger the
# side-effect.
model.compile('SGD', loss=custom_loss)
self.assertIsInstance(obtained_prediction_box[0], Foo)
class ConvertInnerNodeDataTest(tf.test.TestCase):
def test_convert_inner_node_data(self):
data = tf_utils.convert_inner_node_data((tf_utils.ListWrapper(['l', 2, 3]),
tf_utils.ListWrapper(['l', 5, 6])))
self.assertEqual(data, (['l', 2, 3], ['l', 5, 6]))
data = tf_utils.convert_inner_node_data(((['l', 2, 3], ['l', 5, 6])),
wrap=True)
self.assertTrue(all(isinstance(ele, tf_utils.ListWrapper) for ele in data))
class AttrsTest(tf.test.TestCase):
def test_map_structure_with_atomic_accept_attr(self):
if attr is None:
self.skipTest('attr module is unavailable.')
@attr.s(frozen=True)
class Foo(object):
bar = attr.ib()
self.assertEqual(
Foo(2),
tf_utils.map_structure_with_atomic(
is_atomic_fn=lambda x: isinstance(x, int),
map_fn=lambda x: x + 1,
nested=Foo(1)))
class TestIsRagged(tf.test.TestCase):
def test_is_ragged_return_true_for_ragged_tensor(self):
tensor = tf.RaggedTensor.from_row_splits(
values=[3, 1, 4, 1, 5, 9, 2, 6], row_splits=[0, 4, 4, 7, 8, 8])
self.assertTrue(tf_utils.is_ragged(tensor))
def test_is_ragged_return_false_for_list(self):
tensor = [1., 2., 3.]
self.assertFalse(tf_utils.is_ragged(tensor))
class TestIsExtensionType(tf.test.TestCase):
def test_is_extension_type_return_true_for_ragged_tensor(self):
self.assertTrue(tf_utils.is_extension_type(
tf.ragged.constant([[1, 2], [3]])))
def test_is_extension_type_return_true_for_sparse_tensor(self):
self.assertTrue(tf_utils.is_extension_type(
tf.sparse.from_dense([[1, 2], [3, 4]])))
def test_is_extension_type_return_false_for_dense_tensor(self):
self.assertFalse(tf_utils.is_extension_type(
tf.constant([[1, 2], [3, 4]])))
def test_is_extension_type_return_false_for_list(self):
tensor = [1., 2., 3.]
self.assertFalse(tf_utils.is_extension_type(tensor))
if __name__ == '__main__':
tf.test.main()
| [] | [] | [] | [] | [] | python | null | null | null |
proc/crossref.py | import argparse
import asyncio
import html
import json
import logging
import os
import textwrap
import time
import xmltodict
from aiohttp import ClientSession, ClientConnectorError, ServerDisconnectedError, ContentTypeError
from articlemeta.client import RestfulClient
from datetime import datetime
from json import JSONDecodeError
from pyexpat import ExpatError
from pymongo import errors, MongoClient, uri_parser
from utils.string_processor import preprocess_author_name, preprocess_doi, preprocess_journal_title
from xylose.scielodocument import Article, Citation
DIR_DATA = os.environ.get('DIR_DATA', '/opt/data')
MONGO_STDCITS_COLLECTION = os.environ.get('MONGO_STDCITS_COLLECTION', 'standardized')
CROSSREF_URL_WORKS = os.environ.get('CROSSREF_URL_WORKS', 'https://api.crossref.org/works/{}')
CROSSREF_URL_OPENURL = os.environ.get('CROSSREF_URL_OPENURL', 'https://doi.crossref.org/openurl?')
CROSSREF_SEMAPHORE_LIMIT = int(os.environ.get('CROSSREF_SEMAPHORE_LIMIT', '20'))
class CrossrefAsyncCollector(object):
logging.basicConfig(level=logging.INFO)
def __init__(self, email: None, mongo_uri_std_cits=None):
self.email = email
if mongo_uri_std_cits:
try:
self.persist_mode = 'mongo'
mongo_col = uri_parser.parse_uri(mongo_uri_std_cits).get('collection')
if not mongo_col:
mongo_col = MONGO_STDCITS_COLLECTION
self.standardizer = MongoClient(mongo_uri_std_cits).get_database().get_collection(mongo_col)
total_docs = self.standardizer.count_documents({})
logging.info('There are {0} documents in the collection {1}'.format(total_docs, mongo_col))
except ConnectionError as e:
logging.error('ConnectionError %s' % mongo_uri_std_cits)
logging.error(e)
else:
self.persist_mode = 'json'
file_name_results = 'crossref-results-' + str(time.time()) + '.json'
self.path_results = os.path.join(DIR_DATA, file_name_results)
def extract_attrs(self, article: Article):
"""
Extrai os atributos de todas as referências citadas de um documento.
:param article: documento do qual serão extraídos os atributos das referências citadas
:return: dicionário de ids de citações e respectivos atributos
"""
cit_id_to_attrs = {}
if article.citations:
for cit in article.citations:
if cit.publication_type == 'article':
cit_id = self.mount_id(cit, article.collection_acronym)
cit_attrs = {}
if self.persist_mode == 'json':
cit_attrs = self._extract_cit_attrs(cit)
elif self.persist_mode == 'mongo':
cit_data = self.standardizer.find_one({'_id': cit_id})
if not cit_data or not cit_data.get('crossref'):
cit_attrs = self._extract_cit_attrs(cit)
if cit_attrs:
cit_id_to_attrs[cit_id] = cit_attrs
return cit_id_to_attrs
def _extract_cit_attrs(self, cit: Citation):
"""
Extrai os atributos de uma referência citada necessários para requisitar metadados CrossRef.
:param cit: referência citada
:return: dicionário de atributos para consulta no serviço CrossRef
"""
if cit.doi:
valid_doi = preprocess_doi(cit.doi)
if valid_doi:
return {'doi': valid_doi}
attrs = {}
if cit.first_author:
first_author_surname = cit.first_author.get('surname', '')
cleaned_author_surname = preprocess_author_name(first_author_surname)
if cleaned_author_surname:
attrs.update({'aulast': cleaned_author_surname})
journal_title = cit.source
if journal_title:
cleaned_journal_title = preprocess_journal_title(journal_title)
if cleaned_journal_title:
attrs.update({'title': cleaned_journal_title})
publication_date = html.unescape(cit.publication_date) if cit.publication_date else None
if publication_date and len(publication_date) >= 4:
publication_year = publication_date[:4]
if publication_year.isdigit():
attrs.update({'data': publication_year})
volume = html.unescape(cit.volume) if cit.volume else None
if volume:
attrs.update({'volume': volume})
issue = html.unescape(cit.issue) if cit.issue else None
if issue:
attrs.update({'issue': issue})
first_page = html.unescape(cit.first_page) if cit.first_page else None
if first_page:
attrs.update({'spage': first_page})
if attrs:
return attrs
def parse_crossref_openurl_result(self, text):
"""
Converte response.text para JSON com metadados obtidos do endpoint OPENURL.
:param response: resposta de requisição em formato de texto
:return: JSON com metadados obtidos do serviço CrossRef
"""
try:
raw = xmltodict.parse(text)
for v in raw.get('doi_records', {}).values():
metadata = v.get('crossref')
if metadata and 'error' not in metadata.keys():
owner = v.get('@owner')
if owner:
metadata.update({'owner': owner})
timestamp = v.get('@timestamp')
if timestamp:
metadata.update({'timestamp': timestamp})
journal_article = metadata.get('journal', {}).get('journal_article', {})
if 'citation_list' in journal_article:
journal_article.__delitem__('citation_list')
return metadata
except ExpatError as e:
logging.warning("ExpatError {0}".format(text))
logging.warning(e)
def parse_crossref_works_result(self, raw_metadata):
"""
Limpa dicionário de metadados obtidos do endpoint WORKS.
Remove campo de referências
:param raw_metadata: resposta de requisição em formato de dicionário
:return: JSON com metadados obtidos do serviço Crossref
"""
raw_status = raw_metadata.get('status', '')
if raw_status == 'ok':
metadata = raw_metadata.get('message')
if metadata:
if 'reference' in metadata:
metadata.__delitem__('reference')
return metadata
def mount_id(self, cit: Citation, collection: str):
"""
Monta o identificador de uma referência citada.
:param cit: referência citada
:param collection: coleção em que a referência foi citada
:return: código identificador da citação
"""
cit_id = cit.data['v880'][0]['_']
return '{0}-{1}'.format(cit_id, collection)
def save_crossref_metadata(self, id_to_metadata: dict):
"""
Persiste os metadados da referência citada.
:param id_to_metadata: dicionário com id da referência citada e seus respectivos metadados Crossref
"""
if self.persist_mode == 'json':
with open(self.path_results, 'a') as f:
json.dump(id_to_metadata, f)
f.write('\n')
elif self.persist_mode == 'mongo':
self.standardizer.update_one(filter={'_id': id_to_metadata['_id']},
update={'$set': {
'crossref': id_to_metadata['crossref'],
'update-date': datetime.now().strftime('%Y-%m-%d')
}},
upsert=True)
async def run(self, citations_attrs: dict):
sem = asyncio.Semaphore(CROSSREF_SEMAPHORE_LIMIT)
tasks = []
async with ClientSession(headers={'mailto:': self.email}) as session:
for cit_id, attrs in citations_attrs.items():
if 'doi' in attrs:
url = CROSSREF_URL_WORKS.format(attrs['doi'])
mode = 'doi'
else:
url = CROSSREF_URL_OPENURL
for k, v in attrs.items():
if k != 'doi':
url += '&' + k + '=' + v
url += '&pid=' + self.email
url += '&format=unixref'
url += '&multihit=false'
mode = 'attrs'
task = asyncio.ensure_future(self.bound_fetch(cit_id, url, sem, session, mode))
tasks.append(task)
responses = asyncio.gather(*tasks)
await responses
async def bound_fetch(self, cit_id, url, semaphore, session, mode):
async with semaphore:
await self.fetch(cit_id, url, session, mode)
async def fetch(self, cit_id, url, session, mode):
try:
async with session.get(url) as response:
try:
logging.info('Collecting metadata for %s' % cit_id)
if mode == 'doi':
raw_metadata = await response.json(content_type=None)
if raw_metadata:
metadata = self.parse_crossref_works_result(raw_metadata)
else:
raw_metadata = await response.text()
if raw_metadata:
metadata = self.parse_crossref_openurl_result(raw_metadata)
if metadata:
id_to_metadata = {'_id': cit_id, 'crossref': metadata}
self.save_crossref_metadata(id_to_metadata)
except JSONDecodeError as e:
logging.warning('JSONDecodeError: %s' % cit_id)
logging.warning(e)
except TimeoutError as e:
logging.warning('TimeoutError [INNER]: %s' % cit_id)
logging.warning(e)
except ContentTypeError as e:
logging.warning('ContentTypeError: %s' % cit_id)
logging.warning(e)
except ServerDisconnectedError as e:
logging.warning('ServerDisconnectedError: %s' % cit_id)
logging.warning(e)
except TimeoutError as e:
logging.warning('TimeoutError [OUTER]: %s' % cit_id)
logging.warning(e)
except ClientConnectorError as e:
logging.warning('ClientConectorError: %s' % cit_id)
logging.warning(e)
def format_date(date: datetime):
if not date:
return None
return date.strftime('%Y-%m-%d')
def main():
usage = "collect metadata from the Crossref Service"
parser = argparse.ArgumentParser(textwrap.dedent(usage))
parser.add_argument(
'-c', '--col',
default=None,
dest='col',
help='normalize cited references in an entire collection'
)
parser.add_argument(
'-f', '--from_date',
type=lambda x: datetime.strptime(x, '%Y-%m-%d'),
nargs='?',
help='collect metadata for cited references in documents published from a date (YYYY-MM-DD)'
)
parser.add_argument(
'-u', '--until_date',
type=lambda x: datetime.strptime(x, '%Y-%m-%d'),
nargs='?',
default=datetime.now(),
help='collect metadata for cited references in documents published until a date (YYYY-MM-DD)'
)
parser.add_argument(
'-i', '--document_id',
default=None,
dest='pid',
help='collect metadata for cited for the cited references in a PID (document)'
)
parser.add_argument(
'--mongo_uri',
default=None,
dest='mongo_uri_std_cits',
help='mongo uri string in the format mongodb://[username:password@]host1[:port1][,...hostN[:portN]][/[defaultauthdb][?options]]'
)
parser.add_argument(
'-e', '--email',
required=True,
default=None,
dest='email',
help='an e-mail registered in the Crossref service'
)
args = parser.parse_args()
try:
art_meta = RestfulClient()
cac = CrossrefAsyncCollector(email=args.email, mongo_uri_std_cits=args.mongo_uri_std_cits)
cit_ids_to_attrs = {}
start_time = time.time()
if args.pid:
logging.info('Running in one PID mode')
document = art_meta.document(collection=args.col, code=args.pid)
if document:
logging.info('Extracting info from cited references in %s ' % document.publisher_id)
cit_ids_to_attrs = cac.extract_attrs(document)
else:
logging.info('Running in many PIDs mode')
for document in art_meta.documents(collection=args.col,
from_date=format_date(args.from_date),
until_date=format_date(args.until_date)):
logging.info('Extracting info from cited references in %s ' % document.publisher_id)
cit_ids_to_attrs.update(cac.extract_attrs(document))
loop = asyncio.get_event_loop()
future = asyncio.ensure_future(cac.run(cit_ids_to_attrs))
loop.run_until_complete(future)
end_time = time.time()
logging.info('Duration {0} seconds.'.format(end_time - start_time))
except KeyboardInterrupt:
print("Interrupt by user")
| [] | [] | [
"MONGO_STDCITS_COLLECTION",
"CROSSREF_URL_WORKS",
"CROSSREF_SEMAPHORE_LIMIT",
"CROSSREF_URL_OPENURL",
"DIR_DATA"
] | [] | ["MONGO_STDCITS_COLLECTION", "CROSSREF_URL_WORKS", "CROSSREF_SEMAPHORE_LIMIT", "CROSSREF_URL_OPENURL", "DIR_DATA"] | python | 5 | 0 | |
cmd/xsDeploy_generated.go | // Code generated by piper's step-generator. DO NOT EDIT.
package cmd
import (
"fmt"
"os"
"path/filepath"
"time"
"github.com/SAP/jenkins-library/pkg/config"
"github.com/SAP/jenkins-library/pkg/log"
"github.com/SAP/jenkins-library/pkg/piperenv"
"github.com/SAP/jenkins-library/pkg/telemetry"
"github.com/spf13/cobra"
)
type xsDeployOptions struct {
DeployOpts string `json:"deployOpts,omitempty"`
OperationIDLogPattern string `json:"operationIdLogPattern,omitempty"`
MtaPath string `json:"mtaPath,omitempty"`
Action string `json:"action,omitempty"`
Mode string `json:"mode,omitempty"`
OperationID string `json:"operationId,omitempty"`
APIURL string `json:"apiUrl,omitempty"`
User string `json:"user,omitempty"`
Password string `json:"password,omitempty"`
Org string `json:"org,omitempty"`
Space string `json:"space,omitempty"`
LoginOpts string `json:"loginOpts,omitempty"`
XsSessionFile string `json:"xsSessionFile,omitempty"`
}
type xsDeployCommonPipelineEnvironment struct {
operationID string
}
func (p *xsDeployCommonPipelineEnvironment) persist(path, resourceName string) {
content := []struct {
category string
name string
value string
}{
{category: "", name: "operationId", value: p.operationID},
}
errCount := 0
for _, param := range content {
err := piperenv.SetResourceParameter(path, resourceName, filepath.Join(param.category, param.name), param.value)
if err != nil {
log.Entry().WithError(err).Error("Error persisting piper environment.")
errCount++
}
}
if errCount > 0 {
log.Entry().Fatal("failed to persist Piper environment")
}
}
// XsDeployCommand Performs xs deployment
func XsDeployCommand() *cobra.Command {
const STEP_NAME = "xsDeploy"
metadata := xsDeployMetadata()
var stepConfig xsDeployOptions
var startTime time.Time
var commonPipelineEnvironment xsDeployCommonPipelineEnvironment
var createXsDeployCmd = &cobra.Command{
Use: STEP_NAME,
Short: "Performs xs deployment",
Long: `Performs xs deployment`,
PreRunE: func(cmd *cobra.Command, args []string) error {
startTime = time.Now()
log.SetStepName(STEP_NAME)
log.SetVerbose(GeneralConfig.Verbose)
path, _ := os.Getwd()
fatalHook := &log.FatalHook{CorrelationID: GeneralConfig.CorrelationID, Path: path}
log.RegisterHook(fatalHook)
err := PrepareConfig(cmd, &metadata, STEP_NAME, &stepConfig, config.OpenPiperFile)
if err != nil {
return err
}
log.RegisterSecret(stepConfig.User)
log.RegisterSecret(stepConfig.Password)
if len(GeneralConfig.HookConfig.SentryConfig.Dsn) > 0 {
sentryHook := log.NewSentryHook(GeneralConfig.HookConfig.SentryConfig.Dsn, GeneralConfig.CorrelationID)
log.RegisterHook(&sentryHook)
}
return nil
},
Run: func(cmd *cobra.Command, args []string) {
telemetryData := telemetry.CustomData{}
telemetryData.ErrorCode = "1"
handler := func() {
commonPipelineEnvironment.persist(GeneralConfig.EnvRootPath, "commonPipelineEnvironment")
telemetryData.Duration = fmt.Sprintf("%v", time.Since(startTime).Milliseconds())
telemetry.Send(&telemetryData)
}
log.DeferExitHandler(handler)
defer handler()
telemetry.Initialize(GeneralConfig.NoTelemetry, STEP_NAME)
xsDeploy(stepConfig, &telemetryData, &commonPipelineEnvironment)
telemetryData.ErrorCode = "0"
},
}
addXsDeployFlags(createXsDeployCmd, &stepConfig)
return createXsDeployCmd
}
func addXsDeployFlags(cmd *cobra.Command, stepConfig *xsDeployOptions) {
cmd.Flags().StringVar(&stepConfig.DeployOpts, "deployOpts", os.Getenv("PIPER_deployOpts"), "Additional options appended to the deploy command. Only needed for sophisticated cases. When provided it is the duty of the provider to ensure proper quoting / escaping.")
cmd.Flags().StringVar(&stepConfig.OperationIDLogPattern, "operationIdLogPattern", "^.*xs bg-deploy -i (.*) -a.*$", "Regex pattern for retrieving the ID of the operation from the xs log.")
cmd.Flags().StringVar(&stepConfig.MtaPath, "mtaPath", os.Getenv("PIPER_mtaPath"), "Path to deployable")
cmd.Flags().StringVar(&stepConfig.Action, "action", "NONE", "Used for finalizing the blue-green deployment.")
cmd.Flags().StringVar(&stepConfig.Mode, "mode", "DEPLOY", "Controls if there is a standard deployment or a blue green deployment. Values: 'DEPLOY', 'BG_DEPLOY'")
cmd.Flags().StringVar(&stepConfig.OperationID, "operationId", os.Getenv("PIPER_operationId"), "The operation ID. Used in case of bg-deploy in order to resume or abort a previously started deployment.")
cmd.Flags().StringVar(&stepConfig.APIURL, "apiUrl", os.Getenv("PIPER_apiUrl"), "The api url (e.g. https://example.org:12345")
cmd.Flags().StringVar(&stepConfig.User, "user", os.Getenv("PIPER_user"), "User")
cmd.Flags().StringVar(&stepConfig.Password, "password", os.Getenv("PIPER_password"), "Password")
cmd.Flags().StringVar(&stepConfig.Org, "org", os.Getenv("PIPER_org"), "The org")
cmd.Flags().StringVar(&stepConfig.Space, "space", os.Getenv("PIPER_space"), "The space")
cmd.Flags().StringVar(&stepConfig.LoginOpts, "loginOpts", os.Getenv("PIPER_loginOpts"), "Additional options appended to the login command. Only needed for sophisticated cases. When provided it is the duty of the provider to ensure proper quoting / escaping.")
cmd.Flags().StringVar(&stepConfig.XsSessionFile, "xsSessionFile", os.Getenv("PIPER_xsSessionFile"), "The file keeping the xs session.")
cmd.MarkFlagRequired("mtaPath")
cmd.MarkFlagRequired("mode")
cmd.MarkFlagRequired("apiUrl")
cmd.MarkFlagRequired("user")
cmd.MarkFlagRequired("password")
cmd.MarkFlagRequired("org")
cmd.MarkFlagRequired("space")
cmd.MarkFlagRequired("loginOpts")
}
// retrieve step metadata
func xsDeployMetadata() config.StepData {
var theMetaData = config.StepData{
Metadata: config.StepMetadata{
Name: "xsDeploy",
Aliases: []config.Alias{},
},
Spec: config.StepSpec{
Inputs: config.StepInputs{
Parameters: []config.StepParameters{
{
Name: "deployOpts",
ResourceRef: []config.ResourceReference{},
Scope: []string{"PARAMETERS", "STAGES", "STEPS"},
Type: "string",
Mandatory: false,
Aliases: []config.Alias{},
},
{
Name: "operationIdLogPattern",
ResourceRef: []config.ResourceReference{},
Scope: []string{"PARAMETERS", "STAGES", "STEPS"},
Type: "string",
Mandatory: false,
Aliases: []config.Alias{{Name: "deployIdLogPattern"}},
},
{
Name: "mtaPath",
ResourceRef: []config.ResourceReference{{Name: "commonPipelineEnvironment", Param: "mtaPath"}},
Scope: []string{"PARAMETERS", "STAGES", "STEPS"},
Type: "string",
Mandatory: true,
Aliases: []config.Alias{},
},
{
Name: "action",
ResourceRef: []config.ResourceReference{},
Scope: []string{"PARAMETERS", "STAGES", "STEPS"},
Type: "string",
Mandatory: false,
Aliases: []config.Alias{},
},
{
Name: "mode",
ResourceRef: []config.ResourceReference{},
Scope: []string{"PARAMETERS", "STAGES", "STEPS"},
Type: "string",
Mandatory: true,
Aliases: []config.Alias{},
},
{
Name: "operationId",
ResourceRef: []config.ResourceReference{{Name: "commonPipelineEnvironment", Param: "operationId"}},
Scope: []string{"PARAMETERS", "STAGES", "STEPS"},
Type: "string",
Mandatory: false,
Aliases: []config.Alias{},
},
{
Name: "apiUrl",
ResourceRef: []config.ResourceReference{},
Scope: []string{"PARAMETERS", "STAGES", "STEPS"},
Type: "string",
Mandatory: true,
Aliases: []config.Alias{},
},
{
Name: "user",
ResourceRef: []config.ResourceReference{},
Scope: []string{"PARAMETERS", "STAGES", "STEPS"},
Type: "string",
Mandatory: true,
Aliases: []config.Alias{},
},
{
Name: "password",
ResourceRef: []config.ResourceReference{},
Scope: []string{"PARAMETERS", "STAGES", "STEPS"},
Type: "string",
Mandatory: true,
Aliases: []config.Alias{},
},
{
Name: "org",
ResourceRef: []config.ResourceReference{},
Scope: []string{"PARAMETERS", "STAGES", "STEPS"},
Type: "string",
Mandatory: true,
Aliases: []config.Alias{},
},
{
Name: "space",
ResourceRef: []config.ResourceReference{},
Scope: []string{"PARAMETERS", "STAGES", "STEPS"},
Type: "string",
Mandatory: true,
Aliases: []config.Alias{},
},
{
Name: "loginOpts",
ResourceRef: []config.ResourceReference{},
Scope: []string{"PARAMETERS", "STAGES", "STEPS"},
Type: "string",
Mandatory: true,
Aliases: []config.Alias{},
},
{
Name: "xsSessionFile",
ResourceRef: []config.ResourceReference{},
Scope: []string{"PARAMETERS", "STAGES", "STEPS"},
Type: "string",
Mandatory: false,
Aliases: []config.Alias{},
},
},
},
},
}
return theMetaData
}
| [
"\"PIPER_deployOpts\"",
"\"PIPER_mtaPath\"",
"\"PIPER_operationId\"",
"\"PIPER_apiUrl\"",
"\"PIPER_user\"",
"\"PIPER_password\"",
"\"PIPER_org\"",
"\"PIPER_space\"",
"\"PIPER_loginOpts\"",
"\"PIPER_xsSessionFile\""
] | [] | [
"PIPER_org",
"PIPER_password",
"PIPER_deployOpts",
"PIPER_user",
"PIPER_apiUrl",
"PIPER_operationId",
"PIPER_loginOpts",
"PIPER_space",
"PIPER_xsSessionFile",
"PIPER_mtaPath"
] | [] | ["PIPER_org", "PIPER_password", "PIPER_deployOpts", "PIPER_user", "PIPER_apiUrl", "PIPER_operationId", "PIPER_loginOpts", "PIPER_space", "PIPER_xsSessionFile", "PIPER_mtaPath"] | go | 10 | 0 | |
internal/middleware/jwt.go | package middleware
import (
"net/http"
"os"
"strconv"
"strings"
"time"
"github.com/cazyw/shakespeare-go/internal/responses"
"github.com/gofiber/fiber/v2"
jwtMiddleware "github.com/gofiber/jwt/v2"
"github.com/golang-jwt/jwt"
)
// TokenMetadata struct to describe metadata in JWT.
type TokenMetadata struct {
Expires int64
}
// GenerateNewAccessToken func for generate a new Access token.
func GenerateNewAccessToken() (string, error) {
// Set secret key from .env file.
secret := os.Getenv("JWT_SECRET_KEY")
// Set expires minutes count for secret key from .env file.
minutesCount, _ := strconv.Atoi(os.Getenv("JWT_SECRET_KEY_EXPIRE_MINUTES_COUNT"))
// Create a new claims.
claims := jwt.MapClaims{}
// Set public claims:
claims["exp"] = time.Now().Add(time.Minute * time.Duration(minutesCount)).Unix()
// Create a new JWT access token with claims.
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
// Generate token.
t, err := token.SignedString([]byte(secret))
if err != nil {
// Return error, it JWT token generation failed.
return "", err
}
return t, nil
}
// JWTProtected func for specify routes group with JWT authentication.
// See: https://github.com/gofiber/jwt
func JWTProtected() func(*fiber.Ctx) error {
// Create config for JWT authentication middleware.
config := jwtMiddleware.Config{
SigningKey: []byte(os.Getenv("JWT_SECRET_KEY")),
ContextKey: "jwt", // used in private routes
ErrorHandler: jwtError,
}
return jwtMiddleware.New(config)
}
func jwtError(c *fiber.Ctx, err error) error {
// Return status 400 and failed authentication error.
if err.Error() == "Missing or malformed JWT" {
return responses.Response(c, http.StatusBadRequest, responses.ReturnErr, &fiber.Map{"error": err.Error()})
}
// Return status 401 and failed authentication error.
return responses.Response(c, http.StatusUnauthorized, responses.ReturnErr, &fiber.Map{"error": err.Error()})
}
// ExtractTokenMetadata func to extract metadata from JWT.
func ExtractTokenMetadata(c *fiber.Ctx) (*TokenMetadata, error) {
token, err := verifyToken(c)
if err != nil {
return nil, err
}
// Setting and checking token and credentials.
claims, ok := token.Claims.(jwt.MapClaims)
if ok && token.Valid {
// Expires time.
expires := int64(claims["exp"].(float64))
return &TokenMetadata{
Expires: expires,
}, nil
}
return nil, err
}
func extractToken(c *fiber.Ctx) string {
bearToken := c.Get("Authorization")
// Normally Authorization HTTP header.
onlyToken := strings.Split(bearToken, " ")
if len(onlyToken) == 2 {
return onlyToken[1]
}
return ""
}
func verifyToken(c *fiber.Ctx) (*jwt.Token, error) {
tokenString := extractToken(c)
token, err := jwt.Parse(tokenString, jwtKeyFunc)
if err != nil {
return nil, err
}
return token, nil
}
func jwtKeyFunc(token *jwt.Token) (interface{}, error) {
return []byte(os.Getenv("JWT_SECRET_KEY")), nil
}
func CheckAuthenticated(c *fiber.Ctx) error {
// Get now time.
now := time.Now().Unix()
// Get claims from JWT.
claims, err := ExtractTokenMetadata(c)
if err != nil {
// Return status 500 and JWT parse error.
return responses.Response(c, http.StatusInternalServerError, responses.ReturnErr, &fiber.Map{"error": err.Error()})
}
// Set expiration time from JWT data of current quote.
expires := claims.Expires
// Checking, if now time greather than expiration from JWT.
if now > expires {
// Return status 401 and unauthorized error message.
return responses.Response(c, http.StatusUnauthorized, responses.ReturnErr, &fiber.Map{"error": "unauthorized, check expiration time of your token"})
}
return nil
}
| [
"\"JWT_SECRET_KEY\"",
"\"JWT_SECRET_KEY_EXPIRE_MINUTES_COUNT\"",
"\"JWT_SECRET_KEY\"",
"\"JWT_SECRET_KEY\""
] | [] | [
"JWT_SECRET_KEY_EXPIRE_MINUTES_COUNT",
"JWT_SECRET_KEY"
] | [] | ["JWT_SECRET_KEY_EXPIRE_MINUTES_COUNT", "JWT_SECRET_KEY"] | go | 2 | 0 | |
go/examples/test/create_tenant_test.go | // Copyright 2021 VMware, Inc.
// SPDX-License-Identifier: Apache License 2.0
package test
import (
"fmt"
"os"
"testing"
"github.com/vmware/alb-sdk/go/clients"
"github.com/vmware/alb-sdk/go/models"
"github.com/vmware/alb-sdk/go/session"
)
func TestCreateTenant(t *testing.T) {
aviClient, err := clients.NewAviClient(os.Getenv("AVI_CONTROLLER"), os.Getenv("AVI_USERNAME"),
session.SetPassword(os.Getenv("AVI_PASSWORD")),
session.SetTenant(os.Getenv("AVI_TENANT")),
session.SetVersion(os.Getenv("AVI_VERSION")),
session.SetInsecure)
if err != nil {
fmt.Println("Couldn't create session: ", err)
t.Fail()
}
cv, err := aviClient.AviSession.GetControllerVersion()
fmt.Printf("Avi Controller Version: %v:%v\n", cv, err)
// Create tenant avinetworks
tenantobj := models.Tenant{}
name := "avinetworks"
tenantobj.Name = &name
tobj, err := aviClient.Tenant.Create(&tenantobj)
if err != nil {
fmt.Println("\n Tenant creation failed: ", err)
t.Fail()
}
fmt.Println("\n Tenant created successfully. ", tobj)
}
| [
"\"AVI_CONTROLLER\"",
"\"AVI_USERNAME\"",
"\"AVI_PASSWORD\"",
"\"AVI_TENANT\"",
"\"AVI_VERSION\""
] | [] | [
"AVI_PASSWORD",
"AVI_VERSION",
"AVI_USERNAME",
"AVI_TENANT",
"AVI_CONTROLLER"
] | [] | ["AVI_PASSWORD", "AVI_VERSION", "AVI_USERNAME", "AVI_TENANT", "AVI_CONTROLLER"] | go | 5 | 0 | |
test/integration/shared_int_test.go | package integration
import (
"fmt"
"os"
"runtime"
"github.com/ActiveState/cli/internal/logging"
"github.com/gobuffalo/packr"
"github.com/ActiveState/cli/internal/constants"
"github.com/ActiveState/cli/internal/language"
"github.com/ActiveState/cli/internal/strutils"
)
var (
testUser = "test-user"
testProject = "test-project"
namespace = fmt.Sprintf("%s/%s", testUser, testProject)
url = fmt.Sprintf("https://%s/%s", constants.PlatformURL, namespace)
sampleYAMLPython2 = ""
sampleYAMLPython3 = ""
sampleYAMLEditor = ""
)
func init() {
if os.Getenv("VERBOSE") == "true" || os.Getenv("VERBOSE_TESTS") == "true" {
logging.CurrentHandler().SetVerbose(true)
}
shell := "bash"
if runtime.GOOS == "windows" {
shell = "batch"
}
var err error
box := packr.NewBox("../../assets/")
sampleYAMLPython2, err = strutils.ParseTemplate(
box.String("activestate.yaml.python.tpl"),
map[string]interface{}{
"Owner": testUser,
"Project": testProject,
"Shell": shell,
"Language": "python2",
"LangExe": language.MakeByName("python2").Executable().Filename(),
})
if err != nil {
panic(err.Error())
}
sampleYAMLPython3, err = strutils.ParseTemplate(
box.String("activestate.yaml.python.tpl"),
map[string]interface{}{
"Owner": testUser,
"Project": testProject,
"Shell": shell,
"Language": "python3",
"LangExe": language.MakeByName("python3").Executable().Filename(),
})
if err != nil {
panic(err.Error())
}
sampleYAMLEditor, err = strutils.ParseTemplate(box.String("activestate.yaml.editor.tpl"), nil)
if err != nil {
panic(err.Error())
}
}
| [
"\"VERBOSE\"",
"\"VERBOSE_TESTS\""
] | [] | [
"VERBOSE_TESTS",
"VERBOSE"
] | [] | ["VERBOSE_TESTS", "VERBOSE"] | go | 2 | 0 | |
rabbit/src/main/java/istu/bacs/rabbit/RabbitConfiguration.java | package istu.bacs.rabbit;
import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.net.URI;
import java.net.URISyntaxException;
import static istu.bacs.rabbit.QueueName.*;
@Configuration
public class RabbitConfiguration {
private static boolean isNotBlank(String s) {
return s != null && !s.isEmpty();
}
@Bean
ConnectionFactory connectionFactory() {
//получаем адрес AMQP у провайдера
String uri = System.getenv("CLOUDAMQP_URL");
if (uri == null) //значит мы запущены локально и нужно подключаться к локальному rabbitmq
uri = "amqp://guest:guest@localhost";
URI url = null;
try {
url = new URI(uri);
} catch (URISyntaxException e) {
e.printStackTrace(); //тут ошибка крайне маловероятна
}
CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
connectionFactory.setHost(url.getHost());
connectionFactory.setUsername(url.getUserInfo().split(":")[0]);
connectionFactory.setPassword(url.getUserInfo().split(":")[1]);
if (isNotBlank(url.getPath()))
connectionFactory.setVirtualHost(url.getPath().replace("/", ""));
connectionFactory.setConnectionTimeout(3000);
connectionFactory.setRequestedHeartBeat(30);
return connectionFactory;
}
@Bean
AmqpAdmin amqpAdmin(ConnectionFactory connectionFactory) {
return new RabbitAdmin(connectionFactory);
}
@Bean
RabbitService rabbitService(AmqpAdmin amqpAdmin, RabbitTemplate rabbitTemplate, ConnectionFactory connectionFactory) {
return new RabbitServiceImpl(amqpAdmin, rabbitTemplate, connectionFactory);
}
@Bean
Queue scheduledSubmissionsQueue() {
return new Queue(SCHEDULED_SUBMISSIONS.name());
}
@Bean
Queue submittedSubmissionsQueue() {
return new Queue(SUBMITTED_SUBMISSIONS.name());
}
@Bean
Queue checkedSubmissionsQueue() {
return new Queue(CHECKED_SUBMISSIONS.name());
}
@Bean
Queue otherQueue() {
return new Queue(OTHER.name());
}
} | [
"\"CLOUDAMQP_URL\""
] | [] | [
"CLOUDAMQP_URL"
] | [] | ["CLOUDAMQP_URL"] | java | 1 | 0 | |
conf_test.go | package main
import (
"os"
"testing"
"github.com/stretchr/testify/assert"
)
func TestParseConf(t *testing.T) {
*ignore = ""
*args = ""
*suffixes = ""
cnf, err := parseConf("./test/config.json")
assert.Nil(t, err, "Error should not happen if file is ok")
AssertArraysEq(t, []string{"some/path/to/ignore", "some/path/to/ignore"}, cnf.Ignore)
AssertArraysEq(t, []string{"dev", "test"}, cnf.Args)
AssertArraysEq(t, []string{".go", ".html", ".tpl"}, cnf.Suffixes)
assert.Equal(t, true, cnf.Attrib)
}
func TestParseConfWithCliArgs(t *testing.T) {
*ignore = "path1,path2"
*args = "arg1,arg2"
*suffixes = ".go,.html"
*attrib = false
cnf, err := loadConfiguration()
assert.Nil(t, err, "Error should not happen if file is ok")
assert.True(t, len(cnf.Ignore) >= 2)
pathPrefix := os.Getenv("GOPATH") + "/src/github.com/ivpusic/rerun"
assert.True(t, contains(cnf.Ignore, pathPrefix + "/path1"))
assert.True(t, contains(cnf.Ignore, pathPrefix + "/path2"))
AssertArraysEq(t, []string{"arg1", "arg2"}, cnf.Args)
AssertArraysEq(t, []string{".go", ".html"}, cnf.Suffixes)
assert.False(t, cnf.Attrib)
}
| [
"\"GOPATH\""
] | [] | [
"GOPATH"
] | [] | ["GOPATH"] | go | 1 | 0 | |
pkg/tester/client.go | // Copyright 2017 Quentin Machu & eco authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package tester
import (
"context"
"errors"
"fmt"
"net"
"os"
"time"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/agent"
"github.com/coreos/etcd/etcdserver/etcdserverpb"
"github.com/quentin-m/etcd-cloud-operator/pkg/etcd"
)
func isHealthy(c *etcd.Client, clusterSize int) (uint64, error) {
if !c.IsHealthy(5, 5*time.Second) {
return 0, fmt.Errorf("cluster doesn't have quorum")
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
var healthyMembers, unhealthyMembers []string
var leader uint64
var leaderChanged bool
c.ForEachMember(func(c *etcd.Client, m *etcdserverpb.Member) error {
cURL := etcd.URL2Address(m.PeerURLs[0])
resp, err := c.Status(ctx, etcd.ClientURL(cURL, c.SC.TLSEnabled()))
if err != nil {
unhealthyMembers = append(unhealthyMembers, cURL)
return nil
}
healthyMembers = append(healthyMembers, cURL)
if leader == 0 {
leader = resp.Leader
} else if resp.Leader != leader {
leaderChanged = true
}
return nil
})
if leaderChanged {
return leader, fmt.Errorf("leader has changed during member listing, or all members do not agree on one")
}
if len(unhealthyMembers) > 0 {
return leader, fmt.Errorf("cluster has unhealthy members: %v", unhealthyMembers)
}
if len(healthyMembers) != clusterSize {
return leader, fmt.Errorf("cluster has %d healthy members, expected %d", len(healthyMembers), clusterSize)
}
// Verify no alarms are firing.
ctx, cancel = context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
alarms, err := c.AlarmList(ctx)
if err != nil {
return leader, fmt.Errorf("failed to retrieve alarms: %s", err)
}
if len(alarms.Alarms) > 0 {
return leader, errors.New("cluster has alarms firing")
}
return leader, nil
}
func execRemote(address string, cmd string) error {
sshAgent, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK"))
if err != nil {
return err
}
connection, err := ssh.Dial("tcp", address+":22", &ssh.ClientConfig{
User: "core",
Auth: []ssh.AuthMethod{
ssh.PublicKeysCallback(agent.NewClient(sshAgent).Signers),
},
HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
return nil
},
Timeout: 1 * time.Second,
})
if err != nil {
return err
}
session, err := connection.NewSession()
if err != nil {
return err
}
defer session.Close()
err = session.RequestPty("xterm", 80, 40, ssh.TerminalModes{
ssh.ECHO: 0,
ssh.TTY_OP_ISPEED: 14400,
ssh.TTY_OP_OSPEED: 14400,
})
if err != nil {
return err
}
return session.Run(cmd)
}
| [
"\"SSH_AUTH_SOCK\""
] | [] | [
"SSH_AUTH_SOCK"
] | [] | ["SSH_AUTH_SOCK"] | go | 1 | 0 | |
internal/lsp/cache/view.go | // Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package cache implements the caching layer for gopls.
package cache
import (
"context"
"encoding/json"
"fmt"
"go/ast"
"io"
"io/ioutil"
"os"
"path"
"path/filepath"
"reflect"
"strings"
"sync"
"time"
"golang.org/x/tools/internal/event"
"golang.org/x/tools/internal/event/keys"
"golang.org/x/tools/internal/gocommand"
"golang.org/x/tools/internal/imports"
"golang.org/x/tools/internal/lsp/debug/tag"
"golang.org/x/tools/internal/lsp/source"
"golang.org/x/tools/internal/memoize"
"golang.org/x/tools/internal/span"
"golang.org/x/tools/internal/xcontext"
errors "golang.org/x/xerrors"
)
type View struct {
session *Session
id string
optionsMu sync.Mutex
options source.Options
// mu protects most mutable state of the view.
mu sync.Mutex
// baseCtx is the context handed to NewView. This is the parent of all
// background contexts created for this view.
baseCtx context.Context
// backgroundCtx is the current context used by background tasks initiated
// by the view.
backgroundCtx context.Context
// cancel is called when all action being performed by the current view
// should be stopped.
cancel context.CancelFunc
// Name is the user visible name of this view.
name string
// Folder is the root of this view.
folder span.URI
// importsMu guards imports-related state, particularly the ProcessEnv.
importsMu sync.Mutex
// processEnv is the process env for this view.
// Some of its fields can be changed dynamically by modifications to
// the view's options. These fields are repopulated for every use.
// Note: this contains cached module and filesystem state.
//
// TODO(suzmue): the state cached in the process env is specific to each view,
// however, there is state that can be shared between views that is not currently
// cached, like the module cache.
processEnv *imports.ProcessEnv
cacheRefreshDuration time.Duration
cacheRefreshTimer *time.Timer
cachedModFileVersion source.FileIdentity
// keep track of files by uri and by basename, a single file may be mapped
// to multiple uris, and the same basename may map to multiple files
filesByURI map[span.URI]*fileBase
filesByBase map[string][]*fileBase
snapshotMu sync.Mutex
snapshot *snapshot
// initialized is closed when the view has been fully initialized.
// On initialization, the view's workspace packages are loaded.
// All of the fields below are set as part of initialization.
// If we failed to load, we don't re-try to avoid too many go/packages calls.
initializeOnce sync.Once
initialized chan struct{}
initCancel context.CancelFunc
// initializedErr needs no mutex, since any access to it happens after it
// has been set.
initializedErr error
// builtin pins the AST and package for builtin.go in memory.
builtin *builtinPackageHandle
// True if the view is either in GOPATH, a module, or some other
// non go command build system.
hasValidBuildConfiguration bool
// The real go.mod and go.sum files that are attributed to a view.
modURI, sumURI span.URI
// True if this view runs go commands using temporary mod files.
// Only possible with Go versions 1.14 and above.
tmpMod bool
// goCommand indicates if the user is using the go command or some other
// build system.
goCommand bool
// `go env` variables that need to be tracked by gopls.
gocache, gomodcache, gopath, goprivate string
goEnv map[string]string
// gocmdRunner guards go command calls from concurrency errors.
gocmdRunner *gocommand.Runner
}
type builtinPackageHandle struct {
handle *memoize.Handle
file source.ParseGoHandle
}
type builtinPackageData struct {
memoize.NoCopy
pkg *ast.Package
pgh *parseGoHandle
err error
}
func (d *builtinPackageData) Package() *ast.Package {
return d.pkg
}
func (d *builtinPackageData) ParseGoHandle() source.ParseGoHandle {
return d.pgh
}
// fileBase holds the common functionality for all files.
// It is intended to be embedded in the file implementations
type fileBase struct {
uris []span.URI
fname string
view *View
}
func (f *fileBase) URI() span.URI {
return f.uris[0]
}
func (f *fileBase) filename() string {
return f.fname
}
func (f *fileBase) addURI(uri span.URI) int {
f.uris = append(f.uris, uri)
return len(f.uris)
}
func (v *View) ID() string { return v.id }
func (v *View) ValidBuildConfiguration() bool {
return v.hasValidBuildConfiguration
}
func (v *View) ModFile() span.URI {
return v.modURI
}
// tempModFile creates a temporary go.mod file based on the contents of the
// given go.mod file. It is the caller's responsibility to clean up the files
// when they are done using them.
func tempModFile(modFh, sumFH source.FileHandle) (tmpURI span.URI, cleanup func(), err error) {
filenameHash := hashContents([]byte(modFh.URI().Filename()))
tmpMod, err := ioutil.TempFile("", fmt.Sprintf("go.%s.*.mod", filenameHash))
if err != nil {
return "", nil, err
}
defer tmpMod.Close()
tmpURI = span.URIFromPath(tmpMod.Name())
tmpSumName := sumFilename(tmpURI)
content, err := modFh.Read()
if err != nil {
return "", nil, err
}
if _, err := tmpMod.Write(content); err != nil {
return "", nil, err
}
cleanup = func() {
_ = os.Remove(tmpSumName)
_ = os.Remove(tmpURI.Filename())
}
// Be careful to clean up if we return an error from this function.
defer func() {
if err != nil {
cleanup()
cleanup = nil
}
}()
// Create an analogous go.sum, if one exists.
if sumFH != nil {
sumContents, err := sumFH.Read()
if err != nil {
return "", nil, err
}
if err := ioutil.WriteFile(tmpSumName, sumContents, 0655); err != nil {
return "", nil, err
}
}
return tmpURI, cleanup, nil
}
func (v *View) Session() source.Session {
return v.session
}
// Name returns the user visible name of this view.
func (v *View) Name() string {
return v.name
}
// Folder returns the root of this view.
func (v *View) Folder() span.URI {
return v.folder
}
func (v *View) Options() source.Options {
v.optionsMu.Lock()
defer v.optionsMu.Unlock()
return v.options
}
func minorOptionsChange(a, b source.Options) bool {
// Check if any of the settings that modify our understanding of files have been changed
if !reflect.DeepEqual(a.Env, b.Env) {
return false
}
if !reflect.DeepEqual(a.BuildFlags, b.BuildFlags) {
return false
}
// the rest of the options are benign
return true
}
func (v *View) SetOptions(ctx context.Context, options source.Options) (source.View, error) {
// no need to rebuild the view if the options were not materially changed
v.optionsMu.Lock()
if minorOptionsChange(v.options, options) {
v.options = options
v.optionsMu.Unlock()
return v, nil
}
v.optionsMu.Unlock()
newView, _, err := v.session.updateView(ctx, v, options)
return newView, err
}
func (v *View) Rebuild(ctx context.Context) (source.Snapshot, error) {
_, snapshot, err := v.session.updateView(ctx, v, v.Options())
return snapshot, err
}
func (v *View) BuiltinPackage(ctx context.Context) (source.BuiltinPackage, error) {
v.awaitInitialized(ctx)
if v.builtin == nil {
return nil, errors.Errorf("no builtin package for view %s", v.name)
}
data, err := v.builtin.handle.Get(ctx)
if err != nil {
return nil, err
}
if data == nil {
return nil, errors.Errorf("unexpected nil builtin package")
}
d, ok := data.(*builtinPackageData)
if !ok {
return nil, errors.Errorf("unexpected type %T", data)
}
if d.err != nil {
return nil, d.err
}
if d.pkg == nil || d.pkg.Scope == nil {
return nil, errors.Errorf("no builtin package")
}
return d, nil
}
func (v *View) buildBuiltinPackage(ctx context.Context, goFiles []string) error {
if len(goFiles) != 1 {
return errors.Errorf("only expected 1 file, got %v", len(goFiles))
}
uri := span.URIFromPath(goFiles[0])
// Get the FileHandle through the cache to avoid adding it to the snapshot
// and to get the file content from disk.
fh, err := v.session.cache.getFile(ctx, uri)
if err != nil {
return err
}
pgh := v.session.cache.parseGoHandle(ctx, fh, source.ParseFull)
fset := v.session.cache.fset
h := v.session.cache.store.Bind(fh.Identity(), func(ctx context.Context) interface{} {
file, _, _, _, err := pgh.Parse(ctx)
if err != nil {
return &builtinPackageData{err: err}
}
pkg, err := ast.NewPackage(fset, map[string]*ast.File{
pgh.File().URI().Filename(): file,
}, nil, nil)
if err != nil {
return &builtinPackageData{err: err}
}
return &builtinPackageData{
pgh: pgh,
pkg: pkg,
}
})
v.builtin = &builtinPackageHandle{
handle: h,
file: pgh,
}
return nil
}
func (v *View) WriteEnv(ctx context.Context, w io.Writer) error {
v.optionsMu.Lock()
env, buildFlags := v.envLocked()
v.optionsMu.Unlock()
// TODO(rstambler): We could probably avoid running this by saving the
// output on original create, but I'm not sure if it's worth it.
inv := gocommand.Invocation{
Verb: "env",
Env: env,
WorkingDir: v.Folder().Filename(),
}
// Don't go through runGoCommand, as we don't need a temporary go.mod to
// run `go env`.
stdout, err := v.gocmdRunner.Run(ctx, inv)
if err != nil {
return err
}
fmt.Fprintf(w, "go env for %v\n(valid build configuration = %v)\n(build flags: %v)\n", v.folder.Filename(), v.hasValidBuildConfiguration, buildFlags)
fmt.Fprint(w, stdout)
return nil
}
func (v *View) RunProcessEnvFunc(ctx context.Context, fn func(*imports.Options) error) error {
v.importsMu.Lock()
defer v.importsMu.Unlock()
// The resolver cached in the process env is reused, but some fields need
// to be repopulated for each use.
if v.processEnv == nil {
v.processEnv = &imports.ProcessEnv{}
}
var modFH, sumFH source.FileHandle
if v.tmpMod {
var err error
// Use temporary go.mod files, but always go to disk for the contents.
// Rebuilding the cache is expensive, and we don't want to do it for
// transient changes.
modFH, err = v.session.cache.getFile(ctx, v.modURI)
if err != nil {
return err
}
if v.sumURI != "" {
sumFH, err = v.session.cache.getFile(ctx, v.sumURI)
if err != nil {
return err
}
}
}
cleanup, err := v.populateProcessEnv(ctx, modFH, sumFH)
if err != nil {
return err
}
defer cleanup()
// If the go.mod file has changed, clear the cache.
if v.modURI != "" {
modFH, err := v.session.cache.getFile(ctx, v.modURI)
if err != nil {
return err
}
if modFH.Identity() != v.cachedModFileVersion {
v.processEnv.GetResolver().(*imports.ModuleResolver).ClearForNewMod()
v.cachedModFileVersion = modFH.Identity()
}
}
// Run the user function.
opts := &imports.Options{
// Defaults.
AllErrors: true,
Comments: true,
Fragment: true,
FormatOnly: false,
TabIndent: true,
TabWidth: 8,
Env: v.processEnv,
}
if err := fn(opts); err != nil {
return err
}
if v.cacheRefreshTimer == nil {
// Don't refresh more than twice per minute.
delay := 30 * time.Second
// Don't spend more than a couple percent of the time refreshing.
if adaptive := 50 * v.cacheRefreshDuration; adaptive > delay {
delay = adaptive
}
v.cacheRefreshTimer = time.AfterFunc(delay, v.refreshProcessEnv)
}
return nil
}
func (v *View) refreshProcessEnv() {
start := time.Now()
v.importsMu.Lock()
env := v.processEnv
env.GetResolver().ClearForNewScan()
v.importsMu.Unlock()
// We don't have a context handy to use for logging, so use the stdlib for now.
event.Log(v.baseCtx, "background imports cache refresh starting")
err := imports.PrimeCache(context.Background(), env)
if err == nil {
event.Log(v.baseCtx, fmt.Sprintf("background refresh finished after %v", time.Since(start)))
} else {
event.Log(v.baseCtx, fmt.Sprintf("background refresh finished after %v", time.Since(start)), keys.Err.Of(err))
}
v.importsMu.Lock()
v.cacheRefreshDuration = time.Since(start)
v.cacheRefreshTimer = nil
v.importsMu.Unlock()
}
// populateProcessEnv sets the dynamically configurable fields for the view's
// process environment. It operates on a snapshot because it needs to access
// file contents. Assumes that the caller is holding the s.view.importsMu.
func (v *View) populateProcessEnv(ctx context.Context, modFH, sumFH source.FileHandle) (cleanup func(), err error) {
cleanup = func() {}
v.optionsMu.Lock()
_, buildFlags := v.envLocked()
localPrefix, verboseOutput := v.options.LocalPrefix, v.options.VerboseOutput
v.optionsMu.Unlock()
pe := v.processEnv
pe.LocalPrefix = localPrefix
pe.GocmdRunner = v.gocmdRunner
pe.BuildFlags = buildFlags
pe.Env = v.goEnv
pe.WorkingDir = v.folder.Filename()
// Add -modfile to the build flags, if we are using it.
if modFH != nil {
var tmpURI span.URI
tmpURI, cleanup, err = tempModFile(modFH, sumFH)
if err != nil {
return nil, err
}
pe.BuildFlags = append(pe.BuildFlags, fmt.Sprintf("-modfile=%s", tmpURI.Filename()))
}
if verboseOutput {
pe.Logf = func(format string, args ...interface{}) {
event.Log(ctx, fmt.Sprintf(format, args...))
}
}
return cleanup, nil
}
// envLocked returns the environment and build flags for the current view.
// It assumes that the caller is holding the view's optionsMu.
func (v *View) envLocked() ([]string, []string) {
env := append([]string{}, v.options.Env...)
buildFlags := append([]string{}, v.options.BuildFlags...)
return env, buildFlags
}
func (v *View) contains(uri span.URI) bool {
return strings.HasPrefix(string(uri), string(v.folder))
}
func (v *View) mapFile(uri span.URI, f *fileBase) {
v.filesByURI[uri] = f
if f.addURI(uri) == 1 {
basename := basename(f.filename())
v.filesByBase[basename] = append(v.filesByBase[basename], f)
}
}
func basename(filename string) string {
return strings.ToLower(filepath.Base(filename))
}
func (v *View) relevantChange(c source.FileModification) bool {
// If the file is known to the view, the change is relevant.
known := v.knownFile(c.URI)
// If the file is not known to the view, and the change is only on-disk,
// we should not invalidate the snapshot. This is necessary because Emacs
// sends didChangeWatchedFiles events for temp files.
if !known && c.OnDisk && (c.Action == source.Change || c.Action == source.Delete) {
return false
}
return v.contains(c.URI) || known
}
func (v *View) knownFile(uri span.URI) bool {
v.mu.Lock()
defer v.mu.Unlock()
f, err := v.findFile(uri)
return f != nil && err == nil
}
// getFile returns a file for the given URI. It will always succeed because it
// adds the file to the managed set if needed.
func (v *View) getFile(uri span.URI) (*fileBase, error) {
v.mu.Lock()
defer v.mu.Unlock()
f, err := v.findFile(uri)
if err != nil {
return nil, err
} else if f != nil {
return f, nil
}
f = &fileBase{
view: v,
fname: uri.Filename(),
}
v.mapFile(uri, f)
return f, nil
}
// findFile checks the cache for any file matching the given uri.
//
// An error is only returned for an irreparable failure, for example, if the
// filename in question does not exist.
func (v *View) findFile(uri span.URI) (*fileBase, error) {
if f := v.filesByURI[uri]; f != nil {
// a perfect match
return f, nil
}
// no exact match stored, time to do some real work
// check for any files with the same basename
fname := uri.Filename()
basename := basename(fname)
if candidates := v.filesByBase[basename]; candidates != nil {
pathStat, err := os.Stat(fname)
if os.IsNotExist(err) {
return nil, err
}
if err != nil {
return nil, nil // the file may exist, return without an error
}
for _, c := range candidates {
if cStat, err := os.Stat(c.filename()); err == nil {
if os.SameFile(pathStat, cStat) {
// same file, map it
v.mapFile(uri, c)
return c, nil
}
}
}
}
// no file with a matching name was found, it wasn't in our cache
return nil, nil
}
func (v *View) Shutdown(ctx context.Context) {
v.session.removeView(ctx, v)
}
func (v *View) shutdown(ctx context.Context) {
// Cancel the initial workspace load if it is still running.
v.initCancel()
v.mu.Lock()
defer v.mu.Unlock()
if v.cancel != nil {
v.cancel()
v.cancel = nil
}
}
func (v *View) BackgroundContext() context.Context {
v.mu.Lock()
defer v.mu.Unlock()
return v.backgroundCtx
}
func (v *View) IgnoredFile(uri span.URI) bool {
filename := uri.Filename()
var prefixes []string
if v.modURI == "" {
for _, entry := range filepath.SplitList(v.gopath) {
prefixes = append(prefixes, filepath.Join(entry, "src"))
}
} else {
mainMod := filepath.Dir(v.modURI.Filename())
prefixes = []string{mainMod, v.gomodcache}
}
for _, prefix := range prefixes {
if strings.HasPrefix(filename, prefix) {
return checkIgnored(filename[len(prefix):])
}
}
return false
}
// checkIgnored implements go list's exclusion rules. go help list:
// Directory and file names that begin with "." or "_" are ignored
// by the go tool, as are directories named "testdata".
func checkIgnored(suffix string) bool {
for _, component := range strings.Split(suffix, string(filepath.Separator)) {
if len(component) == 0 {
continue
}
if component[0] == '.' || component[0] == '_' || component == "testdata" {
return true
}
}
return false
}
func (v *View) Snapshot() source.Snapshot {
return v.getSnapshot()
}
func (v *View) getSnapshot() *snapshot {
v.snapshotMu.Lock()
defer v.snapshotMu.Unlock()
return v.snapshot
}
func (v *View) initialize(ctx context.Context, s *snapshot) {
v.initializeOnce.Do(func() {
defer close(v.initialized)
if err := s.load(ctx, viewLoadScope("LOAD_VIEW"), packagePath("builtin")); err != nil {
if ctx.Err() != nil {
return
}
v.initializedErr = err
event.Error(ctx, "initial workspace load failed", err)
}
})
}
func (v *View) awaitInitialized(ctx context.Context) {
select {
case <-ctx.Done():
case <-v.initialized:
}
}
// invalidateContent invalidates the content of a Go file,
// including any position and type information that depends on it.
// It returns true if we were already tracking the given file, false otherwise.
func (v *View) invalidateContent(ctx context.Context, uris map[span.URI]source.FileHandle, forceReloadMetadata bool) source.Snapshot {
// Detach the context so that content invalidation cannot be canceled.
ctx = xcontext.Detach(ctx)
// Cancel all still-running previous requests, since they would be
// operating on stale data.
v.cancelBackground()
// Do not clone a snapshot until its view has finished initializing.
v.awaitInitialized(ctx)
// This should be the only time we hold the view's snapshot lock for any period of time.
v.snapshotMu.Lock()
defer v.snapshotMu.Unlock()
v.snapshot = v.snapshot.clone(ctx, uris, forceReloadMetadata)
return v.snapshot
}
func (v *View) cancelBackground() {
v.mu.Lock()
defer v.mu.Unlock()
if v.cancel == nil {
// this can happen during shutdown
return
}
v.cancel()
v.backgroundCtx, v.cancel = context.WithCancel(v.baseCtx)
}
func (v *View) setBuildInformation(ctx context.Context, folder span.URI, env []string, modfileFlagEnabled bool) error {
if err := checkPathCase(folder.Filename()); err != nil {
return fmt.Errorf("invalid workspace configuration: %w", err)
}
// Make sure to get the `go env` before continuing with initialization.
modFile, err := v.setGoEnv(ctx, env)
if err != nil {
return err
}
if modFile == os.DevNull {
return nil
}
v.modURI = span.URIFromPath(modFile)
// Set the sumURI, if the go.sum exists.
sumFilename := filepath.Join(filepath.Dir(modFile), "go.sum")
if stat, _ := os.Stat(sumFilename); stat != nil {
v.sumURI = span.URIFromPath(sumFilename)
}
// Now that we have set all required fields,
// check if the view has a valid build configuration.
v.setBuildConfiguration()
// The user has disabled the use of the -modfile flag or has no go.mod file.
if !modfileFlagEnabled || v.modURI == "" {
return nil
}
if modfileFlag, err := v.modfileFlagExists(ctx, v.Options().Env); err != nil {
return err
} else if modfileFlag {
v.tmpMod = true
}
return nil
}
// OS-specific path case check, for case-insensitive filesystems.
var checkPathCase = defaultCheckPathCase
func defaultCheckPathCase(path string) error {
return nil
}
func (v *View) setBuildConfiguration() (isValid bool) {
defer func() {
v.hasValidBuildConfiguration = isValid
}()
// Since we only really understand the `go` command, if the user is not
// using the go command, assume that their configuration is valid.
if !v.goCommand {
return true
}
// Check if the user is working within a module.
if v.modURI != "" {
return true
}
// The user may have a multiple directories in their GOPATH.
// Check if the workspace is within any of them.
for _, gp := range filepath.SplitList(v.gopath) {
if isSubdirectory(filepath.Join(gp, "src"), v.folder.Filename()) {
return true
}
}
return false
}
func isSubdirectory(root, leaf string) bool {
rel, err := filepath.Rel(root, leaf)
return err == nil && !strings.HasPrefix(rel, "..")
}
// setGoEnv sets the view's various GO* values. It also returns the view's
// GOMOD value, which need not be cached.
func (v *View) setGoEnv(ctx context.Context, configEnv []string) (string, error) {
var gomod string
vars := map[string]*string{
"GOCACHE": &v.gocache,
"GOPATH": &v.gopath,
"GOPRIVATE": &v.goprivate,
"GOMODCACHE": &v.gomodcache,
"GOMOD": &gomod,
}
// We can save ~200 ms by requesting only the variables we care about.
args := append([]string{"-json"}, imports.RequiredGoEnvVars...)
for k := range vars {
args = append(args, k)
}
inv := gocommand.Invocation{
Verb: "env",
Args: args,
Env: configEnv,
WorkingDir: v.Folder().Filename(),
}
// Don't go through runGoCommand, as we don't need a temporary -modfile to
// run `go env`.
stdout, err := v.gocmdRunner.Run(ctx, inv)
if err != nil {
return "", err
}
if err := json.Unmarshal(stdout.Bytes(), &v.goEnv); err != nil {
return "", err
}
for key, ptr := range vars {
*ptr = v.goEnv[key]
}
// Old versions of Go don't have GOMODCACHE, so emulate it.
if v.gomodcache == "" && v.gopath != "" {
v.gomodcache = filepath.Join(filepath.SplitList(v.gopath)[0], "pkg/mod")
}
// The value of GOPACKAGESDRIVER is not returned through the go command.
gopackagesdriver := os.Getenv("GOPACKAGESDRIVER")
v.goCommand = gopackagesdriver == "" || gopackagesdriver == "off"
return gomod, nil
}
func (v *View) IsGoPrivatePath(target string) bool {
return globsMatchPath(v.goprivate, target)
}
// Copied from
// https://cs.opensource.google/go/go/+/master:src/cmd/go/internal/str/path.go;l=58;drc=2910c5b4a01a573ebc97744890a07c1a3122c67a
func globsMatchPath(globs, target string) bool {
for globs != "" {
// Extract next non-empty glob in comma-separated list.
var glob string
if i := strings.Index(globs, ","); i >= 0 {
glob, globs = globs[:i], globs[i+1:]
} else {
glob, globs = globs, ""
}
if glob == "" {
continue
}
// A glob with N+1 path elements (N slashes) needs to be matched
// against the first N+1 path elements of target,
// which end just before the N+1'th slash.
n := strings.Count(glob, "/")
prefix := target
// Walk target, counting slashes, truncating at the N+1'th slash.
for i := 0; i < len(target); i++ {
if target[i] == '/' {
if n == 0 {
prefix = target[:i]
break
}
n--
}
}
if n > 0 {
// Not enough prefix elements.
continue
}
matched, _ := path.Match(glob, prefix)
if matched {
return true
}
}
return false
}
// This function will return the main go.mod file for this folder if it exists and whether the -modfile
// flag exists for this version of go.
func (v *View) modfileFlagExists(ctx context.Context, env []string) (bool, error) {
// Check the go version by running "go list" with modules off.
// Borrowed from internal/imports/mod.go:620.
const format = `{{range context.ReleaseTags}}{{if eq . "go1.14"}}{{.}}{{end}}{{end}}`
folder := v.folder.Filename()
inv := gocommand.Invocation{
Verb: "list",
Args: []string{"-e", "-f", format},
Env: append(env, "GO111MODULE=off"),
WorkingDir: v.Folder().Filename(),
}
stdout, err := v.gocmdRunner.Run(ctx, inv)
if err != nil {
return false, err
}
// If the output is not go1.14 or an empty string, then it could be an error.
lines := strings.Split(stdout.String(), "\n")
if len(lines) < 2 && stdout.String() != "" {
event.Error(ctx, "unexpected stdout when checking for go1.14", errors.Errorf("%q", stdout), tag.Directory.Of(folder))
return false, nil
}
return lines[0] == "go1.14", nil
}
| [
"\"GOPACKAGESDRIVER\""
] | [] | [
"GOPACKAGESDRIVER"
] | [] | ["GOPACKAGESDRIVER"] | go | 1 | 0 | |
service/appmesh/api.go | // Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT.
package appmesh
import (
"fmt"
"time"
"github.com/santhoshs123/aws-sdk-go/aws"
"github.com/santhoshs123/aws-sdk-go/aws/awsutil"
"github.com/santhoshs123/aws-sdk-go/aws/request"
"github.com/santhoshs123/aws-sdk-go/private/protocol"
"github.com/santhoshs123/aws-sdk-go/private/protocol/restjson"
)
const opCreateGatewayRoute = "CreateGatewayRoute"
// CreateGatewayRouteRequest generates a "aws/request.Request" representing the
// client's request for the CreateGatewayRoute operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See CreateGatewayRoute for more information on using the CreateGatewayRoute
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the CreateGatewayRouteRequest method.
// req, resp := client.CreateGatewayRouteRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/CreateGatewayRoute
func (c *AppMesh) CreateGatewayRouteRequest(input *CreateGatewayRouteInput) (req *request.Request, output *CreateGatewayRouteOutput) {
op := &request.Operation{
Name: opCreateGatewayRoute,
HTTPMethod: "PUT",
HTTPPath: "/v20190125/meshes/{meshName}/virtualGateway/{virtualGatewayName}/gatewayRoutes",
}
if input == nil {
input = &CreateGatewayRouteInput{}
}
output = &CreateGatewayRouteOutput{}
req = c.newRequest(op, input, output)
return
}
// CreateGatewayRoute API operation for AWS App Mesh.
//
// Creates a gateway route.
//
// A gateway route is attached to a virtual gateway and routes traffic to an
// existing virtual service. If a route matches a request, it can distribute
// traffic to a target virtual service.
//
// For more information about gateway routes, see Gateway routes (https://docs.aws.amazon.com/app-mesh/latest/userguide/gateway-routes.html).
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for AWS App Mesh's
// API operation CreateGatewayRoute for usage and error information.
//
// Returned Error Types:
// * NotFoundException
// The specified resource doesn't exist. Check your request syntax and try again.
//
// * BadRequestException
// The request syntax was malformed. Check your request syntax and try again.
//
// * ConflictException
// The request contains a client token that was used for a previous update resource
// call with different specifications. Try the request again with a new client
// token.
//
// * TooManyRequestsException
// The maximum request rate permitted by the App Mesh APIs has been exceeded
// for your account. For best results, use an increasing or variable sleep interval
// between requests.
//
// * ForbiddenException
// You don't have permissions to perform this action.
//
// * ServiceUnavailableException
// The request has failed due to a temporary failure of the service.
//
// * InternalServerErrorException
// The request processing has failed because of an unknown error, exception,
// or failure.
//
// * LimitExceededException
// You have exceeded a service limit for your account. For more information,
// see Service Limits (https://docs.aws.amazon.com/app-mesh/latest/userguide/service-quotas.html)
// in the AWS App Mesh User Guide.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/CreateGatewayRoute
func (c *AppMesh) CreateGatewayRoute(input *CreateGatewayRouteInput) (*CreateGatewayRouteOutput, error) {
req, out := c.CreateGatewayRouteRequest(input)
return out, req.Send()
}
// CreateGatewayRouteWithContext is the same as CreateGatewayRoute with the addition of
// the ability to pass a context and additional request options.
//
// See CreateGatewayRoute for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *AppMesh) CreateGatewayRouteWithContext(ctx aws.Context, input *CreateGatewayRouteInput, opts ...request.Option) (*CreateGatewayRouteOutput, error) {
req, out := c.CreateGatewayRouteRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opCreateMesh = "CreateMesh"
// CreateMeshRequest generates a "aws/request.Request" representing the
// client's request for the CreateMesh operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See CreateMesh for more information on using the CreateMesh
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the CreateMeshRequest method.
// req, resp := client.CreateMeshRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/CreateMesh
func (c *AppMesh) CreateMeshRequest(input *CreateMeshInput) (req *request.Request, output *CreateMeshOutput) {
op := &request.Operation{
Name: opCreateMesh,
HTTPMethod: "PUT",
HTTPPath: "/v20190125/meshes",
}
if input == nil {
input = &CreateMeshInput{}
}
output = &CreateMeshOutput{}
req = c.newRequest(op, input, output)
return
}
// CreateMesh API operation for AWS App Mesh.
//
// Creates a service mesh.
//
// A service mesh is a logical boundary for network traffic between services
// that are represented by resources within the mesh. After you create your
// service mesh, you can create virtual services, virtual nodes, virtual routers,
// and routes to distribute traffic between the applications in your mesh.
//
// For more information about service meshes, see Service meshes (https://docs.aws.amazon.com/app-mesh/latest/userguide/meshes.html).
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for AWS App Mesh's
// API operation CreateMesh for usage and error information.
//
// Returned Error Types:
// * NotFoundException
// The specified resource doesn't exist. Check your request syntax and try again.
//
// * BadRequestException
// The request syntax was malformed. Check your request syntax and try again.
//
// * ConflictException
// The request contains a client token that was used for a previous update resource
// call with different specifications. Try the request again with a new client
// token.
//
// * TooManyRequestsException
// The maximum request rate permitted by the App Mesh APIs has been exceeded
// for your account. For best results, use an increasing or variable sleep interval
// between requests.
//
// * ForbiddenException
// You don't have permissions to perform this action.
//
// * ServiceUnavailableException
// The request has failed due to a temporary failure of the service.
//
// * InternalServerErrorException
// The request processing has failed because of an unknown error, exception,
// or failure.
//
// * LimitExceededException
// You have exceeded a service limit for your account. For more information,
// see Service Limits (https://docs.aws.amazon.com/app-mesh/latest/userguide/service-quotas.html)
// in the AWS App Mesh User Guide.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/CreateMesh
func (c *AppMesh) CreateMesh(input *CreateMeshInput) (*CreateMeshOutput, error) {
req, out := c.CreateMeshRequest(input)
return out, req.Send()
}
// CreateMeshWithContext is the same as CreateMesh with the addition of
// the ability to pass a context and additional request options.
//
// See CreateMesh for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *AppMesh) CreateMeshWithContext(ctx aws.Context, input *CreateMeshInput, opts ...request.Option) (*CreateMeshOutput, error) {
req, out := c.CreateMeshRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opCreateRoute = "CreateRoute"
// CreateRouteRequest generates a "aws/request.Request" representing the
// client's request for the CreateRoute operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See CreateRoute for more information on using the CreateRoute
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the CreateRouteRequest method.
// req, resp := client.CreateRouteRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/CreateRoute
func (c *AppMesh) CreateRouteRequest(input *CreateRouteInput) (req *request.Request, output *CreateRouteOutput) {
op := &request.Operation{
Name: opCreateRoute,
HTTPMethod: "PUT",
HTTPPath: "/v20190125/meshes/{meshName}/virtualRouter/{virtualRouterName}/routes",
}
if input == nil {
input = &CreateRouteInput{}
}
output = &CreateRouteOutput{}
req = c.newRequest(op, input, output)
return
}
// CreateRoute API operation for AWS App Mesh.
//
// Creates a route that is associated with a virtual router.
//
// You can route several different protocols and define a retry policy for a
// route. Traffic can be routed to one or more virtual nodes.
//
// For more information about routes, see Routes (https://docs.aws.amazon.com/app-mesh/latest/userguide/routes.html).
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for AWS App Mesh's
// API operation CreateRoute for usage and error information.
//
// Returned Error Types:
// * NotFoundException
// The specified resource doesn't exist. Check your request syntax and try again.
//
// * BadRequestException
// The request syntax was malformed. Check your request syntax and try again.
//
// * ConflictException
// The request contains a client token that was used for a previous update resource
// call with different specifications. Try the request again with a new client
// token.
//
// * TooManyRequestsException
// The maximum request rate permitted by the App Mesh APIs has been exceeded
// for your account. For best results, use an increasing or variable sleep interval
// between requests.
//
// * ForbiddenException
// You don't have permissions to perform this action.
//
// * ServiceUnavailableException
// The request has failed due to a temporary failure of the service.
//
// * InternalServerErrorException
// The request processing has failed because of an unknown error, exception,
// or failure.
//
// * LimitExceededException
// You have exceeded a service limit for your account. For more information,
// see Service Limits (https://docs.aws.amazon.com/app-mesh/latest/userguide/service-quotas.html)
// in the AWS App Mesh User Guide.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/CreateRoute
func (c *AppMesh) CreateRoute(input *CreateRouteInput) (*CreateRouteOutput, error) {
req, out := c.CreateRouteRequest(input)
return out, req.Send()
}
// CreateRouteWithContext is the same as CreateRoute with the addition of
// the ability to pass a context and additional request options.
//
// See CreateRoute for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *AppMesh) CreateRouteWithContext(ctx aws.Context, input *CreateRouteInput, opts ...request.Option) (*CreateRouteOutput, error) {
req, out := c.CreateRouteRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opCreateVirtualGateway = "CreateVirtualGateway"
// CreateVirtualGatewayRequest generates a "aws/request.Request" representing the
// client's request for the CreateVirtualGateway operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See CreateVirtualGateway for more information on using the CreateVirtualGateway
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the CreateVirtualGatewayRequest method.
// req, resp := client.CreateVirtualGatewayRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/CreateVirtualGateway
func (c *AppMesh) CreateVirtualGatewayRequest(input *CreateVirtualGatewayInput) (req *request.Request, output *CreateVirtualGatewayOutput) {
op := &request.Operation{
Name: opCreateVirtualGateway,
HTTPMethod: "PUT",
HTTPPath: "/v20190125/meshes/{meshName}/virtualGateways",
}
if input == nil {
input = &CreateVirtualGatewayInput{}
}
output = &CreateVirtualGatewayOutput{}
req = c.newRequest(op, input, output)
return
}
// CreateVirtualGateway API operation for AWS App Mesh.
//
// Creates a virtual gateway.
//
// A virtual gateway allows resources outside your mesh to communicate to resources
// that are inside your mesh. The virtual gateway represents an Envoy proxy
// running in an Amazon ECS task, in a Kubernetes service, or on an Amazon EC2
// instance. Unlike a virtual node, which represents an Envoy running with an
// application, a virtual gateway represents Envoy deployed by itself.
//
// For more information about virtual gateways, see Virtual gateways (https://docs.aws.amazon.com/app-mesh/latest/userguide/virtual_gateways.html).
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for AWS App Mesh's
// API operation CreateVirtualGateway for usage and error information.
//
// Returned Error Types:
// * NotFoundException
// The specified resource doesn't exist. Check your request syntax and try again.
//
// * BadRequestException
// The request syntax was malformed. Check your request syntax and try again.
//
// * ConflictException
// The request contains a client token that was used for a previous update resource
// call with different specifications. Try the request again with a new client
// token.
//
// * TooManyRequestsException
// The maximum request rate permitted by the App Mesh APIs has been exceeded
// for your account. For best results, use an increasing or variable sleep interval
// between requests.
//
// * ForbiddenException
// You don't have permissions to perform this action.
//
// * ServiceUnavailableException
// The request has failed due to a temporary failure of the service.
//
// * InternalServerErrorException
// The request processing has failed because of an unknown error, exception,
// or failure.
//
// * LimitExceededException
// You have exceeded a service limit for your account. For more information,
// see Service Limits (https://docs.aws.amazon.com/app-mesh/latest/userguide/service-quotas.html)
// in the AWS App Mesh User Guide.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/CreateVirtualGateway
func (c *AppMesh) CreateVirtualGateway(input *CreateVirtualGatewayInput) (*CreateVirtualGatewayOutput, error) {
req, out := c.CreateVirtualGatewayRequest(input)
return out, req.Send()
}
// CreateVirtualGatewayWithContext is the same as CreateVirtualGateway with the addition of
// the ability to pass a context and additional request options.
//
// See CreateVirtualGateway for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *AppMesh) CreateVirtualGatewayWithContext(ctx aws.Context, input *CreateVirtualGatewayInput, opts ...request.Option) (*CreateVirtualGatewayOutput, error) {
req, out := c.CreateVirtualGatewayRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opCreateVirtualNode = "CreateVirtualNode"
// CreateVirtualNodeRequest generates a "aws/request.Request" representing the
// client's request for the CreateVirtualNode operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See CreateVirtualNode for more information on using the CreateVirtualNode
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the CreateVirtualNodeRequest method.
// req, resp := client.CreateVirtualNodeRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/CreateVirtualNode
func (c *AppMesh) CreateVirtualNodeRequest(input *CreateVirtualNodeInput) (req *request.Request, output *CreateVirtualNodeOutput) {
op := &request.Operation{
Name: opCreateVirtualNode,
HTTPMethod: "PUT",
HTTPPath: "/v20190125/meshes/{meshName}/virtualNodes",
}
if input == nil {
input = &CreateVirtualNodeInput{}
}
output = &CreateVirtualNodeOutput{}
req = c.newRequest(op, input, output)
return
}
// CreateVirtualNode API operation for AWS App Mesh.
//
// Creates a virtual node within a service mesh.
//
// A virtual node acts as a logical pointer to a particular task group, such
// as an Amazon ECS service or a Kubernetes deployment. When you create a virtual
// node, you can specify the service discovery information for your task group,
// and whether the proxy running in a task group will communicate with other
// proxies using Transport Layer Security (TLS).
//
// You define a listener for any inbound traffic that your virtual node expects.
// Any virtual service that your virtual node expects to communicate to is specified
// as a backend.
//
// The response metadata for your new virtual node contains the arn that is
// associated with the virtual node. Set this value to the full ARN; for example,
// arn:aws:appmesh:us-west-2:123456789012:myMesh/default/virtualNode/myApp)
// as the APPMESH_RESOURCE_ARN environment variable for your task group's Envoy
// proxy container in your task definition or pod spec. This is then mapped
// to the node.id and node.cluster Envoy parameters.
//
// By default, App Mesh uses the name of the resource you specified in APPMESH_RESOURCE_ARN
// when Envoy is referring to itself in metrics and traces. You can override
// this behavior by setting the APPMESH_RESOURCE_CLUSTER environment variable
// with your own name.
//
// For more information about virtual nodes, see Virtual nodes (https://docs.aws.amazon.com/app-mesh/latest/userguide/virtual_nodes.html).
// You must be using 1.15.0 or later of the Envoy image when setting these variables.
// For more information aboutApp Mesh Envoy variables, see Envoy image (https://docs.aws.amazon.com/app-mesh/latest/userguide/envoy.html)
// in the AWS App Mesh User Guide.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for AWS App Mesh's
// API operation CreateVirtualNode for usage and error information.
//
// Returned Error Types:
// * NotFoundException
// The specified resource doesn't exist. Check your request syntax and try again.
//
// * BadRequestException
// The request syntax was malformed. Check your request syntax and try again.
//
// * ConflictException
// The request contains a client token that was used for a previous update resource
// call with different specifications. Try the request again with a new client
// token.
//
// * TooManyRequestsException
// The maximum request rate permitted by the App Mesh APIs has been exceeded
// for your account. For best results, use an increasing or variable sleep interval
// between requests.
//
// * ForbiddenException
// You don't have permissions to perform this action.
//
// * ServiceUnavailableException
// The request has failed due to a temporary failure of the service.
//
// * InternalServerErrorException
// The request processing has failed because of an unknown error, exception,
// or failure.
//
// * LimitExceededException
// You have exceeded a service limit for your account. For more information,
// see Service Limits (https://docs.aws.amazon.com/app-mesh/latest/userguide/service-quotas.html)
// in the AWS App Mesh User Guide.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/CreateVirtualNode
func (c *AppMesh) CreateVirtualNode(input *CreateVirtualNodeInput) (*CreateVirtualNodeOutput, error) {
req, out := c.CreateVirtualNodeRequest(input)
return out, req.Send()
}
// CreateVirtualNodeWithContext is the same as CreateVirtualNode with the addition of
// the ability to pass a context and additional request options.
//
// See CreateVirtualNode for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *AppMesh) CreateVirtualNodeWithContext(ctx aws.Context, input *CreateVirtualNodeInput, opts ...request.Option) (*CreateVirtualNodeOutput, error) {
req, out := c.CreateVirtualNodeRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opCreateVirtualRouter = "CreateVirtualRouter"
// CreateVirtualRouterRequest generates a "aws/request.Request" representing the
// client's request for the CreateVirtualRouter operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See CreateVirtualRouter for more information on using the CreateVirtualRouter
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the CreateVirtualRouterRequest method.
// req, resp := client.CreateVirtualRouterRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/CreateVirtualRouter
func (c *AppMesh) CreateVirtualRouterRequest(input *CreateVirtualRouterInput) (req *request.Request, output *CreateVirtualRouterOutput) {
op := &request.Operation{
Name: opCreateVirtualRouter,
HTTPMethod: "PUT",
HTTPPath: "/v20190125/meshes/{meshName}/virtualRouters",
}
if input == nil {
input = &CreateVirtualRouterInput{}
}
output = &CreateVirtualRouterOutput{}
req = c.newRequest(op, input, output)
return
}
// CreateVirtualRouter API operation for AWS App Mesh.
//
// Creates a virtual router within a service mesh.
//
// Specify a listener for any inbound traffic that your virtual router receives.
// Create a virtual router for each protocol and port that you need to route.
// Virtual routers handle traffic for one or more virtual services within your
// mesh. After you create your virtual router, create and associate routes for
// your virtual router that direct incoming requests to different virtual nodes.
//
// For more information about virtual routers, see Virtual routers (https://docs.aws.amazon.com/app-mesh/latest/userguide/virtual_routers.html).
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for AWS App Mesh's
// API operation CreateVirtualRouter for usage and error information.
//
// Returned Error Types:
// * NotFoundException
// The specified resource doesn't exist. Check your request syntax and try again.
//
// * BadRequestException
// The request syntax was malformed. Check your request syntax and try again.
//
// * ConflictException
// The request contains a client token that was used for a previous update resource
// call with different specifications. Try the request again with a new client
// token.
//
// * TooManyRequestsException
// The maximum request rate permitted by the App Mesh APIs has been exceeded
// for your account. For best results, use an increasing or variable sleep interval
// between requests.
//
// * ForbiddenException
// You don't have permissions to perform this action.
//
// * ServiceUnavailableException
// The request has failed due to a temporary failure of the service.
//
// * InternalServerErrorException
// The request processing has failed because of an unknown error, exception,
// or failure.
//
// * LimitExceededException
// You have exceeded a service limit for your account. For more information,
// see Service Limits (https://docs.aws.amazon.com/app-mesh/latest/userguide/service-quotas.html)
// in the AWS App Mesh User Guide.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/CreateVirtualRouter
func (c *AppMesh) CreateVirtualRouter(input *CreateVirtualRouterInput) (*CreateVirtualRouterOutput, error) {
req, out := c.CreateVirtualRouterRequest(input)
return out, req.Send()
}
// CreateVirtualRouterWithContext is the same as CreateVirtualRouter with the addition of
// the ability to pass a context and additional request options.
//
// See CreateVirtualRouter for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *AppMesh) CreateVirtualRouterWithContext(ctx aws.Context, input *CreateVirtualRouterInput, opts ...request.Option) (*CreateVirtualRouterOutput, error) {
req, out := c.CreateVirtualRouterRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opCreateVirtualService = "CreateVirtualService"
// CreateVirtualServiceRequest generates a "aws/request.Request" representing the
// client's request for the CreateVirtualService operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See CreateVirtualService for more information on using the CreateVirtualService
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the CreateVirtualServiceRequest method.
// req, resp := client.CreateVirtualServiceRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/CreateVirtualService
func (c *AppMesh) CreateVirtualServiceRequest(input *CreateVirtualServiceInput) (req *request.Request, output *CreateVirtualServiceOutput) {
op := &request.Operation{
Name: opCreateVirtualService,
HTTPMethod: "PUT",
HTTPPath: "/v20190125/meshes/{meshName}/virtualServices",
}
if input == nil {
input = &CreateVirtualServiceInput{}
}
output = &CreateVirtualServiceOutput{}
req = c.newRequest(op, input, output)
return
}
// CreateVirtualService API operation for AWS App Mesh.
//
// Creates a virtual service within a service mesh.
//
// A virtual service is an abstraction of a real service that is provided by
// a virtual node directly or indirectly by means of a virtual router. Dependent
// services call your virtual service by its virtualServiceName, and those requests
// are routed to the virtual node or virtual router that is specified as the
// provider for the virtual service.
//
// For more information about virtual services, see Virtual services (https://docs.aws.amazon.com/app-mesh/latest/userguide/virtual_services.html).
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for AWS App Mesh's
// API operation CreateVirtualService for usage and error information.
//
// Returned Error Types:
// * NotFoundException
// The specified resource doesn't exist. Check your request syntax and try again.
//
// * BadRequestException
// The request syntax was malformed. Check your request syntax and try again.
//
// * ConflictException
// The request contains a client token that was used for a previous update resource
// call with different specifications. Try the request again with a new client
// token.
//
// * TooManyRequestsException
// The maximum request rate permitted by the App Mesh APIs has been exceeded
// for your account. For best results, use an increasing or variable sleep interval
// between requests.
//
// * ForbiddenException
// You don't have permissions to perform this action.
//
// * ServiceUnavailableException
// The request has failed due to a temporary failure of the service.
//
// * InternalServerErrorException
// The request processing has failed because of an unknown error, exception,
// or failure.
//
// * LimitExceededException
// You have exceeded a service limit for your account. For more information,
// see Service Limits (https://docs.aws.amazon.com/app-mesh/latest/userguide/service-quotas.html)
// in the AWS App Mesh User Guide.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/CreateVirtualService
func (c *AppMesh) CreateVirtualService(input *CreateVirtualServiceInput) (*CreateVirtualServiceOutput, error) {
req, out := c.CreateVirtualServiceRequest(input)
return out, req.Send()
}
// CreateVirtualServiceWithContext is the same as CreateVirtualService with the addition of
// the ability to pass a context and additional request options.
//
// See CreateVirtualService for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *AppMesh) CreateVirtualServiceWithContext(ctx aws.Context, input *CreateVirtualServiceInput, opts ...request.Option) (*CreateVirtualServiceOutput, error) {
req, out := c.CreateVirtualServiceRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opDeleteGatewayRoute = "DeleteGatewayRoute"
// DeleteGatewayRouteRequest generates a "aws/request.Request" representing the
// client's request for the DeleteGatewayRoute operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See DeleteGatewayRoute for more information on using the DeleteGatewayRoute
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the DeleteGatewayRouteRequest method.
// req, resp := client.DeleteGatewayRouteRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/DeleteGatewayRoute
func (c *AppMesh) DeleteGatewayRouteRequest(input *DeleteGatewayRouteInput) (req *request.Request, output *DeleteGatewayRouteOutput) {
op := &request.Operation{
Name: opDeleteGatewayRoute,
HTTPMethod: "DELETE",
HTTPPath: "/v20190125/meshes/{meshName}/virtualGateway/{virtualGatewayName}/gatewayRoutes/{gatewayRouteName}",
}
if input == nil {
input = &DeleteGatewayRouteInput{}
}
output = &DeleteGatewayRouteOutput{}
req = c.newRequest(op, input, output)
return
}
// DeleteGatewayRoute API operation for AWS App Mesh.
//
// Deletes an existing gateway route.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for AWS App Mesh's
// API operation DeleteGatewayRoute for usage and error information.
//
// Returned Error Types:
// * NotFoundException
// The specified resource doesn't exist. Check your request syntax and try again.
//
// * BadRequestException
// The request syntax was malformed. Check your request syntax and try again.
//
// * TooManyRequestsException
// The maximum request rate permitted by the App Mesh APIs has been exceeded
// for your account. For best results, use an increasing or variable sleep interval
// between requests.
//
// * ForbiddenException
// You don't have permissions to perform this action.
//
// * ResourceInUseException
// You can't delete the specified resource because it's in use or required by
// another resource.
//
// * ServiceUnavailableException
// The request has failed due to a temporary failure of the service.
//
// * InternalServerErrorException
// The request processing has failed because of an unknown error, exception,
// or failure.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/DeleteGatewayRoute
func (c *AppMesh) DeleteGatewayRoute(input *DeleteGatewayRouteInput) (*DeleteGatewayRouteOutput, error) {
req, out := c.DeleteGatewayRouteRequest(input)
return out, req.Send()
}
// DeleteGatewayRouteWithContext is the same as DeleteGatewayRoute with the addition of
// the ability to pass a context and additional request options.
//
// See DeleteGatewayRoute for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *AppMesh) DeleteGatewayRouteWithContext(ctx aws.Context, input *DeleteGatewayRouteInput, opts ...request.Option) (*DeleteGatewayRouteOutput, error) {
req, out := c.DeleteGatewayRouteRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opDeleteMesh = "DeleteMesh"
// DeleteMeshRequest generates a "aws/request.Request" representing the
// client's request for the DeleteMesh operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See DeleteMesh for more information on using the DeleteMesh
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the DeleteMeshRequest method.
// req, resp := client.DeleteMeshRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/DeleteMesh
func (c *AppMesh) DeleteMeshRequest(input *DeleteMeshInput) (req *request.Request, output *DeleteMeshOutput) {
op := &request.Operation{
Name: opDeleteMesh,
HTTPMethod: "DELETE",
HTTPPath: "/v20190125/meshes/{meshName}",
}
if input == nil {
input = &DeleteMeshInput{}
}
output = &DeleteMeshOutput{}
req = c.newRequest(op, input, output)
return
}
// DeleteMesh API operation for AWS App Mesh.
//
// Deletes an existing service mesh.
//
// You must delete all resources (virtual services, routes, virtual routers,
// and virtual nodes) in the service mesh before you can delete the mesh itself.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for AWS App Mesh's
// API operation DeleteMesh for usage and error information.
//
// Returned Error Types:
// * NotFoundException
// The specified resource doesn't exist. Check your request syntax and try again.
//
// * BadRequestException
// The request syntax was malformed. Check your request syntax and try again.
//
// * TooManyRequestsException
// The maximum request rate permitted by the App Mesh APIs has been exceeded
// for your account. For best results, use an increasing or variable sleep interval
// between requests.
//
// * ForbiddenException
// You don't have permissions to perform this action.
//
// * ResourceInUseException
// You can't delete the specified resource because it's in use or required by
// another resource.
//
// * ServiceUnavailableException
// The request has failed due to a temporary failure of the service.
//
// * InternalServerErrorException
// The request processing has failed because of an unknown error, exception,
// or failure.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/DeleteMesh
func (c *AppMesh) DeleteMesh(input *DeleteMeshInput) (*DeleteMeshOutput, error) {
req, out := c.DeleteMeshRequest(input)
return out, req.Send()
}
// DeleteMeshWithContext is the same as DeleteMesh with the addition of
// the ability to pass a context and additional request options.
//
// See DeleteMesh for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *AppMesh) DeleteMeshWithContext(ctx aws.Context, input *DeleteMeshInput, opts ...request.Option) (*DeleteMeshOutput, error) {
req, out := c.DeleteMeshRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opDeleteRoute = "DeleteRoute"
// DeleteRouteRequest generates a "aws/request.Request" representing the
// client's request for the DeleteRoute operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See DeleteRoute for more information on using the DeleteRoute
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the DeleteRouteRequest method.
// req, resp := client.DeleteRouteRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/DeleteRoute
func (c *AppMesh) DeleteRouteRequest(input *DeleteRouteInput) (req *request.Request, output *DeleteRouteOutput) {
op := &request.Operation{
Name: opDeleteRoute,
HTTPMethod: "DELETE",
HTTPPath: "/v20190125/meshes/{meshName}/virtualRouter/{virtualRouterName}/routes/{routeName}",
}
if input == nil {
input = &DeleteRouteInput{}
}
output = &DeleteRouteOutput{}
req = c.newRequest(op, input, output)
return
}
// DeleteRoute API operation for AWS App Mesh.
//
// Deletes an existing route.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for AWS App Mesh's
// API operation DeleteRoute for usage and error information.
//
// Returned Error Types:
// * NotFoundException
// The specified resource doesn't exist. Check your request syntax and try again.
//
// * BadRequestException
// The request syntax was malformed. Check your request syntax and try again.
//
// * TooManyRequestsException
// The maximum request rate permitted by the App Mesh APIs has been exceeded
// for your account. For best results, use an increasing or variable sleep interval
// between requests.
//
// * ForbiddenException
// You don't have permissions to perform this action.
//
// * ResourceInUseException
// You can't delete the specified resource because it's in use or required by
// another resource.
//
// * ServiceUnavailableException
// The request has failed due to a temporary failure of the service.
//
// * InternalServerErrorException
// The request processing has failed because of an unknown error, exception,
// or failure.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/DeleteRoute
func (c *AppMesh) DeleteRoute(input *DeleteRouteInput) (*DeleteRouteOutput, error) {
req, out := c.DeleteRouteRequest(input)
return out, req.Send()
}
// DeleteRouteWithContext is the same as DeleteRoute with the addition of
// the ability to pass a context and additional request options.
//
// See DeleteRoute for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *AppMesh) DeleteRouteWithContext(ctx aws.Context, input *DeleteRouteInput, opts ...request.Option) (*DeleteRouteOutput, error) {
req, out := c.DeleteRouteRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opDeleteVirtualGateway = "DeleteVirtualGateway"
// DeleteVirtualGatewayRequest generates a "aws/request.Request" representing the
// client's request for the DeleteVirtualGateway operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See DeleteVirtualGateway for more information on using the DeleteVirtualGateway
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the DeleteVirtualGatewayRequest method.
// req, resp := client.DeleteVirtualGatewayRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/DeleteVirtualGateway
func (c *AppMesh) DeleteVirtualGatewayRequest(input *DeleteVirtualGatewayInput) (req *request.Request, output *DeleteVirtualGatewayOutput) {
op := &request.Operation{
Name: opDeleteVirtualGateway,
HTTPMethod: "DELETE",
HTTPPath: "/v20190125/meshes/{meshName}/virtualGateways/{virtualGatewayName}",
}
if input == nil {
input = &DeleteVirtualGatewayInput{}
}
output = &DeleteVirtualGatewayOutput{}
req = c.newRequest(op, input, output)
return
}
// DeleteVirtualGateway API operation for AWS App Mesh.
//
// Deletes an existing virtual gateway. You cannot delete a virtual gateway
// if any gateway routes are associated to it.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for AWS App Mesh's
// API operation DeleteVirtualGateway for usage and error information.
//
// Returned Error Types:
// * NotFoundException
// The specified resource doesn't exist. Check your request syntax and try again.
//
// * BadRequestException
// The request syntax was malformed. Check your request syntax and try again.
//
// * TooManyRequestsException
// The maximum request rate permitted by the App Mesh APIs has been exceeded
// for your account. For best results, use an increasing or variable sleep interval
// between requests.
//
// * ForbiddenException
// You don't have permissions to perform this action.
//
// * ResourceInUseException
// You can't delete the specified resource because it's in use or required by
// another resource.
//
// * ServiceUnavailableException
// The request has failed due to a temporary failure of the service.
//
// * InternalServerErrorException
// The request processing has failed because of an unknown error, exception,
// or failure.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/DeleteVirtualGateway
func (c *AppMesh) DeleteVirtualGateway(input *DeleteVirtualGatewayInput) (*DeleteVirtualGatewayOutput, error) {
req, out := c.DeleteVirtualGatewayRequest(input)
return out, req.Send()
}
// DeleteVirtualGatewayWithContext is the same as DeleteVirtualGateway with the addition of
// the ability to pass a context and additional request options.
//
// See DeleteVirtualGateway for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *AppMesh) DeleteVirtualGatewayWithContext(ctx aws.Context, input *DeleteVirtualGatewayInput, opts ...request.Option) (*DeleteVirtualGatewayOutput, error) {
req, out := c.DeleteVirtualGatewayRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opDeleteVirtualNode = "DeleteVirtualNode"
// DeleteVirtualNodeRequest generates a "aws/request.Request" representing the
// client's request for the DeleteVirtualNode operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See DeleteVirtualNode for more information on using the DeleteVirtualNode
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the DeleteVirtualNodeRequest method.
// req, resp := client.DeleteVirtualNodeRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/DeleteVirtualNode
func (c *AppMesh) DeleteVirtualNodeRequest(input *DeleteVirtualNodeInput) (req *request.Request, output *DeleteVirtualNodeOutput) {
op := &request.Operation{
Name: opDeleteVirtualNode,
HTTPMethod: "DELETE",
HTTPPath: "/v20190125/meshes/{meshName}/virtualNodes/{virtualNodeName}",
}
if input == nil {
input = &DeleteVirtualNodeInput{}
}
output = &DeleteVirtualNodeOutput{}
req = c.newRequest(op, input, output)
return
}
// DeleteVirtualNode API operation for AWS App Mesh.
//
// Deletes an existing virtual node.
//
// You must delete any virtual services that list a virtual node as a service
// provider before you can delete the virtual node itself.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for AWS App Mesh's
// API operation DeleteVirtualNode for usage and error information.
//
// Returned Error Types:
// * NotFoundException
// The specified resource doesn't exist. Check your request syntax and try again.
//
// * BadRequestException
// The request syntax was malformed. Check your request syntax and try again.
//
// * TooManyRequestsException
// The maximum request rate permitted by the App Mesh APIs has been exceeded
// for your account. For best results, use an increasing or variable sleep interval
// between requests.
//
// * ForbiddenException
// You don't have permissions to perform this action.
//
// * ResourceInUseException
// You can't delete the specified resource because it's in use or required by
// another resource.
//
// * ServiceUnavailableException
// The request has failed due to a temporary failure of the service.
//
// * InternalServerErrorException
// The request processing has failed because of an unknown error, exception,
// or failure.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/DeleteVirtualNode
func (c *AppMesh) DeleteVirtualNode(input *DeleteVirtualNodeInput) (*DeleteVirtualNodeOutput, error) {
req, out := c.DeleteVirtualNodeRequest(input)
return out, req.Send()
}
// DeleteVirtualNodeWithContext is the same as DeleteVirtualNode with the addition of
// the ability to pass a context and additional request options.
//
// See DeleteVirtualNode for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *AppMesh) DeleteVirtualNodeWithContext(ctx aws.Context, input *DeleteVirtualNodeInput, opts ...request.Option) (*DeleteVirtualNodeOutput, error) {
req, out := c.DeleteVirtualNodeRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opDeleteVirtualRouter = "DeleteVirtualRouter"
// DeleteVirtualRouterRequest generates a "aws/request.Request" representing the
// client's request for the DeleteVirtualRouter operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See DeleteVirtualRouter for more information on using the DeleteVirtualRouter
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the DeleteVirtualRouterRequest method.
// req, resp := client.DeleteVirtualRouterRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/DeleteVirtualRouter
func (c *AppMesh) DeleteVirtualRouterRequest(input *DeleteVirtualRouterInput) (req *request.Request, output *DeleteVirtualRouterOutput) {
op := &request.Operation{
Name: opDeleteVirtualRouter,
HTTPMethod: "DELETE",
HTTPPath: "/v20190125/meshes/{meshName}/virtualRouters/{virtualRouterName}",
}
if input == nil {
input = &DeleteVirtualRouterInput{}
}
output = &DeleteVirtualRouterOutput{}
req = c.newRequest(op, input, output)
return
}
// DeleteVirtualRouter API operation for AWS App Mesh.
//
// Deletes an existing virtual router.
//
// You must delete any routes associated with the virtual router before you
// can delete the router itself.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for AWS App Mesh's
// API operation DeleteVirtualRouter for usage and error information.
//
// Returned Error Types:
// * NotFoundException
// The specified resource doesn't exist. Check your request syntax and try again.
//
// * BadRequestException
// The request syntax was malformed. Check your request syntax and try again.
//
// * TooManyRequestsException
// The maximum request rate permitted by the App Mesh APIs has been exceeded
// for your account. For best results, use an increasing or variable sleep interval
// between requests.
//
// * ForbiddenException
// You don't have permissions to perform this action.
//
// * ResourceInUseException
// You can't delete the specified resource because it's in use or required by
// another resource.
//
// * ServiceUnavailableException
// The request has failed due to a temporary failure of the service.
//
// * InternalServerErrorException
// The request processing has failed because of an unknown error, exception,
// or failure.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/DeleteVirtualRouter
func (c *AppMesh) DeleteVirtualRouter(input *DeleteVirtualRouterInput) (*DeleteVirtualRouterOutput, error) {
req, out := c.DeleteVirtualRouterRequest(input)
return out, req.Send()
}
// DeleteVirtualRouterWithContext is the same as DeleteVirtualRouter with the addition of
// the ability to pass a context and additional request options.
//
// See DeleteVirtualRouter for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *AppMesh) DeleteVirtualRouterWithContext(ctx aws.Context, input *DeleteVirtualRouterInput, opts ...request.Option) (*DeleteVirtualRouterOutput, error) {
req, out := c.DeleteVirtualRouterRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opDeleteVirtualService = "DeleteVirtualService"
// DeleteVirtualServiceRequest generates a "aws/request.Request" representing the
// client's request for the DeleteVirtualService operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See DeleteVirtualService for more information on using the DeleteVirtualService
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the DeleteVirtualServiceRequest method.
// req, resp := client.DeleteVirtualServiceRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/DeleteVirtualService
func (c *AppMesh) DeleteVirtualServiceRequest(input *DeleteVirtualServiceInput) (req *request.Request, output *DeleteVirtualServiceOutput) {
op := &request.Operation{
Name: opDeleteVirtualService,
HTTPMethod: "DELETE",
HTTPPath: "/v20190125/meshes/{meshName}/virtualServices/{virtualServiceName}",
}
if input == nil {
input = &DeleteVirtualServiceInput{}
}
output = &DeleteVirtualServiceOutput{}
req = c.newRequest(op, input, output)
return
}
// DeleteVirtualService API operation for AWS App Mesh.
//
// Deletes an existing virtual service.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for AWS App Mesh's
// API operation DeleteVirtualService for usage and error information.
//
// Returned Error Types:
// * NotFoundException
// The specified resource doesn't exist. Check your request syntax and try again.
//
// * BadRequestException
// The request syntax was malformed. Check your request syntax and try again.
//
// * TooManyRequestsException
// The maximum request rate permitted by the App Mesh APIs has been exceeded
// for your account. For best results, use an increasing or variable sleep interval
// between requests.
//
// * ForbiddenException
// You don't have permissions to perform this action.
//
// * ResourceInUseException
// You can't delete the specified resource because it's in use or required by
// another resource.
//
// * ServiceUnavailableException
// The request has failed due to a temporary failure of the service.
//
// * InternalServerErrorException
// The request processing has failed because of an unknown error, exception,
// or failure.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/DeleteVirtualService
func (c *AppMesh) DeleteVirtualService(input *DeleteVirtualServiceInput) (*DeleteVirtualServiceOutput, error) {
req, out := c.DeleteVirtualServiceRequest(input)
return out, req.Send()
}
// DeleteVirtualServiceWithContext is the same as DeleteVirtualService with the addition of
// the ability to pass a context and additional request options.
//
// See DeleteVirtualService for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *AppMesh) DeleteVirtualServiceWithContext(ctx aws.Context, input *DeleteVirtualServiceInput, opts ...request.Option) (*DeleteVirtualServiceOutput, error) {
req, out := c.DeleteVirtualServiceRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opDescribeGatewayRoute = "DescribeGatewayRoute"
// DescribeGatewayRouteRequest generates a "aws/request.Request" representing the
// client's request for the DescribeGatewayRoute operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See DescribeGatewayRoute for more information on using the DescribeGatewayRoute
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the DescribeGatewayRouteRequest method.
// req, resp := client.DescribeGatewayRouteRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/DescribeGatewayRoute
func (c *AppMesh) DescribeGatewayRouteRequest(input *DescribeGatewayRouteInput) (req *request.Request, output *DescribeGatewayRouteOutput) {
op := &request.Operation{
Name: opDescribeGatewayRoute,
HTTPMethod: "GET",
HTTPPath: "/v20190125/meshes/{meshName}/virtualGateway/{virtualGatewayName}/gatewayRoutes/{gatewayRouteName}",
}
if input == nil {
input = &DescribeGatewayRouteInput{}
}
output = &DescribeGatewayRouteOutput{}
req = c.newRequest(op, input, output)
return
}
// DescribeGatewayRoute API operation for AWS App Mesh.
//
// Describes an existing gateway route.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for AWS App Mesh's
// API operation DescribeGatewayRoute for usage and error information.
//
// Returned Error Types:
// * NotFoundException
// The specified resource doesn't exist. Check your request syntax and try again.
//
// * BadRequestException
// The request syntax was malformed. Check your request syntax and try again.
//
// * TooManyRequestsException
// The maximum request rate permitted by the App Mesh APIs has been exceeded
// for your account. For best results, use an increasing or variable sleep interval
// between requests.
//
// * ForbiddenException
// You don't have permissions to perform this action.
//
// * ServiceUnavailableException
// The request has failed due to a temporary failure of the service.
//
// * InternalServerErrorException
// The request processing has failed because of an unknown error, exception,
// or failure.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/DescribeGatewayRoute
func (c *AppMesh) DescribeGatewayRoute(input *DescribeGatewayRouteInput) (*DescribeGatewayRouteOutput, error) {
req, out := c.DescribeGatewayRouteRequest(input)
return out, req.Send()
}
// DescribeGatewayRouteWithContext is the same as DescribeGatewayRoute with the addition of
// the ability to pass a context and additional request options.
//
// See DescribeGatewayRoute for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *AppMesh) DescribeGatewayRouteWithContext(ctx aws.Context, input *DescribeGatewayRouteInput, opts ...request.Option) (*DescribeGatewayRouteOutput, error) {
req, out := c.DescribeGatewayRouteRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opDescribeMesh = "DescribeMesh"
// DescribeMeshRequest generates a "aws/request.Request" representing the
// client's request for the DescribeMesh operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See DescribeMesh for more information on using the DescribeMesh
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the DescribeMeshRequest method.
// req, resp := client.DescribeMeshRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/DescribeMesh
func (c *AppMesh) DescribeMeshRequest(input *DescribeMeshInput) (req *request.Request, output *DescribeMeshOutput) {
op := &request.Operation{
Name: opDescribeMesh,
HTTPMethod: "GET",
HTTPPath: "/v20190125/meshes/{meshName}",
}
if input == nil {
input = &DescribeMeshInput{}
}
output = &DescribeMeshOutput{}
req = c.newRequest(op, input, output)
return
}
// DescribeMesh API operation for AWS App Mesh.
//
// Describes an existing service mesh.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for AWS App Mesh's
// API operation DescribeMesh for usage and error information.
//
// Returned Error Types:
// * NotFoundException
// The specified resource doesn't exist. Check your request syntax and try again.
//
// * BadRequestException
// The request syntax was malformed. Check your request syntax and try again.
//
// * TooManyRequestsException
// The maximum request rate permitted by the App Mesh APIs has been exceeded
// for your account. For best results, use an increasing or variable sleep interval
// between requests.
//
// * ForbiddenException
// You don't have permissions to perform this action.
//
// * ServiceUnavailableException
// The request has failed due to a temporary failure of the service.
//
// * InternalServerErrorException
// The request processing has failed because of an unknown error, exception,
// or failure.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/DescribeMesh
func (c *AppMesh) DescribeMesh(input *DescribeMeshInput) (*DescribeMeshOutput, error) {
req, out := c.DescribeMeshRequest(input)
return out, req.Send()
}
// DescribeMeshWithContext is the same as DescribeMesh with the addition of
// the ability to pass a context and additional request options.
//
// See DescribeMesh for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *AppMesh) DescribeMeshWithContext(ctx aws.Context, input *DescribeMeshInput, opts ...request.Option) (*DescribeMeshOutput, error) {
req, out := c.DescribeMeshRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opDescribeRoute = "DescribeRoute"
// DescribeRouteRequest generates a "aws/request.Request" representing the
// client's request for the DescribeRoute operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See DescribeRoute for more information on using the DescribeRoute
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the DescribeRouteRequest method.
// req, resp := client.DescribeRouteRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/DescribeRoute
func (c *AppMesh) DescribeRouteRequest(input *DescribeRouteInput) (req *request.Request, output *DescribeRouteOutput) {
op := &request.Operation{
Name: opDescribeRoute,
HTTPMethod: "GET",
HTTPPath: "/v20190125/meshes/{meshName}/virtualRouter/{virtualRouterName}/routes/{routeName}",
}
if input == nil {
input = &DescribeRouteInput{}
}
output = &DescribeRouteOutput{}
req = c.newRequest(op, input, output)
return
}
// DescribeRoute API operation for AWS App Mesh.
//
// Describes an existing route.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for AWS App Mesh's
// API operation DescribeRoute for usage and error information.
//
// Returned Error Types:
// * NotFoundException
// The specified resource doesn't exist. Check your request syntax and try again.
//
// * BadRequestException
// The request syntax was malformed. Check your request syntax and try again.
//
// * TooManyRequestsException
// The maximum request rate permitted by the App Mesh APIs has been exceeded
// for your account. For best results, use an increasing or variable sleep interval
// between requests.
//
// * ForbiddenException
// You don't have permissions to perform this action.
//
// * ServiceUnavailableException
// The request has failed due to a temporary failure of the service.
//
// * InternalServerErrorException
// The request processing has failed because of an unknown error, exception,
// or failure.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/DescribeRoute
func (c *AppMesh) DescribeRoute(input *DescribeRouteInput) (*DescribeRouteOutput, error) {
req, out := c.DescribeRouteRequest(input)
return out, req.Send()
}
// DescribeRouteWithContext is the same as DescribeRoute with the addition of
// the ability to pass a context and additional request options.
//
// See DescribeRoute for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *AppMesh) DescribeRouteWithContext(ctx aws.Context, input *DescribeRouteInput, opts ...request.Option) (*DescribeRouteOutput, error) {
req, out := c.DescribeRouteRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opDescribeVirtualGateway = "DescribeVirtualGateway"
// DescribeVirtualGatewayRequest generates a "aws/request.Request" representing the
// client's request for the DescribeVirtualGateway operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See DescribeVirtualGateway for more information on using the DescribeVirtualGateway
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the DescribeVirtualGatewayRequest method.
// req, resp := client.DescribeVirtualGatewayRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/DescribeVirtualGateway
func (c *AppMesh) DescribeVirtualGatewayRequest(input *DescribeVirtualGatewayInput) (req *request.Request, output *DescribeVirtualGatewayOutput) {
op := &request.Operation{
Name: opDescribeVirtualGateway,
HTTPMethod: "GET",
HTTPPath: "/v20190125/meshes/{meshName}/virtualGateways/{virtualGatewayName}",
}
if input == nil {
input = &DescribeVirtualGatewayInput{}
}
output = &DescribeVirtualGatewayOutput{}
req = c.newRequest(op, input, output)
return
}
// DescribeVirtualGateway API operation for AWS App Mesh.
//
// Describes an existing virtual gateway.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for AWS App Mesh's
// API operation DescribeVirtualGateway for usage and error information.
//
// Returned Error Types:
// * NotFoundException
// The specified resource doesn't exist. Check your request syntax and try again.
//
// * BadRequestException
// The request syntax was malformed. Check your request syntax and try again.
//
// * TooManyRequestsException
// The maximum request rate permitted by the App Mesh APIs has been exceeded
// for your account. For best results, use an increasing or variable sleep interval
// between requests.
//
// * ForbiddenException
// You don't have permissions to perform this action.
//
// * ServiceUnavailableException
// The request has failed due to a temporary failure of the service.
//
// * InternalServerErrorException
// The request processing has failed because of an unknown error, exception,
// or failure.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/DescribeVirtualGateway
func (c *AppMesh) DescribeVirtualGateway(input *DescribeVirtualGatewayInput) (*DescribeVirtualGatewayOutput, error) {
req, out := c.DescribeVirtualGatewayRequest(input)
return out, req.Send()
}
// DescribeVirtualGatewayWithContext is the same as DescribeVirtualGateway with the addition of
// the ability to pass a context and additional request options.
//
// See DescribeVirtualGateway for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *AppMesh) DescribeVirtualGatewayWithContext(ctx aws.Context, input *DescribeVirtualGatewayInput, opts ...request.Option) (*DescribeVirtualGatewayOutput, error) {
req, out := c.DescribeVirtualGatewayRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opDescribeVirtualNode = "DescribeVirtualNode"
// DescribeVirtualNodeRequest generates a "aws/request.Request" representing the
// client's request for the DescribeVirtualNode operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See DescribeVirtualNode for more information on using the DescribeVirtualNode
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the DescribeVirtualNodeRequest method.
// req, resp := client.DescribeVirtualNodeRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/DescribeVirtualNode
func (c *AppMesh) DescribeVirtualNodeRequest(input *DescribeVirtualNodeInput) (req *request.Request, output *DescribeVirtualNodeOutput) {
op := &request.Operation{
Name: opDescribeVirtualNode,
HTTPMethod: "GET",
HTTPPath: "/v20190125/meshes/{meshName}/virtualNodes/{virtualNodeName}",
}
if input == nil {
input = &DescribeVirtualNodeInput{}
}
output = &DescribeVirtualNodeOutput{}
req = c.newRequest(op, input, output)
return
}
// DescribeVirtualNode API operation for AWS App Mesh.
//
// Describes an existing virtual node.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for AWS App Mesh's
// API operation DescribeVirtualNode for usage and error information.
//
// Returned Error Types:
// * NotFoundException
// The specified resource doesn't exist. Check your request syntax and try again.
//
// * BadRequestException
// The request syntax was malformed. Check your request syntax and try again.
//
// * TooManyRequestsException
// The maximum request rate permitted by the App Mesh APIs has been exceeded
// for your account. For best results, use an increasing or variable sleep interval
// between requests.
//
// * ForbiddenException
// You don't have permissions to perform this action.
//
// * ServiceUnavailableException
// The request has failed due to a temporary failure of the service.
//
// * InternalServerErrorException
// The request processing has failed because of an unknown error, exception,
// or failure.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/DescribeVirtualNode
func (c *AppMesh) DescribeVirtualNode(input *DescribeVirtualNodeInput) (*DescribeVirtualNodeOutput, error) {
req, out := c.DescribeVirtualNodeRequest(input)
return out, req.Send()
}
// DescribeVirtualNodeWithContext is the same as DescribeVirtualNode with the addition of
// the ability to pass a context and additional request options.
//
// See DescribeVirtualNode for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *AppMesh) DescribeVirtualNodeWithContext(ctx aws.Context, input *DescribeVirtualNodeInput, opts ...request.Option) (*DescribeVirtualNodeOutput, error) {
req, out := c.DescribeVirtualNodeRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opDescribeVirtualRouter = "DescribeVirtualRouter"
// DescribeVirtualRouterRequest generates a "aws/request.Request" representing the
// client's request for the DescribeVirtualRouter operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See DescribeVirtualRouter for more information on using the DescribeVirtualRouter
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the DescribeVirtualRouterRequest method.
// req, resp := client.DescribeVirtualRouterRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/DescribeVirtualRouter
func (c *AppMesh) DescribeVirtualRouterRequest(input *DescribeVirtualRouterInput) (req *request.Request, output *DescribeVirtualRouterOutput) {
op := &request.Operation{
Name: opDescribeVirtualRouter,
HTTPMethod: "GET",
HTTPPath: "/v20190125/meshes/{meshName}/virtualRouters/{virtualRouterName}",
}
if input == nil {
input = &DescribeVirtualRouterInput{}
}
output = &DescribeVirtualRouterOutput{}
req = c.newRequest(op, input, output)
return
}
// DescribeVirtualRouter API operation for AWS App Mesh.
//
// Describes an existing virtual router.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for AWS App Mesh's
// API operation DescribeVirtualRouter for usage and error information.
//
// Returned Error Types:
// * NotFoundException
// The specified resource doesn't exist. Check your request syntax and try again.
//
// * BadRequestException
// The request syntax was malformed. Check your request syntax and try again.
//
// * TooManyRequestsException
// The maximum request rate permitted by the App Mesh APIs has been exceeded
// for your account. For best results, use an increasing or variable sleep interval
// between requests.
//
// * ForbiddenException
// You don't have permissions to perform this action.
//
// * ServiceUnavailableException
// The request has failed due to a temporary failure of the service.
//
// * InternalServerErrorException
// The request processing has failed because of an unknown error, exception,
// or failure.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/DescribeVirtualRouter
func (c *AppMesh) DescribeVirtualRouter(input *DescribeVirtualRouterInput) (*DescribeVirtualRouterOutput, error) {
req, out := c.DescribeVirtualRouterRequest(input)
return out, req.Send()
}
// DescribeVirtualRouterWithContext is the same as DescribeVirtualRouter with the addition of
// the ability to pass a context and additional request options.
//
// See DescribeVirtualRouter for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *AppMesh) DescribeVirtualRouterWithContext(ctx aws.Context, input *DescribeVirtualRouterInput, opts ...request.Option) (*DescribeVirtualRouterOutput, error) {
req, out := c.DescribeVirtualRouterRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opDescribeVirtualService = "DescribeVirtualService"
// DescribeVirtualServiceRequest generates a "aws/request.Request" representing the
// client's request for the DescribeVirtualService operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See DescribeVirtualService for more information on using the DescribeVirtualService
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the DescribeVirtualServiceRequest method.
// req, resp := client.DescribeVirtualServiceRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/DescribeVirtualService
func (c *AppMesh) DescribeVirtualServiceRequest(input *DescribeVirtualServiceInput) (req *request.Request, output *DescribeVirtualServiceOutput) {
op := &request.Operation{
Name: opDescribeVirtualService,
HTTPMethod: "GET",
HTTPPath: "/v20190125/meshes/{meshName}/virtualServices/{virtualServiceName}",
}
if input == nil {
input = &DescribeVirtualServiceInput{}
}
output = &DescribeVirtualServiceOutput{}
req = c.newRequest(op, input, output)
return
}
// DescribeVirtualService API operation for AWS App Mesh.
//
// Describes an existing virtual service.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for AWS App Mesh's
// API operation DescribeVirtualService for usage and error information.
//
// Returned Error Types:
// * NotFoundException
// The specified resource doesn't exist. Check your request syntax and try again.
//
// * BadRequestException
// The request syntax was malformed. Check your request syntax and try again.
//
// * TooManyRequestsException
// The maximum request rate permitted by the App Mesh APIs has been exceeded
// for your account. For best results, use an increasing or variable sleep interval
// between requests.
//
// * ForbiddenException
// You don't have permissions to perform this action.
//
// * ServiceUnavailableException
// The request has failed due to a temporary failure of the service.
//
// * InternalServerErrorException
// The request processing has failed because of an unknown error, exception,
// or failure.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/DescribeVirtualService
func (c *AppMesh) DescribeVirtualService(input *DescribeVirtualServiceInput) (*DescribeVirtualServiceOutput, error) {
req, out := c.DescribeVirtualServiceRequest(input)
return out, req.Send()
}
// DescribeVirtualServiceWithContext is the same as DescribeVirtualService with the addition of
// the ability to pass a context and additional request options.
//
// See DescribeVirtualService for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *AppMesh) DescribeVirtualServiceWithContext(ctx aws.Context, input *DescribeVirtualServiceInput, opts ...request.Option) (*DescribeVirtualServiceOutput, error) {
req, out := c.DescribeVirtualServiceRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opListGatewayRoutes = "ListGatewayRoutes"
// ListGatewayRoutesRequest generates a "aws/request.Request" representing the
// client's request for the ListGatewayRoutes operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See ListGatewayRoutes for more information on using the ListGatewayRoutes
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the ListGatewayRoutesRequest method.
// req, resp := client.ListGatewayRoutesRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/ListGatewayRoutes
func (c *AppMesh) ListGatewayRoutesRequest(input *ListGatewayRoutesInput) (req *request.Request, output *ListGatewayRoutesOutput) {
op := &request.Operation{
Name: opListGatewayRoutes,
HTTPMethod: "GET",
HTTPPath: "/v20190125/meshes/{meshName}/virtualGateway/{virtualGatewayName}/gatewayRoutes",
Paginator: &request.Paginator{
InputTokens: []string{"nextToken"},
OutputTokens: []string{"nextToken"},
LimitToken: "limit",
TruncationToken: "",
},
}
if input == nil {
input = &ListGatewayRoutesInput{}
}
output = &ListGatewayRoutesOutput{}
req = c.newRequest(op, input, output)
return
}
// ListGatewayRoutes API operation for AWS App Mesh.
//
// Returns a list of existing gateway routes that are associated to a virtual
// gateway.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for AWS App Mesh's
// API operation ListGatewayRoutes for usage and error information.
//
// Returned Error Types:
// * NotFoundException
// The specified resource doesn't exist. Check your request syntax and try again.
//
// * BadRequestException
// The request syntax was malformed. Check your request syntax and try again.
//
// * TooManyRequestsException
// The maximum request rate permitted by the App Mesh APIs has been exceeded
// for your account. For best results, use an increasing or variable sleep interval
// between requests.
//
// * ForbiddenException
// You don't have permissions to perform this action.
//
// * ServiceUnavailableException
// The request has failed due to a temporary failure of the service.
//
// * InternalServerErrorException
// The request processing has failed because of an unknown error, exception,
// or failure.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/ListGatewayRoutes
func (c *AppMesh) ListGatewayRoutes(input *ListGatewayRoutesInput) (*ListGatewayRoutesOutput, error) {
req, out := c.ListGatewayRoutesRequest(input)
return out, req.Send()
}
// ListGatewayRoutesWithContext is the same as ListGatewayRoutes with the addition of
// the ability to pass a context and additional request options.
//
// See ListGatewayRoutes for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *AppMesh) ListGatewayRoutesWithContext(ctx aws.Context, input *ListGatewayRoutesInput, opts ...request.Option) (*ListGatewayRoutesOutput, error) {
req, out := c.ListGatewayRoutesRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
// ListGatewayRoutesPages iterates over the pages of a ListGatewayRoutes operation,
// calling the "fn" function with the response data for each page. To stop
// iterating, return false from the fn function.
//
// See ListGatewayRoutes method for more information on how to use this operation.
//
// Note: This operation can generate multiple requests to a service.
//
// // Example iterating over at most 3 pages of a ListGatewayRoutes operation.
// pageNum := 0
// err := client.ListGatewayRoutesPages(params,
// func(page *appmesh.ListGatewayRoutesOutput, lastPage bool) bool {
// pageNum++
// fmt.Println(page)
// return pageNum <= 3
// })
//
func (c *AppMesh) ListGatewayRoutesPages(input *ListGatewayRoutesInput, fn func(*ListGatewayRoutesOutput, bool) bool) error {
return c.ListGatewayRoutesPagesWithContext(aws.BackgroundContext(), input, fn)
}
// ListGatewayRoutesPagesWithContext same as ListGatewayRoutesPages except
// it takes a Context and allows setting request options on the pages.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *AppMesh) ListGatewayRoutesPagesWithContext(ctx aws.Context, input *ListGatewayRoutesInput, fn func(*ListGatewayRoutesOutput, bool) bool, opts ...request.Option) error {
p := request.Pagination{
NewRequest: func() (*request.Request, error) {
var inCpy *ListGatewayRoutesInput
if input != nil {
tmp := *input
inCpy = &tmp
}
req, _ := c.ListGatewayRoutesRequest(inCpy)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return req, nil
},
}
for p.Next() {
if !fn(p.Page().(*ListGatewayRoutesOutput), !p.HasNextPage()) {
break
}
}
return p.Err()
}
const opListMeshes = "ListMeshes"
// ListMeshesRequest generates a "aws/request.Request" representing the
// client's request for the ListMeshes operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See ListMeshes for more information on using the ListMeshes
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the ListMeshesRequest method.
// req, resp := client.ListMeshesRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/ListMeshes
func (c *AppMesh) ListMeshesRequest(input *ListMeshesInput) (req *request.Request, output *ListMeshesOutput) {
op := &request.Operation{
Name: opListMeshes,
HTTPMethod: "GET",
HTTPPath: "/v20190125/meshes",
Paginator: &request.Paginator{
InputTokens: []string{"nextToken"},
OutputTokens: []string{"nextToken"},
LimitToken: "limit",
TruncationToken: "",
},
}
if input == nil {
input = &ListMeshesInput{}
}
output = &ListMeshesOutput{}
req = c.newRequest(op, input, output)
return
}
// ListMeshes API operation for AWS App Mesh.
//
// Returns a list of existing service meshes.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for AWS App Mesh's
// API operation ListMeshes for usage and error information.
//
// Returned Error Types:
// * NotFoundException
// The specified resource doesn't exist. Check your request syntax and try again.
//
// * BadRequestException
// The request syntax was malformed. Check your request syntax and try again.
//
// * TooManyRequestsException
// The maximum request rate permitted by the App Mesh APIs has been exceeded
// for your account. For best results, use an increasing or variable sleep interval
// between requests.
//
// * ForbiddenException
// You don't have permissions to perform this action.
//
// * ServiceUnavailableException
// The request has failed due to a temporary failure of the service.
//
// * InternalServerErrorException
// The request processing has failed because of an unknown error, exception,
// or failure.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/ListMeshes
func (c *AppMesh) ListMeshes(input *ListMeshesInput) (*ListMeshesOutput, error) {
req, out := c.ListMeshesRequest(input)
return out, req.Send()
}
// ListMeshesWithContext is the same as ListMeshes with the addition of
// the ability to pass a context and additional request options.
//
// See ListMeshes for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *AppMesh) ListMeshesWithContext(ctx aws.Context, input *ListMeshesInput, opts ...request.Option) (*ListMeshesOutput, error) {
req, out := c.ListMeshesRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
// ListMeshesPages iterates over the pages of a ListMeshes operation,
// calling the "fn" function with the response data for each page. To stop
// iterating, return false from the fn function.
//
// See ListMeshes method for more information on how to use this operation.
//
// Note: This operation can generate multiple requests to a service.
//
// // Example iterating over at most 3 pages of a ListMeshes operation.
// pageNum := 0
// err := client.ListMeshesPages(params,
// func(page *appmesh.ListMeshesOutput, lastPage bool) bool {
// pageNum++
// fmt.Println(page)
// return pageNum <= 3
// })
//
func (c *AppMesh) ListMeshesPages(input *ListMeshesInput, fn func(*ListMeshesOutput, bool) bool) error {
return c.ListMeshesPagesWithContext(aws.BackgroundContext(), input, fn)
}
// ListMeshesPagesWithContext same as ListMeshesPages except
// it takes a Context and allows setting request options on the pages.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *AppMesh) ListMeshesPagesWithContext(ctx aws.Context, input *ListMeshesInput, fn func(*ListMeshesOutput, bool) bool, opts ...request.Option) error {
p := request.Pagination{
NewRequest: func() (*request.Request, error) {
var inCpy *ListMeshesInput
if input != nil {
tmp := *input
inCpy = &tmp
}
req, _ := c.ListMeshesRequest(inCpy)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return req, nil
},
}
for p.Next() {
if !fn(p.Page().(*ListMeshesOutput), !p.HasNextPage()) {
break
}
}
return p.Err()
}
const opListRoutes = "ListRoutes"
// ListRoutesRequest generates a "aws/request.Request" representing the
// client's request for the ListRoutes operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See ListRoutes for more information on using the ListRoutes
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the ListRoutesRequest method.
// req, resp := client.ListRoutesRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/ListRoutes
func (c *AppMesh) ListRoutesRequest(input *ListRoutesInput) (req *request.Request, output *ListRoutesOutput) {
op := &request.Operation{
Name: opListRoutes,
HTTPMethod: "GET",
HTTPPath: "/v20190125/meshes/{meshName}/virtualRouter/{virtualRouterName}/routes",
Paginator: &request.Paginator{
InputTokens: []string{"nextToken"},
OutputTokens: []string{"nextToken"},
LimitToken: "limit",
TruncationToken: "",
},
}
if input == nil {
input = &ListRoutesInput{}
}
output = &ListRoutesOutput{}
req = c.newRequest(op, input, output)
return
}
// ListRoutes API operation for AWS App Mesh.
//
// Returns a list of existing routes in a service mesh.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for AWS App Mesh's
// API operation ListRoutes for usage and error information.
//
// Returned Error Types:
// * NotFoundException
// The specified resource doesn't exist. Check your request syntax and try again.
//
// * BadRequestException
// The request syntax was malformed. Check your request syntax and try again.
//
// * TooManyRequestsException
// The maximum request rate permitted by the App Mesh APIs has been exceeded
// for your account. For best results, use an increasing or variable sleep interval
// between requests.
//
// * ForbiddenException
// You don't have permissions to perform this action.
//
// * ServiceUnavailableException
// The request has failed due to a temporary failure of the service.
//
// * InternalServerErrorException
// The request processing has failed because of an unknown error, exception,
// or failure.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/ListRoutes
func (c *AppMesh) ListRoutes(input *ListRoutesInput) (*ListRoutesOutput, error) {
req, out := c.ListRoutesRequest(input)
return out, req.Send()
}
// ListRoutesWithContext is the same as ListRoutes with the addition of
// the ability to pass a context and additional request options.
//
// See ListRoutes for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *AppMesh) ListRoutesWithContext(ctx aws.Context, input *ListRoutesInput, opts ...request.Option) (*ListRoutesOutput, error) {
req, out := c.ListRoutesRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
// ListRoutesPages iterates over the pages of a ListRoutes operation,
// calling the "fn" function with the response data for each page. To stop
// iterating, return false from the fn function.
//
// See ListRoutes method for more information on how to use this operation.
//
// Note: This operation can generate multiple requests to a service.
//
// // Example iterating over at most 3 pages of a ListRoutes operation.
// pageNum := 0
// err := client.ListRoutesPages(params,
// func(page *appmesh.ListRoutesOutput, lastPage bool) bool {
// pageNum++
// fmt.Println(page)
// return pageNum <= 3
// })
//
func (c *AppMesh) ListRoutesPages(input *ListRoutesInput, fn func(*ListRoutesOutput, bool) bool) error {
return c.ListRoutesPagesWithContext(aws.BackgroundContext(), input, fn)
}
// ListRoutesPagesWithContext same as ListRoutesPages except
// it takes a Context and allows setting request options on the pages.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *AppMesh) ListRoutesPagesWithContext(ctx aws.Context, input *ListRoutesInput, fn func(*ListRoutesOutput, bool) bool, opts ...request.Option) error {
p := request.Pagination{
NewRequest: func() (*request.Request, error) {
var inCpy *ListRoutesInput
if input != nil {
tmp := *input
inCpy = &tmp
}
req, _ := c.ListRoutesRequest(inCpy)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return req, nil
},
}
for p.Next() {
if !fn(p.Page().(*ListRoutesOutput), !p.HasNextPage()) {
break
}
}
return p.Err()
}
const opListTagsForResource = "ListTagsForResource"
// ListTagsForResourceRequest generates a "aws/request.Request" representing the
// client's request for the ListTagsForResource operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See ListTagsForResource for more information on using the ListTagsForResource
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the ListTagsForResourceRequest method.
// req, resp := client.ListTagsForResourceRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/ListTagsForResource
func (c *AppMesh) ListTagsForResourceRequest(input *ListTagsForResourceInput) (req *request.Request, output *ListTagsForResourceOutput) {
op := &request.Operation{
Name: opListTagsForResource,
HTTPMethod: "GET",
HTTPPath: "/v20190125/tags",
Paginator: &request.Paginator{
InputTokens: []string{"nextToken"},
OutputTokens: []string{"nextToken"},
LimitToken: "limit",
TruncationToken: "",
},
}
if input == nil {
input = &ListTagsForResourceInput{}
}
output = &ListTagsForResourceOutput{}
req = c.newRequest(op, input, output)
return
}
// ListTagsForResource API operation for AWS App Mesh.
//
// List the tags for an App Mesh resource.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for AWS App Mesh's
// API operation ListTagsForResource for usage and error information.
//
// Returned Error Types:
// * NotFoundException
// The specified resource doesn't exist. Check your request syntax and try again.
//
// * BadRequestException
// The request syntax was malformed. Check your request syntax and try again.
//
// * TooManyRequestsException
// The maximum request rate permitted by the App Mesh APIs has been exceeded
// for your account. For best results, use an increasing or variable sleep interval
// between requests.
//
// * ForbiddenException
// You don't have permissions to perform this action.
//
// * ServiceUnavailableException
// The request has failed due to a temporary failure of the service.
//
// * InternalServerErrorException
// The request processing has failed because of an unknown error, exception,
// or failure.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/ListTagsForResource
func (c *AppMesh) ListTagsForResource(input *ListTagsForResourceInput) (*ListTagsForResourceOutput, error) {
req, out := c.ListTagsForResourceRequest(input)
return out, req.Send()
}
// ListTagsForResourceWithContext is the same as ListTagsForResource with the addition of
// the ability to pass a context and additional request options.
//
// See ListTagsForResource for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *AppMesh) ListTagsForResourceWithContext(ctx aws.Context, input *ListTagsForResourceInput, opts ...request.Option) (*ListTagsForResourceOutput, error) {
req, out := c.ListTagsForResourceRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
// ListTagsForResourcePages iterates over the pages of a ListTagsForResource operation,
// calling the "fn" function with the response data for each page. To stop
// iterating, return false from the fn function.
//
// See ListTagsForResource method for more information on how to use this operation.
//
// Note: This operation can generate multiple requests to a service.
//
// // Example iterating over at most 3 pages of a ListTagsForResource operation.
// pageNum := 0
// err := client.ListTagsForResourcePages(params,
// func(page *appmesh.ListTagsForResourceOutput, lastPage bool) bool {
// pageNum++
// fmt.Println(page)
// return pageNum <= 3
// })
//
func (c *AppMesh) ListTagsForResourcePages(input *ListTagsForResourceInput, fn func(*ListTagsForResourceOutput, bool) bool) error {
return c.ListTagsForResourcePagesWithContext(aws.BackgroundContext(), input, fn)
}
// ListTagsForResourcePagesWithContext same as ListTagsForResourcePages except
// it takes a Context and allows setting request options on the pages.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *AppMesh) ListTagsForResourcePagesWithContext(ctx aws.Context, input *ListTagsForResourceInput, fn func(*ListTagsForResourceOutput, bool) bool, opts ...request.Option) error {
p := request.Pagination{
NewRequest: func() (*request.Request, error) {
var inCpy *ListTagsForResourceInput
if input != nil {
tmp := *input
inCpy = &tmp
}
req, _ := c.ListTagsForResourceRequest(inCpy)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return req, nil
},
}
for p.Next() {
if !fn(p.Page().(*ListTagsForResourceOutput), !p.HasNextPage()) {
break
}
}
return p.Err()
}
const opListVirtualGateways = "ListVirtualGateways"
// ListVirtualGatewaysRequest generates a "aws/request.Request" representing the
// client's request for the ListVirtualGateways operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See ListVirtualGateways for more information on using the ListVirtualGateways
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the ListVirtualGatewaysRequest method.
// req, resp := client.ListVirtualGatewaysRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/ListVirtualGateways
func (c *AppMesh) ListVirtualGatewaysRequest(input *ListVirtualGatewaysInput) (req *request.Request, output *ListVirtualGatewaysOutput) {
op := &request.Operation{
Name: opListVirtualGateways,
HTTPMethod: "GET",
HTTPPath: "/v20190125/meshes/{meshName}/virtualGateways",
Paginator: &request.Paginator{
InputTokens: []string{"nextToken"},
OutputTokens: []string{"nextToken"},
LimitToken: "limit",
TruncationToken: "",
},
}
if input == nil {
input = &ListVirtualGatewaysInput{}
}
output = &ListVirtualGatewaysOutput{}
req = c.newRequest(op, input, output)
return
}
// ListVirtualGateways API operation for AWS App Mesh.
//
// Returns a list of existing virtual gateways in a service mesh.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for AWS App Mesh's
// API operation ListVirtualGateways for usage and error information.
//
// Returned Error Types:
// * NotFoundException
// The specified resource doesn't exist. Check your request syntax and try again.
//
// * BadRequestException
// The request syntax was malformed. Check your request syntax and try again.
//
// * TooManyRequestsException
// The maximum request rate permitted by the App Mesh APIs has been exceeded
// for your account. For best results, use an increasing or variable sleep interval
// between requests.
//
// * ForbiddenException
// You don't have permissions to perform this action.
//
// * ServiceUnavailableException
// The request has failed due to a temporary failure of the service.
//
// * InternalServerErrorException
// The request processing has failed because of an unknown error, exception,
// or failure.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/ListVirtualGateways
func (c *AppMesh) ListVirtualGateways(input *ListVirtualGatewaysInput) (*ListVirtualGatewaysOutput, error) {
req, out := c.ListVirtualGatewaysRequest(input)
return out, req.Send()
}
// ListVirtualGatewaysWithContext is the same as ListVirtualGateways with the addition of
// the ability to pass a context and additional request options.
//
// See ListVirtualGateways for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *AppMesh) ListVirtualGatewaysWithContext(ctx aws.Context, input *ListVirtualGatewaysInput, opts ...request.Option) (*ListVirtualGatewaysOutput, error) {
req, out := c.ListVirtualGatewaysRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
// ListVirtualGatewaysPages iterates over the pages of a ListVirtualGateways operation,
// calling the "fn" function with the response data for each page. To stop
// iterating, return false from the fn function.
//
// See ListVirtualGateways method for more information on how to use this operation.
//
// Note: This operation can generate multiple requests to a service.
//
// // Example iterating over at most 3 pages of a ListVirtualGateways operation.
// pageNum := 0
// err := client.ListVirtualGatewaysPages(params,
// func(page *appmesh.ListVirtualGatewaysOutput, lastPage bool) bool {
// pageNum++
// fmt.Println(page)
// return pageNum <= 3
// })
//
func (c *AppMesh) ListVirtualGatewaysPages(input *ListVirtualGatewaysInput, fn func(*ListVirtualGatewaysOutput, bool) bool) error {
return c.ListVirtualGatewaysPagesWithContext(aws.BackgroundContext(), input, fn)
}
// ListVirtualGatewaysPagesWithContext same as ListVirtualGatewaysPages except
// it takes a Context and allows setting request options on the pages.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *AppMesh) ListVirtualGatewaysPagesWithContext(ctx aws.Context, input *ListVirtualGatewaysInput, fn func(*ListVirtualGatewaysOutput, bool) bool, opts ...request.Option) error {
p := request.Pagination{
NewRequest: func() (*request.Request, error) {
var inCpy *ListVirtualGatewaysInput
if input != nil {
tmp := *input
inCpy = &tmp
}
req, _ := c.ListVirtualGatewaysRequest(inCpy)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return req, nil
},
}
for p.Next() {
if !fn(p.Page().(*ListVirtualGatewaysOutput), !p.HasNextPage()) {
break
}
}
return p.Err()
}
const opListVirtualNodes = "ListVirtualNodes"
// ListVirtualNodesRequest generates a "aws/request.Request" representing the
// client's request for the ListVirtualNodes operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See ListVirtualNodes for more information on using the ListVirtualNodes
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the ListVirtualNodesRequest method.
// req, resp := client.ListVirtualNodesRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/ListVirtualNodes
func (c *AppMesh) ListVirtualNodesRequest(input *ListVirtualNodesInput) (req *request.Request, output *ListVirtualNodesOutput) {
op := &request.Operation{
Name: opListVirtualNodes,
HTTPMethod: "GET",
HTTPPath: "/v20190125/meshes/{meshName}/virtualNodes",
Paginator: &request.Paginator{
InputTokens: []string{"nextToken"},
OutputTokens: []string{"nextToken"},
LimitToken: "limit",
TruncationToken: "",
},
}
if input == nil {
input = &ListVirtualNodesInput{}
}
output = &ListVirtualNodesOutput{}
req = c.newRequest(op, input, output)
return
}
// ListVirtualNodes API operation for AWS App Mesh.
//
// Returns a list of existing virtual nodes.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for AWS App Mesh's
// API operation ListVirtualNodes for usage and error information.
//
// Returned Error Types:
// * NotFoundException
// The specified resource doesn't exist. Check your request syntax and try again.
//
// * BadRequestException
// The request syntax was malformed. Check your request syntax and try again.
//
// * TooManyRequestsException
// The maximum request rate permitted by the App Mesh APIs has been exceeded
// for your account. For best results, use an increasing or variable sleep interval
// between requests.
//
// * ForbiddenException
// You don't have permissions to perform this action.
//
// * ServiceUnavailableException
// The request has failed due to a temporary failure of the service.
//
// * InternalServerErrorException
// The request processing has failed because of an unknown error, exception,
// or failure.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/ListVirtualNodes
func (c *AppMesh) ListVirtualNodes(input *ListVirtualNodesInput) (*ListVirtualNodesOutput, error) {
req, out := c.ListVirtualNodesRequest(input)
return out, req.Send()
}
// ListVirtualNodesWithContext is the same as ListVirtualNodes with the addition of
// the ability to pass a context and additional request options.
//
// See ListVirtualNodes for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *AppMesh) ListVirtualNodesWithContext(ctx aws.Context, input *ListVirtualNodesInput, opts ...request.Option) (*ListVirtualNodesOutput, error) {
req, out := c.ListVirtualNodesRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
// ListVirtualNodesPages iterates over the pages of a ListVirtualNodes operation,
// calling the "fn" function with the response data for each page. To stop
// iterating, return false from the fn function.
//
// See ListVirtualNodes method for more information on how to use this operation.
//
// Note: This operation can generate multiple requests to a service.
//
// // Example iterating over at most 3 pages of a ListVirtualNodes operation.
// pageNum := 0
// err := client.ListVirtualNodesPages(params,
// func(page *appmesh.ListVirtualNodesOutput, lastPage bool) bool {
// pageNum++
// fmt.Println(page)
// return pageNum <= 3
// })
//
func (c *AppMesh) ListVirtualNodesPages(input *ListVirtualNodesInput, fn func(*ListVirtualNodesOutput, bool) bool) error {
return c.ListVirtualNodesPagesWithContext(aws.BackgroundContext(), input, fn)
}
// ListVirtualNodesPagesWithContext same as ListVirtualNodesPages except
// it takes a Context and allows setting request options on the pages.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *AppMesh) ListVirtualNodesPagesWithContext(ctx aws.Context, input *ListVirtualNodesInput, fn func(*ListVirtualNodesOutput, bool) bool, opts ...request.Option) error {
p := request.Pagination{
NewRequest: func() (*request.Request, error) {
var inCpy *ListVirtualNodesInput
if input != nil {
tmp := *input
inCpy = &tmp
}
req, _ := c.ListVirtualNodesRequest(inCpy)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return req, nil
},
}
for p.Next() {
if !fn(p.Page().(*ListVirtualNodesOutput), !p.HasNextPage()) {
break
}
}
return p.Err()
}
const opListVirtualRouters = "ListVirtualRouters"
// ListVirtualRoutersRequest generates a "aws/request.Request" representing the
// client's request for the ListVirtualRouters operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See ListVirtualRouters for more information on using the ListVirtualRouters
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the ListVirtualRoutersRequest method.
// req, resp := client.ListVirtualRoutersRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/ListVirtualRouters
func (c *AppMesh) ListVirtualRoutersRequest(input *ListVirtualRoutersInput) (req *request.Request, output *ListVirtualRoutersOutput) {
op := &request.Operation{
Name: opListVirtualRouters,
HTTPMethod: "GET",
HTTPPath: "/v20190125/meshes/{meshName}/virtualRouters",
Paginator: &request.Paginator{
InputTokens: []string{"nextToken"},
OutputTokens: []string{"nextToken"},
LimitToken: "limit",
TruncationToken: "",
},
}
if input == nil {
input = &ListVirtualRoutersInput{}
}
output = &ListVirtualRoutersOutput{}
req = c.newRequest(op, input, output)
return
}
// ListVirtualRouters API operation for AWS App Mesh.
//
// Returns a list of existing virtual routers in a service mesh.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for AWS App Mesh's
// API operation ListVirtualRouters for usage and error information.
//
// Returned Error Types:
// * NotFoundException
// The specified resource doesn't exist. Check your request syntax and try again.
//
// * BadRequestException
// The request syntax was malformed. Check your request syntax and try again.
//
// * TooManyRequestsException
// The maximum request rate permitted by the App Mesh APIs has been exceeded
// for your account. For best results, use an increasing or variable sleep interval
// between requests.
//
// * ForbiddenException
// You don't have permissions to perform this action.
//
// * ServiceUnavailableException
// The request has failed due to a temporary failure of the service.
//
// * InternalServerErrorException
// The request processing has failed because of an unknown error, exception,
// or failure.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/ListVirtualRouters
func (c *AppMesh) ListVirtualRouters(input *ListVirtualRoutersInput) (*ListVirtualRoutersOutput, error) {
req, out := c.ListVirtualRoutersRequest(input)
return out, req.Send()
}
// ListVirtualRoutersWithContext is the same as ListVirtualRouters with the addition of
// the ability to pass a context and additional request options.
//
// See ListVirtualRouters for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *AppMesh) ListVirtualRoutersWithContext(ctx aws.Context, input *ListVirtualRoutersInput, opts ...request.Option) (*ListVirtualRoutersOutput, error) {
req, out := c.ListVirtualRoutersRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
// ListVirtualRoutersPages iterates over the pages of a ListVirtualRouters operation,
// calling the "fn" function with the response data for each page. To stop
// iterating, return false from the fn function.
//
// See ListVirtualRouters method for more information on how to use this operation.
//
// Note: This operation can generate multiple requests to a service.
//
// // Example iterating over at most 3 pages of a ListVirtualRouters operation.
// pageNum := 0
// err := client.ListVirtualRoutersPages(params,
// func(page *appmesh.ListVirtualRoutersOutput, lastPage bool) bool {
// pageNum++
// fmt.Println(page)
// return pageNum <= 3
// })
//
func (c *AppMesh) ListVirtualRoutersPages(input *ListVirtualRoutersInput, fn func(*ListVirtualRoutersOutput, bool) bool) error {
return c.ListVirtualRoutersPagesWithContext(aws.BackgroundContext(), input, fn)
}
// ListVirtualRoutersPagesWithContext same as ListVirtualRoutersPages except
// it takes a Context and allows setting request options on the pages.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *AppMesh) ListVirtualRoutersPagesWithContext(ctx aws.Context, input *ListVirtualRoutersInput, fn func(*ListVirtualRoutersOutput, bool) bool, opts ...request.Option) error {
p := request.Pagination{
NewRequest: func() (*request.Request, error) {
var inCpy *ListVirtualRoutersInput
if input != nil {
tmp := *input
inCpy = &tmp
}
req, _ := c.ListVirtualRoutersRequest(inCpy)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return req, nil
},
}
for p.Next() {
if !fn(p.Page().(*ListVirtualRoutersOutput), !p.HasNextPage()) {
break
}
}
return p.Err()
}
const opListVirtualServices = "ListVirtualServices"
// ListVirtualServicesRequest generates a "aws/request.Request" representing the
// client's request for the ListVirtualServices operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See ListVirtualServices for more information on using the ListVirtualServices
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the ListVirtualServicesRequest method.
// req, resp := client.ListVirtualServicesRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/ListVirtualServices
func (c *AppMesh) ListVirtualServicesRequest(input *ListVirtualServicesInput) (req *request.Request, output *ListVirtualServicesOutput) {
op := &request.Operation{
Name: opListVirtualServices,
HTTPMethod: "GET",
HTTPPath: "/v20190125/meshes/{meshName}/virtualServices",
Paginator: &request.Paginator{
InputTokens: []string{"nextToken"},
OutputTokens: []string{"nextToken"},
LimitToken: "limit",
TruncationToken: "",
},
}
if input == nil {
input = &ListVirtualServicesInput{}
}
output = &ListVirtualServicesOutput{}
req = c.newRequest(op, input, output)
return
}
// ListVirtualServices API operation for AWS App Mesh.
//
// Returns a list of existing virtual services in a service mesh.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for AWS App Mesh's
// API operation ListVirtualServices for usage and error information.
//
// Returned Error Types:
// * NotFoundException
// The specified resource doesn't exist. Check your request syntax and try again.
//
// * BadRequestException
// The request syntax was malformed. Check your request syntax and try again.
//
// * TooManyRequestsException
// The maximum request rate permitted by the App Mesh APIs has been exceeded
// for your account. For best results, use an increasing or variable sleep interval
// between requests.
//
// * ForbiddenException
// You don't have permissions to perform this action.
//
// * ServiceUnavailableException
// The request has failed due to a temporary failure of the service.
//
// * InternalServerErrorException
// The request processing has failed because of an unknown error, exception,
// or failure.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/ListVirtualServices
func (c *AppMesh) ListVirtualServices(input *ListVirtualServicesInput) (*ListVirtualServicesOutput, error) {
req, out := c.ListVirtualServicesRequest(input)
return out, req.Send()
}
// ListVirtualServicesWithContext is the same as ListVirtualServices with the addition of
// the ability to pass a context and additional request options.
//
// See ListVirtualServices for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *AppMesh) ListVirtualServicesWithContext(ctx aws.Context, input *ListVirtualServicesInput, opts ...request.Option) (*ListVirtualServicesOutput, error) {
req, out := c.ListVirtualServicesRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
// ListVirtualServicesPages iterates over the pages of a ListVirtualServices operation,
// calling the "fn" function with the response data for each page. To stop
// iterating, return false from the fn function.
//
// See ListVirtualServices method for more information on how to use this operation.
//
// Note: This operation can generate multiple requests to a service.
//
// // Example iterating over at most 3 pages of a ListVirtualServices operation.
// pageNum := 0
// err := client.ListVirtualServicesPages(params,
// func(page *appmesh.ListVirtualServicesOutput, lastPage bool) bool {
// pageNum++
// fmt.Println(page)
// return pageNum <= 3
// })
//
func (c *AppMesh) ListVirtualServicesPages(input *ListVirtualServicesInput, fn func(*ListVirtualServicesOutput, bool) bool) error {
return c.ListVirtualServicesPagesWithContext(aws.BackgroundContext(), input, fn)
}
// ListVirtualServicesPagesWithContext same as ListVirtualServicesPages except
// it takes a Context and allows setting request options on the pages.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *AppMesh) ListVirtualServicesPagesWithContext(ctx aws.Context, input *ListVirtualServicesInput, fn func(*ListVirtualServicesOutput, bool) bool, opts ...request.Option) error {
p := request.Pagination{
NewRequest: func() (*request.Request, error) {
var inCpy *ListVirtualServicesInput
if input != nil {
tmp := *input
inCpy = &tmp
}
req, _ := c.ListVirtualServicesRequest(inCpy)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return req, nil
},
}
for p.Next() {
if !fn(p.Page().(*ListVirtualServicesOutput), !p.HasNextPage()) {
break
}
}
return p.Err()
}
const opTagResource = "TagResource"
// TagResourceRequest generates a "aws/request.Request" representing the
// client's request for the TagResource operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See TagResource for more information on using the TagResource
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the TagResourceRequest method.
// req, resp := client.TagResourceRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/TagResource
func (c *AppMesh) TagResourceRequest(input *TagResourceInput) (req *request.Request, output *TagResourceOutput) {
op := &request.Operation{
Name: opTagResource,
HTTPMethod: "PUT",
HTTPPath: "/v20190125/tag",
}
if input == nil {
input = &TagResourceInput{}
}
output = &TagResourceOutput{}
req = c.newRequest(op, input, output)
req.Handlers.Unmarshal.Swap(restjson.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler)
return
}
// TagResource API operation for AWS App Mesh.
//
// Associates the specified tags to a resource with the specified resourceArn.
// If existing tags on a resource aren't specified in the request parameters,
// they aren't changed. When a resource is deleted, the tags associated with
// that resource are also deleted.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for AWS App Mesh's
// API operation TagResource for usage and error information.
//
// Returned Error Types:
// * NotFoundException
// The specified resource doesn't exist. Check your request syntax and try again.
//
// * BadRequestException
// The request syntax was malformed. Check your request syntax and try again.
//
// * TooManyTagsException
// The request exceeds the maximum allowed number of tags allowed per resource.
// The current limit is 50 user tags per resource. You must reduce the number
// of tags in the request. None of the tags in this request were applied.
//
// * TooManyRequestsException
// The maximum request rate permitted by the App Mesh APIs has been exceeded
// for your account. For best results, use an increasing or variable sleep interval
// between requests.
//
// * ForbiddenException
// You don't have permissions to perform this action.
//
// * ServiceUnavailableException
// The request has failed due to a temporary failure of the service.
//
// * InternalServerErrorException
// The request processing has failed because of an unknown error, exception,
// or failure.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/TagResource
func (c *AppMesh) TagResource(input *TagResourceInput) (*TagResourceOutput, error) {
req, out := c.TagResourceRequest(input)
return out, req.Send()
}
// TagResourceWithContext is the same as TagResource with the addition of
// the ability to pass a context and additional request options.
//
// See TagResource for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *AppMesh) TagResourceWithContext(ctx aws.Context, input *TagResourceInput, opts ...request.Option) (*TagResourceOutput, error) {
req, out := c.TagResourceRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opUntagResource = "UntagResource"
// UntagResourceRequest generates a "aws/request.Request" representing the
// client's request for the UntagResource operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See UntagResource for more information on using the UntagResource
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the UntagResourceRequest method.
// req, resp := client.UntagResourceRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/UntagResource
func (c *AppMesh) UntagResourceRequest(input *UntagResourceInput) (req *request.Request, output *UntagResourceOutput) {
op := &request.Operation{
Name: opUntagResource,
HTTPMethod: "PUT",
HTTPPath: "/v20190125/untag",
}
if input == nil {
input = &UntagResourceInput{}
}
output = &UntagResourceOutput{}
req = c.newRequest(op, input, output)
req.Handlers.Unmarshal.Swap(restjson.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler)
return
}
// UntagResource API operation for AWS App Mesh.
//
// Deletes specified tags from a resource.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for AWS App Mesh's
// API operation UntagResource for usage and error information.
//
// Returned Error Types:
// * NotFoundException
// The specified resource doesn't exist. Check your request syntax and try again.
//
// * BadRequestException
// The request syntax was malformed. Check your request syntax and try again.
//
// * TooManyRequestsException
// The maximum request rate permitted by the App Mesh APIs has been exceeded
// for your account. For best results, use an increasing or variable sleep interval
// between requests.
//
// * ForbiddenException
// You don't have permissions to perform this action.
//
// * ServiceUnavailableException
// The request has failed due to a temporary failure of the service.
//
// * InternalServerErrorException
// The request processing has failed because of an unknown error, exception,
// or failure.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/UntagResource
func (c *AppMesh) UntagResource(input *UntagResourceInput) (*UntagResourceOutput, error) {
req, out := c.UntagResourceRequest(input)
return out, req.Send()
}
// UntagResourceWithContext is the same as UntagResource with the addition of
// the ability to pass a context and additional request options.
//
// See UntagResource for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *AppMesh) UntagResourceWithContext(ctx aws.Context, input *UntagResourceInput, opts ...request.Option) (*UntagResourceOutput, error) {
req, out := c.UntagResourceRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opUpdateGatewayRoute = "UpdateGatewayRoute"
// UpdateGatewayRouteRequest generates a "aws/request.Request" representing the
// client's request for the UpdateGatewayRoute operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See UpdateGatewayRoute for more information on using the UpdateGatewayRoute
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the UpdateGatewayRouteRequest method.
// req, resp := client.UpdateGatewayRouteRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/UpdateGatewayRoute
func (c *AppMesh) UpdateGatewayRouteRequest(input *UpdateGatewayRouteInput) (req *request.Request, output *UpdateGatewayRouteOutput) {
op := &request.Operation{
Name: opUpdateGatewayRoute,
HTTPMethod: "PUT",
HTTPPath: "/v20190125/meshes/{meshName}/virtualGateway/{virtualGatewayName}/gatewayRoutes/{gatewayRouteName}",
}
if input == nil {
input = &UpdateGatewayRouteInput{}
}
output = &UpdateGatewayRouteOutput{}
req = c.newRequest(op, input, output)
return
}
// UpdateGatewayRoute API operation for AWS App Mesh.
//
// Updates an existing gateway route that is associated to a specified virtual
// gateway in a service mesh.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for AWS App Mesh's
// API operation UpdateGatewayRoute for usage and error information.
//
// Returned Error Types:
// * NotFoundException
// The specified resource doesn't exist. Check your request syntax and try again.
//
// * BadRequestException
// The request syntax was malformed. Check your request syntax and try again.
//
// * ConflictException
// The request contains a client token that was used for a previous update resource
// call with different specifications. Try the request again with a new client
// token.
//
// * TooManyRequestsException
// The maximum request rate permitted by the App Mesh APIs has been exceeded
// for your account. For best results, use an increasing or variable sleep interval
// between requests.
//
// * ForbiddenException
// You don't have permissions to perform this action.
//
// * ServiceUnavailableException
// The request has failed due to a temporary failure of the service.
//
// * InternalServerErrorException
// The request processing has failed because of an unknown error, exception,
// or failure.
//
// * LimitExceededException
// You have exceeded a service limit for your account. For more information,
// see Service Limits (https://docs.aws.amazon.com/app-mesh/latest/userguide/service-quotas.html)
// in the AWS App Mesh User Guide.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/UpdateGatewayRoute
func (c *AppMesh) UpdateGatewayRoute(input *UpdateGatewayRouteInput) (*UpdateGatewayRouteOutput, error) {
req, out := c.UpdateGatewayRouteRequest(input)
return out, req.Send()
}
// UpdateGatewayRouteWithContext is the same as UpdateGatewayRoute with the addition of
// the ability to pass a context and additional request options.
//
// See UpdateGatewayRoute for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *AppMesh) UpdateGatewayRouteWithContext(ctx aws.Context, input *UpdateGatewayRouteInput, opts ...request.Option) (*UpdateGatewayRouteOutput, error) {
req, out := c.UpdateGatewayRouteRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opUpdateMesh = "UpdateMesh"
// UpdateMeshRequest generates a "aws/request.Request" representing the
// client's request for the UpdateMesh operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See UpdateMesh for more information on using the UpdateMesh
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the UpdateMeshRequest method.
// req, resp := client.UpdateMeshRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/UpdateMesh
func (c *AppMesh) UpdateMeshRequest(input *UpdateMeshInput) (req *request.Request, output *UpdateMeshOutput) {
op := &request.Operation{
Name: opUpdateMesh,
HTTPMethod: "PUT",
HTTPPath: "/v20190125/meshes/{meshName}",
}
if input == nil {
input = &UpdateMeshInput{}
}
output = &UpdateMeshOutput{}
req = c.newRequest(op, input, output)
return
}
// UpdateMesh API operation for AWS App Mesh.
//
// Updates an existing service mesh.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for AWS App Mesh's
// API operation UpdateMesh for usage and error information.
//
// Returned Error Types:
// * NotFoundException
// The specified resource doesn't exist. Check your request syntax and try again.
//
// * BadRequestException
// The request syntax was malformed. Check your request syntax and try again.
//
// * ConflictException
// The request contains a client token that was used for a previous update resource
// call with different specifications. Try the request again with a new client
// token.
//
// * TooManyRequestsException
// The maximum request rate permitted by the App Mesh APIs has been exceeded
// for your account. For best results, use an increasing or variable sleep interval
// between requests.
//
// * ForbiddenException
// You don't have permissions to perform this action.
//
// * ServiceUnavailableException
// The request has failed due to a temporary failure of the service.
//
// * InternalServerErrorException
// The request processing has failed because of an unknown error, exception,
// or failure.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/UpdateMesh
func (c *AppMesh) UpdateMesh(input *UpdateMeshInput) (*UpdateMeshOutput, error) {
req, out := c.UpdateMeshRequest(input)
return out, req.Send()
}
// UpdateMeshWithContext is the same as UpdateMesh with the addition of
// the ability to pass a context and additional request options.
//
// See UpdateMesh for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *AppMesh) UpdateMeshWithContext(ctx aws.Context, input *UpdateMeshInput, opts ...request.Option) (*UpdateMeshOutput, error) {
req, out := c.UpdateMeshRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opUpdateRoute = "UpdateRoute"
// UpdateRouteRequest generates a "aws/request.Request" representing the
// client's request for the UpdateRoute operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See UpdateRoute for more information on using the UpdateRoute
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the UpdateRouteRequest method.
// req, resp := client.UpdateRouteRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/UpdateRoute
func (c *AppMesh) UpdateRouteRequest(input *UpdateRouteInput) (req *request.Request, output *UpdateRouteOutput) {
op := &request.Operation{
Name: opUpdateRoute,
HTTPMethod: "PUT",
HTTPPath: "/v20190125/meshes/{meshName}/virtualRouter/{virtualRouterName}/routes/{routeName}",
}
if input == nil {
input = &UpdateRouteInput{}
}
output = &UpdateRouteOutput{}
req = c.newRequest(op, input, output)
return
}
// UpdateRoute API operation for AWS App Mesh.
//
// Updates an existing route for a specified service mesh and virtual router.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for AWS App Mesh's
// API operation UpdateRoute for usage and error information.
//
// Returned Error Types:
// * NotFoundException
// The specified resource doesn't exist. Check your request syntax and try again.
//
// * BadRequestException
// The request syntax was malformed. Check your request syntax and try again.
//
// * ConflictException
// The request contains a client token that was used for a previous update resource
// call with different specifications. Try the request again with a new client
// token.
//
// * TooManyRequestsException
// The maximum request rate permitted by the App Mesh APIs has been exceeded
// for your account. For best results, use an increasing or variable sleep interval
// between requests.
//
// * ForbiddenException
// You don't have permissions to perform this action.
//
// * ServiceUnavailableException
// The request has failed due to a temporary failure of the service.
//
// * InternalServerErrorException
// The request processing has failed because of an unknown error, exception,
// or failure.
//
// * LimitExceededException
// You have exceeded a service limit for your account. For more information,
// see Service Limits (https://docs.aws.amazon.com/app-mesh/latest/userguide/service-quotas.html)
// in the AWS App Mesh User Guide.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/UpdateRoute
func (c *AppMesh) UpdateRoute(input *UpdateRouteInput) (*UpdateRouteOutput, error) {
req, out := c.UpdateRouteRequest(input)
return out, req.Send()
}
// UpdateRouteWithContext is the same as UpdateRoute with the addition of
// the ability to pass a context and additional request options.
//
// See UpdateRoute for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *AppMesh) UpdateRouteWithContext(ctx aws.Context, input *UpdateRouteInput, opts ...request.Option) (*UpdateRouteOutput, error) {
req, out := c.UpdateRouteRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opUpdateVirtualGateway = "UpdateVirtualGateway"
// UpdateVirtualGatewayRequest generates a "aws/request.Request" representing the
// client's request for the UpdateVirtualGateway operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See UpdateVirtualGateway for more information on using the UpdateVirtualGateway
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the UpdateVirtualGatewayRequest method.
// req, resp := client.UpdateVirtualGatewayRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/UpdateVirtualGateway
func (c *AppMesh) UpdateVirtualGatewayRequest(input *UpdateVirtualGatewayInput) (req *request.Request, output *UpdateVirtualGatewayOutput) {
op := &request.Operation{
Name: opUpdateVirtualGateway,
HTTPMethod: "PUT",
HTTPPath: "/v20190125/meshes/{meshName}/virtualGateways/{virtualGatewayName}",
}
if input == nil {
input = &UpdateVirtualGatewayInput{}
}
output = &UpdateVirtualGatewayOutput{}
req = c.newRequest(op, input, output)
return
}
// UpdateVirtualGateway API operation for AWS App Mesh.
//
// Updates an existing virtual gateway in a specified service mesh.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for AWS App Mesh's
// API operation UpdateVirtualGateway for usage and error information.
//
// Returned Error Types:
// * NotFoundException
// The specified resource doesn't exist. Check your request syntax and try again.
//
// * BadRequestException
// The request syntax was malformed. Check your request syntax and try again.
//
// * ConflictException
// The request contains a client token that was used for a previous update resource
// call with different specifications. Try the request again with a new client
// token.
//
// * TooManyRequestsException
// The maximum request rate permitted by the App Mesh APIs has been exceeded
// for your account. For best results, use an increasing or variable sleep interval
// between requests.
//
// * ForbiddenException
// You don't have permissions to perform this action.
//
// * ServiceUnavailableException
// The request has failed due to a temporary failure of the service.
//
// * InternalServerErrorException
// The request processing has failed because of an unknown error, exception,
// or failure.
//
// * LimitExceededException
// You have exceeded a service limit for your account. For more information,
// see Service Limits (https://docs.aws.amazon.com/app-mesh/latest/userguide/service-quotas.html)
// in the AWS App Mesh User Guide.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/UpdateVirtualGateway
func (c *AppMesh) UpdateVirtualGateway(input *UpdateVirtualGatewayInput) (*UpdateVirtualGatewayOutput, error) {
req, out := c.UpdateVirtualGatewayRequest(input)
return out, req.Send()
}
// UpdateVirtualGatewayWithContext is the same as UpdateVirtualGateway with the addition of
// the ability to pass a context and additional request options.
//
// See UpdateVirtualGateway for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *AppMesh) UpdateVirtualGatewayWithContext(ctx aws.Context, input *UpdateVirtualGatewayInput, opts ...request.Option) (*UpdateVirtualGatewayOutput, error) {
req, out := c.UpdateVirtualGatewayRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opUpdateVirtualNode = "UpdateVirtualNode"
// UpdateVirtualNodeRequest generates a "aws/request.Request" representing the
// client's request for the UpdateVirtualNode operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See UpdateVirtualNode for more information on using the UpdateVirtualNode
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the UpdateVirtualNodeRequest method.
// req, resp := client.UpdateVirtualNodeRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/UpdateVirtualNode
func (c *AppMesh) UpdateVirtualNodeRequest(input *UpdateVirtualNodeInput) (req *request.Request, output *UpdateVirtualNodeOutput) {
op := &request.Operation{
Name: opUpdateVirtualNode,
HTTPMethod: "PUT",
HTTPPath: "/v20190125/meshes/{meshName}/virtualNodes/{virtualNodeName}",
}
if input == nil {
input = &UpdateVirtualNodeInput{}
}
output = &UpdateVirtualNodeOutput{}
req = c.newRequest(op, input, output)
return
}
// UpdateVirtualNode API operation for AWS App Mesh.
//
// Updates an existing virtual node in a specified service mesh.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for AWS App Mesh's
// API operation UpdateVirtualNode for usage and error information.
//
// Returned Error Types:
// * NotFoundException
// The specified resource doesn't exist. Check your request syntax and try again.
//
// * BadRequestException
// The request syntax was malformed. Check your request syntax and try again.
//
// * ConflictException
// The request contains a client token that was used for a previous update resource
// call with different specifications. Try the request again with a new client
// token.
//
// * TooManyRequestsException
// The maximum request rate permitted by the App Mesh APIs has been exceeded
// for your account. For best results, use an increasing or variable sleep interval
// between requests.
//
// * ForbiddenException
// You don't have permissions to perform this action.
//
// * ServiceUnavailableException
// The request has failed due to a temporary failure of the service.
//
// * InternalServerErrorException
// The request processing has failed because of an unknown error, exception,
// or failure.
//
// * LimitExceededException
// You have exceeded a service limit for your account. For more information,
// see Service Limits (https://docs.aws.amazon.com/app-mesh/latest/userguide/service-quotas.html)
// in the AWS App Mesh User Guide.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/UpdateVirtualNode
func (c *AppMesh) UpdateVirtualNode(input *UpdateVirtualNodeInput) (*UpdateVirtualNodeOutput, error) {
req, out := c.UpdateVirtualNodeRequest(input)
return out, req.Send()
}
// UpdateVirtualNodeWithContext is the same as UpdateVirtualNode with the addition of
// the ability to pass a context and additional request options.
//
// See UpdateVirtualNode for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *AppMesh) UpdateVirtualNodeWithContext(ctx aws.Context, input *UpdateVirtualNodeInput, opts ...request.Option) (*UpdateVirtualNodeOutput, error) {
req, out := c.UpdateVirtualNodeRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opUpdateVirtualRouter = "UpdateVirtualRouter"
// UpdateVirtualRouterRequest generates a "aws/request.Request" representing the
// client's request for the UpdateVirtualRouter operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See UpdateVirtualRouter for more information on using the UpdateVirtualRouter
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the UpdateVirtualRouterRequest method.
// req, resp := client.UpdateVirtualRouterRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/UpdateVirtualRouter
func (c *AppMesh) UpdateVirtualRouterRequest(input *UpdateVirtualRouterInput) (req *request.Request, output *UpdateVirtualRouterOutput) {
op := &request.Operation{
Name: opUpdateVirtualRouter,
HTTPMethod: "PUT",
HTTPPath: "/v20190125/meshes/{meshName}/virtualRouters/{virtualRouterName}",
}
if input == nil {
input = &UpdateVirtualRouterInput{}
}
output = &UpdateVirtualRouterOutput{}
req = c.newRequest(op, input, output)
return
}
// UpdateVirtualRouter API operation for AWS App Mesh.
//
// Updates an existing virtual router in a specified service mesh.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for AWS App Mesh's
// API operation UpdateVirtualRouter for usage and error information.
//
// Returned Error Types:
// * NotFoundException
// The specified resource doesn't exist. Check your request syntax and try again.
//
// * BadRequestException
// The request syntax was malformed. Check your request syntax and try again.
//
// * ConflictException
// The request contains a client token that was used for a previous update resource
// call with different specifications. Try the request again with a new client
// token.
//
// * TooManyRequestsException
// The maximum request rate permitted by the App Mesh APIs has been exceeded
// for your account. For best results, use an increasing or variable sleep interval
// between requests.
//
// * ForbiddenException
// You don't have permissions to perform this action.
//
// * ServiceUnavailableException
// The request has failed due to a temporary failure of the service.
//
// * InternalServerErrorException
// The request processing has failed because of an unknown error, exception,
// or failure.
//
// * LimitExceededException
// You have exceeded a service limit for your account. For more information,
// see Service Limits (https://docs.aws.amazon.com/app-mesh/latest/userguide/service-quotas.html)
// in the AWS App Mesh User Guide.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/UpdateVirtualRouter
func (c *AppMesh) UpdateVirtualRouter(input *UpdateVirtualRouterInput) (*UpdateVirtualRouterOutput, error) {
req, out := c.UpdateVirtualRouterRequest(input)
return out, req.Send()
}
// UpdateVirtualRouterWithContext is the same as UpdateVirtualRouter with the addition of
// the ability to pass a context and additional request options.
//
// See UpdateVirtualRouter for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *AppMesh) UpdateVirtualRouterWithContext(ctx aws.Context, input *UpdateVirtualRouterInput, opts ...request.Option) (*UpdateVirtualRouterOutput, error) {
req, out := c.UpdateVirtualRouterRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opUpdateVirtualService = "UpdateVirtualService"
// UpdateVirtualServiceRequest generates a "aws/request.Request" representing the
// client's request for the UpdateVirtualService operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See UpdateVirtualService for more information on using the UpdateVirtualService
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the UpdateVirtualServiceRequest method.
// req, resp := client.UpdateVirtualServiceRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/UpdateVirtualService
func (c *AppMesh) UpdateVirtualServiceRequest(input *UpdateVirtualServiceInput) (req *request.Request, output *UpdateVirtualServiceOutput) {
op := &request.Operation{
Name: opUpdateVirtualService,
HTTPMethod: "PUT",
HTTPPath: "/v20190125/meshes/{meshName}/virtualServices/{virtualServiceName}",
}
if input == nil {
input = &UpdateVirtualServiceInput{}
}
output = &UpdateVirtualServiceOutput{}
req = c.newRequest(op, input, output)
return
}
// UpdateVirtualService API operation for AWS App Mesh.
//
// Updates an existing virtual service in a specified service mesh.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for AWS App Mesh's
// API operation UpdateVirtualService for usage and error information.
//
// Returned Error Types:
// * NotFoundException
// The specified resource doesn't exist. Check your request syntax and try again.
//
// * BadRequestException
// The request syntax was malformed. Check your request syntax and try again.
//
// * ConflictException
// The request contains a client token that was used for a previous update resource
// call with different specifications. Try the request again with a new client
// token.
//
// * TooManyRequestsException
// The maximum request rate permitted by the App Mesh APIs has been exceeded
// for your account. For best results, use an increasing or variable sleep interval
// between requests.
//
// * ForbiddenException
// You don't have permissions to perform this action.
//
// * ServiceUnavailableException
// The request has failed due to a temporary failure of the service.
//
// * InternalServerErrorException
// The request processing has failed because of an unknown error, exception,
// or failure.
//
// * LimitExceededException
// You have exceeded a service limit for your account. For more information,
// see Service Limits (https://docs.aws.amazon.com/app-mesh/latest/userguide/service-quotas.html)
// in the AWS App Mesh User Guide.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/UpdateVirtualService
func (c *AppMesh) UpdateVirtualService(input *UpdateVirtualServiceInput) (*UpdateVirtualServiceOutput, error) {
req, out := c.UpdateVirtualServiceRequest(input)
return out, req.Send()
}
// UpdateVirtualServiceWithContext is the same as UpdateVirtualService with the addition of
// the ability to pass a context and additional request options.
//
// See UpdateVirtualService for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *AppMesh) UpdateVirtualServiceWithContext(ctx aws.Context, input *UpdateVirtualServiceInput, opts ...request.Option) (*UpdateVirtualServiceOutput, error) {
req, out := c.UpdateVirtualServiceRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
// An object that represents the access logging information for a virtual node.
type AccessLog struct {
_ struct{} `type:"structure"`
// The file object to send virtual node access logs to.
File *FileAccessLog `locationName:"file" type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s AccessLog) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s AccessLog) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *AccessLog) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "AccessLog"}
if s.File != nil {
if err := s.File.Validate(); err != nil {
invalidParams.AddNested("File", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetFile sets the File field's value.
func (s *AccessLog) SetFile(v *FileAccessLog) *AccessLog {
s.File = v
return s
}
// An object that represents the Cloud Map attribute information for your virtual
// node.
//
// AWS Cloud Map is not available in the eu-south-1 Region.
type AwsCloudMapInstanceAttribute struct {
_ struct{} `type:"structure"`
// The name of an Cloud Map service instance attribute key. Any Cloud Map service
// instance that contains the specified key and value is returned.
//
// Key is a required field
Key *string `locationName:"key" min:"1" type:"string" required:"true"`
// The value of an Cloud Map service instance attribute key. Any Cloud Map service
// instance that contains the specified key and value is returned.
//
// Value is a required field
Value *string `locationName:"value" min:"1" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s AwsCloudMapInstanceAttribute) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s AwsCloudMapInstanceAttribute) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *AwsCloudMapInstanceAttribute) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "AwsCloudMapInstanceAttribute"}
if s.Key == nil {
invalidParams.Add(request.NewErrParamRequired("Key"))
}
if s.Key != nil && len(*s.Key) < 1 {
invalidParams.Add(request.NewErrParamMinLen("Key", 1))
}
if s.Value == nil {
invalidParams.Add(request.NewErrParamRequired("Value"))
}
if s.Value != nil && len(*s.Value) < 1 {
invalidParams.Add(request.NewErrParamMinLen("Value", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetKey sets the Key field's value.
func (s *AwsCloudMapInstanceAttribute) SetKey(v string) *AwsCloudMapInstanceAttribute {
s.Key = &v
return s
}
// SetValue sets the Value field's value.
func (s *AwsCloudMapInstanceAttribute) SetValue(v string) *AwsCloudMapInstanceAttribute {
s.Value = &v
return s
}
// An object that represents the Cloud Map service discovery information for
// your virtual node.
//
// Cloud Map is not available in the eu-south-1 Region.
type AwsCloudMapServiceDiscovery struct {
_ struct{} `type:"structure"`
// A string map that contains attributes with values that you can use to filter
// instances by any custom attribute that you specified when you registered
// the instance. Only instances that match all of the specified key/value pairs
// will be returned.
Attributes []*AwsCloudMapInstanceAttribute `locationName:"attributes" type:"list"`
// The name of the Cloud Map namespace to use.
//
// NamespaceName is a required field
NamespaceName *string `locationName:"namespaceName" min:"1" type:"string" required:"true"`
// The name of the Cloud Map service to use.
//
// ServiceName is a required field
ServiceName *string `locationName:"serviceName" min:"1" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s AwsCloudMapServiceDiscovery) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s AwsCloudMapServiceDiscovery) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *AwsCloudMapServiceDiscovery) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "AwsCloudMapServiceDiscovery"}
if s.NamespaceName == nil {
invalidParams.Add(request.NewErrParamRequired("NamespaceName"))
}
if s.NamespaceName != nil && len(*s.NamespaceName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("NamespaceName", 1))
}
if s.ServiceName == nil {
invalidParams.Add(request.NewErrParamRequired("ServiceName"))
}
if s.ServiceName != nil && len(*s.ServiceName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("ServiceName", 1))
}
if s.Attributes != nil {
for i, v := range s.Attributes {
if v == nil {
continue
}
if err := v.Validate(); err != nil {
invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Attributes", i), err.(request.ErrInvalidParams))
}
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetAttributes sets the Attributes field's value.
func (s *AwsCloudMapServiceDiscovery) SetAttributes(v []*AwsCloudMapInstanceAttribute) *AwsCloudMapServiceDiscovery {
s.Attributes = v
return s
}
// SetNamespaceName sets the NamespaceName field's value.
func (s *AwsCloudMapServiceDiscovery) SetNamespaceName(v string) *AwsCloudMapServiceDiscovery {
s.NamespaceName = &v
return s
}
// SetServiceName sets the ServiceName field's value.
func (s *AwsCloudMapServiceDiscovery) SetServiceName(v string) *AwsCloudMapServiceDiscovery {
s.ServiceName = &v
return s
}
// An object that represents the backends that a virtual node is expected to
// send outbound traffic to.
type Backend struct {
_ struct{} `type:"structure"`
// Specifies a virtual service to use as a backend.
VirtualService *VirtualServiceBackend `locationName:"virtualService" type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s Backend) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s Backend) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *Backend) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "Backend"}
if s.VirtualService != nil {
if err := s.VirtualService.Validate(); err != nil {
invalidParams.AddNested("VirtualService", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetVirtualService sets the VirtualService field's value.
func (s *Backend) SetVirtualService(v *VirtualServiceBackend) *Backend {
s.VirtualService = v
return s
}
// An object that represents the default properties for a backend.
type BackendDefaults struct {
_ struct{} `type:"structure"`
// A reference to an object that represents a client policy.
ClientPolicy *ClientPolicy `locationName:"clientPolicy" type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s BackendDefaults) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s BackendDefaults) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *BackendDefaults) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "BackendDefaults"}
if s.ClientPolicy != nil {
if err := s.ClientPolicy.Validate(); err != nil {
invalidParams.AddNested("ClientPolicy", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetClientPolicy sets the ClientPolicy field's value.
func (s *BackendDefaults) SetClientPolicy(v *ClientPolicy) *BackendDefaults {
s.ClientPolicy = v
return s
}
// The request syntax was malformed. Check your request syntax and try again.
type BadRequestException struct {
_ struct{} `type:"structure"`
RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"`
Message_ *string `locationName:"message" type:"string"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s BadRequestException) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s BadRequestException) GoString() string {
return s.String()
}
func newErrorBadRequestException(v protocol.ResponseMetadata) error {
return &BadRequestException{
RespMetadata: v,
}
}
// Code returns the exception type name.
func (s *BadRequestException) Code() string {
return "BadRequestException"
}
// Message returns the exception's message.
func (s *BadRequestException) Message() string {
if s.Message_ != nil {
return *s.Message_
}
return ""
}
// OrigErr always returns nil, satisfies awserr.Error interface.
func (s *BadRequestException) OrigErr() error {
return nil
}
func (s *BadRequestException) Error() string {
return fmt.Sprintf("%s: %s", s.Code(), s.Message())
}
// Status code returns the HTTP status code for the request's response error.
func (s *BadRequestException) StatusCode() int {
return s.RespMetadata.StatusCode
}
// RequestID returns the service's response RequestID for request.
func (s *BadRequestException) RequestID() string {
return s.RespMetadata.RequestID
}
// An object that represents a client policy.
type ClientPolicy struct {
_ struct{} `type:"structure"`
// A reference to an object that represents a Transport Layer Security (TLS)
// client policy.
Tls *ClientPolicyTls `locationName:"tls" type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ClientPolicy) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ClientPolicy) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *ClientPolicy) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "ClientPolicy"}
if s.Tls != nil {
if err := s.Tls.Validate(); err != nil {
invalidParams.AddNested("Tls", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetTls sets the Tls field's value.
func (s *ClientPolicy) SetTls(v *ClientPolicyTls) *ClientPolicy {
s.Tls = v
return s
}
// A reference to an object that represents a Transport Layer Security (TLS)
// client policy.
type ClientPolicyTls struct {
_ struct{} `type:"structure"`
// A reference to an object that represents a client's TLS certificate.
Certificate *ClientTlsCertificate `locationName:"certificate" type:"structure"`
// Whether the policy is enforced. The default is True, if a value isn't specified.
Enforce *bool `locationName:"enforce" type:"boolean"`
// One or more ports that the policy is enforced for.
Ports []*int64 `locationName:"ports" type:"list"`
// A reference to an object that represents a TLS validation context.
//
// Validation is a required field
Validation *TlsValidationContext `locationName:"validation" type:"structure" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ClientPolicyTls) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ClientPolicyTls) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *ClientPolicyTls) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "ClientPolicyTls"}
if s.Validation == nil {
invalidParams.Add(request.NewErrParamRequired("Validation"))
}
if s.Certificate != nil {
if err := s.Certificate.Validate(); err != nil {
invalidParams.AddNested("Certificate", err.(request.ErrInvalidParams))
}
}
if s.Validation != nil {
if err := s.Validation.Validate(); err != nil {
invalidParams.AddNested("Validation", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetCertificate sets the Certificate field's value.
func (s *ClientPolicyTls) SetCertificate(v *ClientTlsCertificate) *ClientPolicyTls {
s.Certificate = v
return s
}
// SetEnforce sets the Enforce field's value.
func (s *ClientPolicyTls) SetEnforce(v bool) *ClientPolicyTls {
s.Enforce = &v
return s
}
// SetPorts sets the Ports field's value.
func (s *ClientPolicyTls) SetPorts(v []*int64) *ClientPolicyTls {
s.Ports = v
return s
}
// SetValidation sets the Validation field's value.
func (s *ClientPolicyTls) SetValidation(v *TlsValidationContext) *ClientPolicyTls {
s.Validation = v
return s
}
// An object that represents the client's certificate.
type ClientTlsCertificate struct {
_ struct{} `type:"structure"`
// An object that represents a local file certificate. The certificate must
// meet specific requirements and you must have proxy authorization enabled.
// For more information, see Transport Layer Security (TLS) (https://docs.aws.amazon.com/app-mesh/latest/userguide/tls.html).
File *ListenerTlsFileCertificate `locationName:"file" type:"structure"`
// A reference to an object that represents a client's TLS Secret Discovery
// Service certificate.
Sds *ListenerTlsSdsCertificate `locationName:"sds" type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ClientTlsCertificate) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ClientTlsCertificate) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *ClientTlsCertificate) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "ClientTlsCertificate"}
if s.File != nil {
if err := s.File.Validate(); err != nil {
invalidParams.AddNested("File", err.(request.ErrInvalidParams))
}
}
if s.Sds != nil {
if err := s.Sds.Validate(); err != nil {
invalidParams.AddNested("Sds", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetFile sets the File field's value.
func (s *ClientTlsCertificate) SetFile(v *ListenerTlsFileCertificate) *ClientTlsCertificate {
s.File = v
return s
}
// SetSds sets the Sds field's value.
func (s *ClientTlsCertificate) SetSds(v *ListenerTlsSdsCertificate) *ClientTlsCertificate {
s.Sds = v
return s
}
// The request contains a client token that was used for a previous update resource
// call with different specifications. Try the request again with a new client
// token.
type ConflictException struct {
_ struct{} `type:"structure"`
RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"`
Message_ *string `locationName:"message" type:"string"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ConflictException) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ConflictException) GoString() string {
return s.String()
}
func newErrorConflictException(v protocol.ResponseMetadata) error {
return &ConflictException{
RespMetadata: v,
}
}
// Code returns the exception type name.
func (s *ConflictException) Code() string {
return "ConflictException"
}
// Message returns the exception's message.
func (s *ConflictException) Message() string {
if s.Message_ != nil {
return *s.Message_
}
return ""
}
// OrigErr always returns nil, satisfies awserr.Error interface.
func (s *ConflictException) OrigErr() error {
return nil
}
func (s *ConflictException) Error() string {
return fmt.Sprintf("%s: %s", s.Code(), s.Message())
}
// Status code returns the HTTP status code for the request's response error.
func (s *ConflictException) StatusCode() int {
return s.RespMetadata.StatusCode
}
// RequestID returns the service's response RequestID for request.
func (s *ConflictException) RequestID() string {
return s.RespMetadata.RequestID
}
type CreateGatewayRouteInput struct {
_ struct{} `type:"structure"`
// Unique, case-sensitive identifier that you provide to ensure the idempotency
// of the request. Up to 36 letters, numbers, hyphens, and underscores are allowed.
ClientToken *string `locationName:"clientToken" type:"string" idempotencyToken:"true"`
// The name to use for the gateway route.
//
// GatewayRouteName is a required field
GatewayRouteName *string `locationName:"gatewayRouteName" min:"1" type:"string" required:"true"`
// The name of the service mesh to create the gateway route in.
//
// MeshName is a required field
MeshName *string `location:"uri" locationName:"meshName" min:"1" type:"string" required:"true"`
// The AWS IAM account ID of the service mesh owner. If the account ID is not
// your own, then the account that you specify must share the mesh with your
// account before you can create the resource in the service mesh. For more
// information about mesh sharing, see Working with shared meshes (https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html).
MeshOwner *string `location:"querystring" locationName:"meshOwner" min:"12" type:"string"`
// The gateway route specification to apply.
//
// Spec is a required field
Spec *GatewayRouteSpec `locationName:"spec" type:"structure" required:"true"`
// Optional metadata that you can apply to the gateway route to assist with
// categorization and organization. Each tag consists of a key and an optional
// value, both of which you define. Tag keys can have a maximum character length
// of 128 characters, and tag values can have a maximum length of 256 characters.
Tags []*TagRef `locationName:"tags" type:"list"`
// The name of the virtual gateway to associate the gateway route with. If the
// virtual gateway is in a shared mesh, then you must be the owner of the virtual
// gateway resource.
//
// VirtualGatewayName is a required field
VirtualGatewayName *string `location:"uri" locationName:"virtualGatewayName" min:"1" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s CreateGatewayRouteInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s CreateGatewayRouteInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *CreateGatewayRouteInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "CreateGatewayRouteInput"}
if s.GatewayRouteName == nil {
invalidParams.Add(request.NewErrParamRequired("GatewayRouteName"))
}
if s.GatewayRouteName != nil && len(*s.GatewayRouteName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("GatewayRouteName", 1))
}
if s.MeshName == nil {
invalidParams.Add(request.NewErrParamRequired("MeshName"))
}
if s.MeshName != nil && len(*s.MeshName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("MeshName", 1))
}
if s.MeshOwner != nil && len(*s.MeshOwner) < 12 {
invalidParams.Add(request.NewErrParamMinLen("MeshOwner", 12))
}
if s.Spec == nil {
invalidParams.Add(request.NewErrParamRequired("Spec"))
}
if s.VirtualGatewayName == nil {
invalidParams.Add(request.NewErrParamRequired("VirtualGatewayName"))
}
if s.VirtualGatewayName != nil && len(*s.VirtualGatewayName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("VirtualGatewayName", 1))
}
if s.Spec != nil {
if err := s.Spec.Validate(); err != nil {
invalidParams.AddNested("Spec", err.(request.ErrInvalidParams))
}
}
if s.Tags != nil {
for i, v := range s.Tags {
if v == nil {
continue
}
if err := v.Validate(); err != nil {
invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams))
}
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetClientToken sets the ClientToken field's value.
func (s *CreateGatewayRouteInput) SetClientToken(v string) *CreateGatewayRouteInput {
s.ClientToken = &v
return s
}
// SetGatewayRouteName sets the GatewayRouteName field's value.
func (s *CreateGatewayRouteInput) SetGatewayRouteName(v string) *CreateGatewayRouteInput {
s.GatewayRouteName = &v
return s
}
// SetMeshName sets the MeshName field's value.
func (s *CreateGatewayRouteInput) SetMeshName(v string) *CreateGatewayRouteInput {
s.MeshName = &v
return s
}
// SetMeshOwner sets the MeshOwner field's value.
func (s *CreateGatewayRouteInput) SetMeshOwner(v string) *CreateGatewayRouteInput {
s.MeshOwner = &v
return s
}
// SetSpec sets the Spec field's value.
func (s *CreateGatewayRouteInput) SetSpec(v *GatewayRouteSpec) *CreateGatewayRouteInput {
s.Spec = v
return s
}
// SetTags sets the Tags field's value.
func (s *CreateGatewayRouteInput) SetTags(v []*TagRef) *CreateGatewayRouteInput {
s.Tags = v
return s
}
// SetVirtualGatewayName sets the VirtualGatewayName field's value.
func (s *CreateGatewayRouteInput) SetVirtualGatewayName(v string) *CreateGatewayRouteInput {
s.VirtualGatewayName = &v
return s
}
type CreateGatewayRouteOutput struct {
_ struct{} `type:"structure" payload:"GatewayRoute"`
// The full description of your gateway route following the create call.
//
// GatewayRoute is a required field
GatewayRoute *GatewayRouteData `locationName:"gatewayRoute" type:"structure" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s CreateGatewayRouteOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s CreateGatewayRouteOutput) GoString() string {
return s.String()
}
// SetGatewayRoute sets the GatewayRoute field's value.
func (s *CreateGatewayRouteOutput) SetGatewayRoute(v *GatewayRouteData) *CreateGatewayRouteOutput {
s.GatewayRoute = v
return s
}
type CreateMeshInput struct {
_ struct{} `type:"structure"`
// Unique, case-sensitive identifier that you provide to ensure the idempotency
// of the request. Up to 36 letters, numbers, hyphens, and underscores are allowed.
ClientToken *string `locationName:"clientToken" type:"string" idempotencyToken:"true"`
// The name to use for the service mesh.
//
// MeshName is a required field
MeshName *string `locationName:"meshName" min:"1" type:"string" required:"true"`
// The service mesh specification to apply.
Spec *MeshSpec `locationName:"spec" type:"structure"`
// Optional metadata that you can apply to the service mesh to assist with categorization
// and organization. Each tag consists of a key and an optional value, both
// of which you define. Tag keys can have a maximum character length of 128
// characters, and tag values can have a maximum length of 256 characters.
Tags []*TagRef `locationName:"tags" type:"list"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s CreateMeshInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s CreateMeshInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *CreateMeshInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "CreateMeshInput"}
if s.MeshName == nil {
invalidParams.Add(request.NewErrParamRequired("MeshName"))
}
if s.MeshName != nil && len(*s.MeshName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("MeshName", 1))
}
if s.Spec != nil {
if err := s.Spec.Validate(); err != nil {
invalidParams.AddNested("Spec", err.(request.ErrInvalidParams))
}
}
if s.Tags != nil {
for i, v := range s.Tags {
if v == nil {
continue
}
if err := v.Validate(); err != nil {
invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams))
}
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetClientToken sets the ClientToken field's value.
func (s *CreateMeshInput) SetClientToken(v string) *CreateMeshInput {
s.ClientToken = &v
return s
}
// SetMeshName sets the MeshName field's value.
func (s *CreateMeshInput) SetMeshName(v string) *CreateMeshInput {
s.MeshName = &v
return s
}
// SetSpec sets the Spec field's value.
func (s *CreateMeshInput) SetSpec(v *MeshSpec) *CreateMeshInput {
s.Spec = v
return s
}
// SetTags sets the Tags field's value.
func (s *CreateMeshInput) SetTags(v []*TagRef) *CreateMeshInput {
s.Tags = v
return s
}
type CreateMeshOutput struct {
_ struct{} `type:"structure" payload:"Mesh"`
// The full description of your service mesh following the create call.
//
// Mesh is a required field
Mesh *MeshData `locationName:"mesh" type:"structure" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s CreateMeshOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s CreateMeshOutput) GoString() string {
return s.String()
}
// SetMesh sets the Mesh field's value.
func (s *CreateMeshOutput) SetMesh(v *MeshData) *CreateMeshOutput {
s.Mesh = v
return s
}
type CreateRouteInput struct {
_ struct{} `type:"structure"`
// Unique, case-sensitive identifier that you provide to ensure the idempotency
// of the request. Up to 36 letters, numbers, hyphens, and underscores are allowed.
ClientToken *string `locationName:"clientToken" type:"string" idempotencyToken:"true"`
// The name of the service mesh to create the route in.
//
// MeshName is a required field
MeshName *string `location:"uri" locationName:"meshName" min:"1" type:"string" required:"true"`
// The AWS IAM account ID of the service mesh owner. If the account ID is not
// your own, then the account that you specify must share the mesh with your
// account before you can create the resource in the service mesh. For more
// information about mesh sharing, see Working with shared meshes (https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html).
MeshOwner *string `location:"querystring" locationName:"meshOwner" min:"12" type:"string"`
// The name to use for the route.
//
// RouteName is a required field
RouteName *string `locationName:"routeName" min:"1" type:"string" required:"true"`
// The route specification to apply.
//
// Spec is a required field
Spec *RouteSpec `locationName:"spec" type:"structure" required:"true"`
// Optional metadata that you can apply to the route to assist with categorization
// and organization. Each tag consists of a key and an optional value, both
// of which you define. Tag keys can have a maximum character length of 128
// characters, and tag values can have a maximum length of 256 characters.
Tags []*TagRef `locationName:"tags" type:"list"`
// The name of the virtual router in which to create the route. If the virtual
// router is in a shared mesh, then you must be the owner of the virtual router
// resource.
//
// VirtualRouterName is a required field
VirtualRouterName *string `location:"uri" locationName:"virtualRouterName" min:"1" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s CreateRouteInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s CreateRouteInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *CreateRouteInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "CreateRouteInput"}
if s.MeshName == nil {
invalidParams.Add(request.NewErrParamRequired("MeshName"))
}
if s.MeshName != nil && len(*s.MeshName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("MeshName", 1))
}
if s.MeshOwner != nil && len(*s.MeshOwner) < 12 {
invalidParams.Add(request.NewErrParamMinLen("MeshOwner", 12))
}
if s.RouteName == nil {
invalidParams.Add(request.NewErrParamRequired("RouteName"))
}
if s.RouteName != nil && len(*s.RouteName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("RouteName", 1))
}
if s.Spec == nil {
invalidParams.Add(request.NewErrParamRequired("Spec"))
}
if s.VirtualRouterName == nil {
invalidParams.Add(request.NewErrParamRequired("VirtualRouterName"))
}
if s.VirtualRouterName != nil && len(*s.VirtualRouterName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("VirtualRouterName", 1))
}
if s.Spec != nil {
if err := s.Spec.Validate(); err != nil {
invalidParams.AddNested("Spec", err.(request.ErrInvalidParams))
}
}
if s.Tags != nil {
for i, v := range s.Tags {
if v == nil {
continue
}
if err := v.Validate(); err != nil {
invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams))
}
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetClientToken sets the ClientToken field's value.
func (s *CreateRouteInput) SetClientToken(v string) *CreateRouteInput {
s.ClientToken = &v
return s
}
// SetMeshName sets the MeshName field's value.
func (s *CreateRouteInput) SetMeshName(v string) *CreateRouteInput {
s.MeshName = &v
return s
}
// SetMeshOwner sets the MeshOwner field's value.
func (s *CreateRouteInput) SetMeshOwner(v string) *CreateRouteInput {
s.MeshOwner = &v
return s
}
// SetRouteName sets the RouteName field's value.
func (s *CreateRouteInput) SetRouteName(v string) *CreateRouteInput {
s.RouteName = &v
return s
}
// SetSpec sets the Spec field's value.
func (s *CreateRouteInput) SetSpec(v *RouteSpec) *CreateRouteInput {
s.Spec = v
return s
}
// SetTags sets the Tags field's value.
func (s *CreateRouteInput) SetTags(v []*TagRef) *CreateRouteInput {
s.Tags = v
return s
}
// SetVirtualRouterName sets the VirtualRouterName field's value.
func (s *CreateRouteInput) SetVirtualRouterName(v string) *CreateRouteInput {
s.VirtualRouterName = &v
return s
}
type CreateRouteOutput struct {
_ struct{} `type:"structure" payload:"Route"`
// The full description of your mesh following the create call.
//
// Route is a required field
Route *RouteData `locationName:"route" type:"structure" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s CreateRouteOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s CreateRouteOutput) GoString() string {
return s.String()
}
// SetRoute sets the Route field's value.
func (s *CreateRouteOutput) SetRoute(v *RouteData) *CreateRouteOutput {
s.Route = v
return s
}
type CreateVirtualGatewayInput struct {
_ struct{} `type:"structure"`
// Unique, case-sensitive identifier that you provide to ensure the idempotency
// of the request. Up to 36 letters, numbers, hyphens, and underscores are allowed.
ClientToken *string `locationName:"clientToken" type:"string" idempotencyToken:"true"`
// The name of the service mesh to create the virtual gateway in.
//
// MeshName is a required field
MeshName *string `location:"uri" locationName:"meshName" min:"1" type:"string" required:"true"`
// The AWS IAM account ID of the service mesh owner. If the account ID is not
// your own, then the account that you specify must share the mesh with your
// account before you can create the resource in the service mesh. For more
// information about mesh sharing, see Working with shared meshes (https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html).
MeshOwner *string `location:"querystring" locationName:"meshOwner" min:"12" type:"string"`
// The virtual gateway specification to apply.
//
// Spec is a required field
Spec *VirtualGatewaySpec `locationName:"spec" type:"structure" required:"true"`
// Optional metadata that you can apply to the virtual gateway to assist with
// categorization and organization. Each tag consists of a key and an optional
// value, both of which you define. Tag keys can have a maximum character length
// of 128 characters, and tag values can have a maximum length of 256 characters.
Tags []*TagRef `locationName:"tags" type:"list"`
// The name to use for the virtual gateway.
//
// VirtualGatewayName is a required field
VirtualGatewayName *string `locationName:"virtualGatewayName" min:"1" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s CreateVirtualGatewayInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s CreateVirtualGatewayInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *CreateVirtualGatewayInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "CreateVirtualGatewayInput"}
if s.MeshName == nil {
invalidParams.Add(request.NewErrParamRequired("MeshName"))
}
if s.MeshName != nil && len(*s.MeshName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("MeshName", 1))
}
if s.MeshOwner != nil && len(*s.MeshOwner) < 12 {
invalidParams.Add(request.NewErrParamMinLen("MeshOwner", 12))
}
if s.Spec == nil {
invalidParams.Add(request.NewErrParamRequired("Spec"))
}
if s.VirtualGatewayName == nil {
invalidParams.Add(request.NewErrParamRequired("VirtualGatewayName"))
}
if s.VirtualGatewayName != nil && len(*s.VirtualGatewayName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("VirtualGatewayName", 1))
}
if s.Spec != nil {
if err := s.Spec.Validate(); err != nil {
invalidParams.AddNested("Spec", err.(request.ErrInvalidParams))
}
}
if s.Tags != nil {
for i, v := range s.Tags {
if v == nil {
continue
}
if err := v.Validate(); err != nil {
invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams))
}
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetClientToken sets the ClientToken field's value.
func (s *CreateVirtualGatewayInput) SetClientToken(v string) *CreateVirtualGatewayInput {
s.ClientToken = &v
return s
}
// SetMeshName sets the MeshName field's value.
func (s *CreateVirtualGatewayInput) SetMeshName(v string) *CreateVirtualGatewayInput {
s.MeshName = &v
return s
}
// SetMeshOwner sets the MeshOwner field's value.
func (s *CreateVirtualGatewayInput) SetMeshOwner(v string) *CreateVirtualGatewayInput {
s.MeshOwner = &v
return s
}
// SetSpec sets the Spec field's value.
func (s *CreateVirtualGatewayInput) SetSpec(v *VirtualGatewaySpec) *CreateVirtualGatewayInput {
s.Spec = v
return s
}
// SetTags sets the Tags field's value.
func (s *CreateVirtualGatewayInput) SetTags(v []*TagRef) *CreateVirtualGatewayInput {
s.Tags = v
return s
}
// SetVirtualGatewayName sets the VirtualGatewayName field's value.
func (s *CreateVirtualGatewayInput) SetVirtualGatewayName(v string) *CreateVirtualGatewayInput {
s.VirtualGatewayName = &v
return s
}
type CreateVirtualGatewayOutput struct {
_ struct{} `type:"structure" payload:"VirtualGateway"`
// The full description of your virtual gateway following the create call.
//
// VirtualGateway is a required field
VirtualGateway *VirtualGatewayData `locationName:"virtualGateway" type:"structure" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s CreateVirtualGatewayOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s CreateVirtualGatewayOutput) GoString() string {
return s.String()
}
// SetVirtualGateway sets the VirtualGateway field's value.
func (s *CreateVirtualGatewayOutput) SetVirtualGateway(v *VirtualGatewayData) *CreateVirtualGatewayOutput {
s.VirtualGateway = v
return s
}
type CreateVirtualNodeInput struct {
_ struct{} `type:"structure"`
// Unique, case-sensitive identifier that you provide to ensure the idempotency
// of the request. Up to 36 letters, numbers, hyphens, and underscores are allowed.
ClientToken *string `locationName:"clientToken" type:"string" idempotencyToken:"true"`
// The name of the service mesh to create the virtual node in.
//
// MeshName is a required field
MeshName *string `location:"uri" locationName:"meshName" min:"1" type:"string" required:"true"`
// The AWS IAM account ID of the service mesh owner. If the account ID is not
// your own, then the account that you specify must share the mesh with your
// account before you can create the resource in the service mesh. For more
// information about mesh sharing, see Working with shared meshes (https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html).
MeshOwner *string `location:"querystring" locationName:"meshOwner" min:"12" type:"string"`
// The virtual node specification to apply.
//
// Spec is a required field
Spec *VirtualNodeSpec `locationName:"spec" type:"structure" required:"true"`
// Optional metadata that you can apply to the virtual node to assist with categorization
// and organization. Each tag consists of a key and an optional value, both
// of which you define. Tag keys can have a maximum character length of 128
// characters, and tag values can have a maximum length of 256 characters.
Tags []*TagRef `locationName:"tags" type:"list"`
// The name to use for the virtual node.
//
// VirtualNodeName is a required field
VirtualNodeName *string `locationName:"virtualNodeName" min:"1" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s CreateVirtualNodeInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s CreateVirtualNodeInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *CreateVirtualNodeInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "CreateVirtualNodeInput"}
if s.MeshName == nil {
invalidParams.Add(request.NewErrParamRequired("MeshName"))
}
if s.MeshName != nil && len(*s.MeshName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("MeshName", 1))
}
if s.MeshOwner != nil && len(*s.MeshOwner) < 12 {
invalidParams.Add(request.NewErrParamMinLen("MeshOwner", 12))
}
if s.Spec == nil {
invalidParams.Add(request.NewErrParamRequired("Spec"))
}
if s.VirtualNodeName == nil {
invalidParams.Add(request.NewErrParamRequired("VirtualNodeName"))
}
if s.VirtualNodeName != nil && len(*s.VirtualNodeName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("VirtualNodeName", 1))
}
if s.Spec != nil {
if err := s.Spec.Validate(); err != nil {
invalidParams.AddNested("Spec", err.(request.ErrInvalidParams))
}
}
if s.Tags != nil {
for i, v := range s.Tags {
if v == nil {
continue
}
if err := v.Validate(); err != nil {
invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams))
}
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetClientToken sets the ClientToken field's value.
func (s *CreateVirtualNodeInput) SetClientToken(v string) *CreateVirtualNodeInput {
s.ClientToken = &v
return s
}
// SetMeshName sets the MeshName field's value.
func (s *CreateVirtualNodeInput) SetMeshName(v string) *CreateVirtualNodeInput {
s.MeshName = &v
return s
}
// SetMeshOwner sets the MeshOwner field's value.
func (s *CreateVirtualNodeInput) SetMeshOwner(v string) *CreateVirtualNodeInput {
s.MeshOwner = &v
return s
}
// SetSpec sets the Spec field's value.
func (s *CreateVirtualNodeInput) SetSpec(v *VirtualNodeSpec) *CreateVirtualNodeInput {
s.Spec = v
return s
}
// SetTags sets the Tags field's value.
func (s *CreateVirtualNodeInput) SetTags(v []*TagRef) *CreateVirtualNodeInput {
s.Tags = v
return s
}
// SetVirtualNodeName sets the VirtualNodeName field's value.
func (s *CreateVirtualNodeInput) SetVirtualNodeName(v string) *CreateVirtualNodeInput {
s.VirtualNodeName = &v
return s
}
type CreateVirtualNodeOutput struct {
_ struct{} `type:"structure" payload:"VirtualNode"`
// The full description of your virtual node following the create call.
//
// VirtualNode is a required field
VirtualNode *VirtualNodeData `locationName:"virtualNode" type:"structure" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s CreateVirtualNodeOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s CreateVirtualNodeOutput) GoString() string {
return s.String()
}
// SetVirtualNode sets the VirtualNode field's value.
func (s *CreateVirtualNodeOutput) SetVirtualNode(v *VirtualNodeData) *CreateVirtualNodeOutput {
s.VirtualNode = v
return s
}
type CreateVirtualRouterInput struct {
_ struct{} `type:"structure"`
// Unique, case-sensitive identifier that you provide to ensure the idempotency
// of the request. Up to 36 letters, numbers, hyphens, and underscores are allowed.
ClientToken *string `locationName:"clientToken" type:"string" idempotencyToken:"true"`
// The name of the service mesh to create the virtual router in.
//
// MeshName is a required field
MeshName *string `location:"uri" locationName:"meshName" min:"1" type:"string" required:"true"`
// The AWS IAM account ID of the service mesh owner. If the account ID is not
// your own, then the account that you specify must share the mesh with your
// account before you can create the resource in the service mesh. For more
// information about mesh sharing, see Working with shared meshes (https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html).
MeshOwner *string `location:"querystring" locationName:"meshOwner" min:"12" type:"string"`
// The virtual router specification to apply.
//
// Spec is a required field
Spec *VirtualRouterSpec `locationName:"spec" type:"structure" required:"true"`
// Optional metadata that you can apply to the virtual router to assist with
// categorization and organization. Each tag consists of a key and an optional
// value, both of which you define. Tag keys can have a maximum character length
// of 128 characters, and tag values can have a maximum length of 256 characters.
Tags []*TagRef `locationName:"tags" type:"list"`
// The name to use for the virtual router.
//
// VirtualRouterName is a required field
VirtualRouterName *string `locationName:"virtualRouterName" min:"1" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s CreateVirtualRouterInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s CreateVirtualRouterInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *CreateVirtualRouterInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "CreateVirtualRouterInput"}
if s.MeshName == nil {
invalidParams.Add(request.NewErrParamRequired("MeshName"))
}
if s.MeshName != nil && len(*s.MeshName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("MeshName", 1))
}
if s.MeshOwner != nil && len(*s.MeshOwner) < 12 {
invalidParams.Add(request.NewErrParamMinLen("MeshOwner", 12))
}
if s.Spec == nil {
invalidParams.Add(request.NewErrParamRequired("Spec"))
}
if s.VirtualRouterName == nil {
invalidParams.Add(request.NewErrParamRequired("VirtualRouterName"))
}
if s.VirtualRouterName != nil && len(*s.VirtualRouterName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("VirtualRouterName", 1))
}
if s.Spec != nil {
if err := s.Spec.Validate(); err != nil {
invalidParams.AddNested("Spec", err.(request.ErrInvalidParams))
}
}
if s.Tags != nil {
for i, v := range s.Tags {
if v == nil {
continue
}
if err := v.Validate(); err != nil {
invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams))
}
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetClientToken sets the ClientToken field's value.
func (s *CreateVirtualRouterInput) SetClientToken(v string) *CreateVirtualRouterInput {
s.ClientToken = &v
return s
}
// SetMeshName sets the MeshName field's value.
func (s *CreateVirtualRouterInput) SetMeshName(v string) *CreateVirtualRouterInput {
s.MeshName = &v
return s
}
// SetMeshOwner sets the MeshOwner field's value.
func (s *CreateVirtualRouterInput) SetMeshOwner(v string) *CreateVirtualRouterInput {
s.MeshOwner = &v
return s
}
// SetSpec sets the Spec field's value.
func (s *CreateVirtualRouterInput) SetSpec(v *VirtualRouterSpec) *CreateVirtualRouterInput {
s.Spec = v
return s
}
// SetTags sets the Tags field's value.
func (s *CreateVirtualRouterInput) SetTags(v []*TagRef) *CreateVirtualRouterInput {
s.Tags = v
return s
}
// SetVirtualRouterName sets the VirtualRouterName field's value.
func (s *CreateVirtualRouterInput) SetVirtualRouterName(v string) *CreateVirtualRouterInput {
s.VirtualRouterName = &v
return s
}
type CreateVirtualRouterOutput struct {
_ struct{} `type:"structure" payload:"VirtualRouter"`
// The full description of your virtual router following the create call.
//
// VirtualRouter is a required field
VirtualRouter *VirtualRouterData `locationName:"virtualRouter" type:"structure" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s CreateVirtualRouterOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s CreateVirtualRouterOutput) GoString() string {
return s.String()
}
// SetVirtualRouter sets the VirtualRouter field's value.
func (s *CreateVirtualRouterOutput) SetVirtualRouter(v *VirtualRouterData) *CreateVirtualRouterOutput {
s.VirtualRouter = v
return s
}
type CreateVirtualServiceInput struct {
_ struct{} `type:"structure"`
// Unique, case-sensitive identifier that you provide to ensure the idempotency
// of the request. Up to 36 letters, numbers, hyphens, and underscores are allowed.
ClientToken *string `locationName:"clientToken" type:"string" idempotencyToken:"true"`
// The name of the service mesh to create the virtual service in.
//
// MeshName is a required field
MeshName *string `location:"uri" locationName:"meshName" min:"1" type:"string" required:"true"`
// The AWS IAM account ID of the service mesh owner. If the account ID is not
// your own, then the account that you specify must share the mesh with your
// account before you can create the resource in the service mesh. For more
// information about mesh sharing, see Working with shared meshes (https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html).
MeshOwner *string `location:"querystring" locationName:"meshOwner" min:"12" type:"string"`
// The virtual service specification to apply.
//
// Spec is a required field
Spec *VirtualServiceSpec `locationName:"spec" type:"structure" required:"true"`
// Optional metadata that you can apply to the virtual service to assist with
// categorization and organization. Each tag consists of a key and an optional
// value, both of which you define. Tag keys can have a maximum character length
// of 128 characters, and tag values can have a maximum length of 256 characters.
Tags []*TagRef `locationName:"tags" type:"list"`
// The name to use for the virtual service.
//
// VirtualServiceName is a required field
VirtualServiceName *string `locationName:"virtualServiceName" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s CreateVirtualServiceInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s CreateVirtualServiceInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *CreateVirtualServiceInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "CreateVirtualServiceInput"}
if s.MeshName == nil {
invalidParams.Add(request.NewErrParamRequired("MeshName"))
}
if s.MeshName != nil && len(*s.MeshName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("MeshName", 1))
}
if s.MeshOwner != nil && len(*s.MeshOwner) < 12 {
invalidParams.Add(request.NewErrParamMinLen("MeshOwner", 12))
}
if s.Spec == nil {
invalidParams.Add(request.NewErrParamRequired("Spec"))
}
if s.VirtualServiceName == nil {
invalidParams.Add(request.NewErrParamRequired("VirtualServiceName"))
}
if s.Spec != nil {
if err := s.Spec.Validate(); err != nil {
invalidParams.AddNested("Spec", err.(request.ErrInvalidParams))
}
}
if s.Tags != nil {
for i, v := range s.Tags {
if v == nil {
continue
}
if err := v.Validate(); err != nil {
invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams))
}
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetClientToken sets the ClientToken field's value.
func (s *CreateVirtualServiceInput) SetClientToken(v string) *CreateVirtualServiceInput {
s.ClientToken = &v
return s
}
// SetMeshName sets the MeshName field's value.
func (s *CreateVirtualServiceInput) SetMeshName(v string) *CreateVirtualServiceInput {
s.MeshName = &v
return s
}
// SetMeshOwner sets the MeshOwner field's value.
func (s *CreateVirtualServiceInput) SetMeshOwner(v string) *CreateVirtualServiceInput {
s.MeshOwner = &v
return s
}
// SetSpec sets the Spec field's value.
func (s *CreateVirtualServiceInput) SetSpec(v *VirtualServiceSpec) *CreateVirtualServiceInput {
s.Spec = v
return s
}
// SetTags sets the Tags field's value.
func (s *CreateVirtualServiceInput) SetTags(v []*TagRef) *CreateVirtualServiceInput {
s.Tags = v
return s
}
// SetVirtualServiceName sets the VirtualServiceName field's value.
func (s *CreateVirtualServiceInput) SetVirtualServiceName(v string) *CreateVirtualServiceInput {
s.VirtualServiceName = &v
return s
}
type CreateVirtualServiceOutput struct {
_ struct{} `type:"structure" payload:"VirtualService"`
// The full description of your virtual service following the create call.
//
// VirtualService is a required field
VirtualService *VirtualServiceData `locationName:"virtualService" type:"structure" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s CreateVirtualServiceOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s CreateVirtualServiceOutput) GoString() string {
return s.String()
}
// SetVirtualService sets the VirtualService field's value.
func (s *CreateVirtualServiceOutput) SetVirtualService(v *VirtualServiceData) *CreateVirtualServiceOutput {
s.VirtualService = v
return s
}
type DeleteGatewayRouteInput struct {
_ struct{} `type:"structure"`
// The name of the gateway route to delete.
//
// GatewayRouteName is a required field
GatewayRouteName *string `location:"uri" locationName:"gatewayRouteName" min:"1" type:"string" required:"true"`
// The name of the service mesh to delete the gateway route from.
//
// MeshName is a required field
MeshName *string `location:"uri" locationName:"meshName" min:"1" type:"string" required:"true"`
// The AWS IAM account ID of the service mesh owner. If the account ID is not
// your own, then it's the ID of the account that shared the mesh with your
// account. For more information about mesh sharing, see Working with shared
// meshes (https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html).
MeshOwner *string `location:"querystring" locationName:"meshOwner" min:"12" type:"string"`
// The name of the virtual gateway to delete the route from.
//
// VirtualGatewayName is a required field
VirtualGatewayName *string `location:"uri" locationName:"virtualGatewayName" min:"1" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DeleteGatewayRouteInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DeleteGatewayRouteInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *DeleteGatewayRouteInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "DeleteGatewayRouteInput"}
if s.GatewayRouteName == nil {
invalidParams.Add(request.NewErrParamRequired("GatewayRouteName"))
}
if s.GatewayRouteName != nil && len(*s.GatewayRouteName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("GatewayRouteName", 1))
}
if s.MeshName == nil {
invalidParams.Add(request.NewErrParamRequired("MeshName"))
}
if s.MeshName != nil && len(*s.MeshName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("MeshName", 1))
}
if s.MeshOwner != nil && len(*s.MeshOwner) < 12 {
invalidParams.Add(request.NewErrParamMinLen("MeshOwner", 12))
}
if s.VirtualGatewayName == nil {
invalidParams.Add(request.NewErrParamRequired("VirtualGatewayName"))
}
if s.VirtualGatewayName != nil && len(*s.VirtualGatewayName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("VirtualGatewayName", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetGatewayRouteName sets the GatewayRouteName field's value.
func (s *DeleteGatewayRouteInput) SetGatewayRouteName(v string) *DeleteGatewayRouteInput {
s.GatewayRouteName = &v
return s
}
// SetMeshName sets the MeshName field's value.
func (s *DeleteGatewayRouteInput) SetMeshName(v string) *DeleteGatewayRouteInput {
s.MeshName = &v
return s
}
// SetMeshOwner sets the MeshOwner field's value.
func (s *DeleteGatewayRouteInput) SetMeshOwner(v string) *DeleteGatewayRouteInput {
s.MeshOwner = &v
return s
}
// SetVirtualGatewayName sets the VirtualGatewayName field's value.
func (s *DeleteGatewayRouteInput) SetVirtualGatewayName(v string) *DeleteGatewayRouteInput {
s.VirtualGatewayName = &v
return s
}
type DeleteGatewayRouteOutput struct {
_ struct{} `type:"structure" payload:"GatewayRoute"`
// The gateway route that was deleted.
//
// GatewayRoute is a required field
GatewayRoute *GatewayRouteData `locationName:"gatewayRoute" type:"structure" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DeleteGatewayRouteOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DeleteGatewayRouteOutput) GoString() string {
return s.String()
}
// SetGatewayRoute sets the GatewayRoute field's value.
func (s *DeleteGatewayRouteOutput) SetGatewayRoute(v *GatewayRouteData) *DeleteGatewayRouteOutput {
s.GatewayRoute = v
return s
}
type DeleteMeshInput struct {
_ struct{} `type:"structure"`
// The name of the service mesh to delete.
//
// MeshName is a required field
MeshName *string `location:"uri" locationName:"meshName" min:"1" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DeleteMeshInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DeleteMeshInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *DeleteMeshInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "DeleteMeshInput"}
if s.MeshName == nil {
invalidParams.Add(request.NewErrParamRequired("MeshName"))
}
if s.MeshName != nil && len(*s.MeshName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("MeshName", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetMeshName sets the MeshName field's value.
func (s *DeleteMeshInput) SetMeshName(v string) *DeleteMeshInput {
s.MeshName = &v
return s
}
type DeleteMeshOutput struct {
_ struct{} `type:"structure" payload:"Mesh"`
// The service mesh that was deleted.
//
// Mesh is a required field
Mesh *MeshData `locationName:"mesh" type:"structure" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DeleteMeshOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DeleteMeshOutput) GoString() string {
return s.String()
}
// SetMesh sets the Mesh field's value.
func (s *DeleteMeshOutput) SetMesh(v *MeshData) *DeleteMeshOutput {
s.Mesh = v
return s
}
type DeleteRouteInput struct {
_ struct{} `type:"structure"`
// The name of the service mesh to delete the route in.
//
// MeshName is a required field
MeshName *string `location:"uri" locationName:"meshName" min:"1" type:"string" required:"true"`
// The AWS IAM account ID of the service mesh owner. If the account ID is not
// your own, then it's the ID of the account that shared the mesh with your
// account. For more information about mesh sharing, see Working with shared
// meshes (https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html).
MeshOwner *string `location:"querystring" locationName:"meshOwner" min:"12" type:"string"`
// The name of the route to delete.
//
// RouteName is a required field
RouteName *string `location:"uri" locationName:"routeName" min:"1" type:"string" required:"true"`
// The name of the virtual router to delete the route in.
//
// VirtualRouterName is a required field
VirtualRouterName *string `location:"uri" locationName:"virtualRouterName" min:"1" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DeleteRouteInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DeleteRouteInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *DeleteRouteInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "DeleteRouteInput"}
if s.MeshName == nil {
invalidParams.Add(request.NewErrParamRequired("MeshName"))
}
if s.MeshName != nil && len(*s.MeshName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("MeshName", 1))
}
if s.MeshOwner != nil && len(*s.MeshOwner) < 12 {
invalidParams.Add(request.NewErrParamMinLen("MeshOwner", 12))
}
if s.RouteName == nil {
invalidParams.Add(request.NewErrParamRequired("RouteName"))
}
if s.RouteName != nil && len(*s.RouteName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("RouteName", 1))
}
if s.VirtualRouterName == nil {
invalidParams.Add(request.NewErrParamRequired("VirtualRouterName"))
}
if s.VirtualRouterName != nil && len(*s.VirtualRouterName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("VirtualRouterName", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetMeshName sets the MeshName field's value.
func (s *DeleteRouteInput) SetMeshName(v string) *DeleteRouteInput {
s.MeshName = &v
return s
}
// SetMeshOwner sets the MeshOwner field's value.
func (s *DeleteRouteInput) SetMeshOwner(v string) *DeleteRouteInput {
s.MeshOwner = &v
return s
}
// SetRouteName sets the RouteName field's value.
func (s *DeleteRouteInput) SetRouteName(v string) *DeleteRouteInput {
s.RouteName = &v
return s
}
// SetVirtualRouterName sets the VirtualRouterName field's value.
func (s *DeleteRouteInput) SetVirtualRouterName(v string) *DeleteRouteInput {
s.VirtualRouterName = &v
return s
}
type DeleteRouteOutput struct {
_ struct{} `type:"structure" payload:"Route"`
// The route that was deleted.
//
// Route is a required field
Route *RouteData `locationName:"route" type:"structure" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DeleteRouteOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DeleteRouteOutput) GoString() string {
return s.String()
}
// SetRoute sets the Route field's value.
func (s *DeleteRouteOutput) SetRoute(v *RouteData) *DeleteRouteOutput {
s.Route = v
return s
}
type DeleteVirtualGatewayInput struct {
_ struct{} `type:"structure"`
// The name of the service mesh to delete the virtual gateway from.
//
// MeshName is a required field
MeshName *string `location:"uri" locationName:"meshName" min:"1" type:"string" required:"true"`
// The AWS IAM account ID of the service mesh owner. If the account ID is not
// your own, then it's the ID of the account that shared the mesh with your
// account. For more information about mesh sharing, see Working with shared
// meshes (https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html).
MeshOwner *string `location:"querystring" locationName:"meshOwner" min:"12" type:"string"`
// The name of the virtual gateway to delete.
//
// VirtualGatewayName is a required field
VirtualGatewayName *string `location:"uri" locationName:"virtualGatewayName" min:"1" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DeleteVirtualGatewayInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DeleteVirtualGatewayInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *DeleteVirtualGatewayInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "DeleteVirtualGatewayInput"}
if s.MeshName == nil {
invalidParams.Add(request.NewErrParamRequired("MeshName"))
}
if s.MeshName != nil && len(*s.MeshName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("MeshName", 1))
}
if s.MeshOwner != nil && len(*s.MeshOwner) < 12 {
invalidParams.Add(request.NewErrParamMinLen("MeshOwner", 12))
}
if s.VirtualGatewayName == nil {
invalidParams.Add(request.NewErrParamRequired("VirtualGatewayName"))
}
if s.VirtualGatewayName != nil && len(*s.VirtualGatewayName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("VirtualGatewayName", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetMeshName sets the MeshName field's value.
func (s *DeleteVirtualGatewayInput) SetMeshName(v string) *DeleteVirtualGatewayInput {
s.MeshName = &v
return s
}
// SetMeshOwner sets the MeshOwner field's value.
func (s *DeleteVirtualGatewayInput) SetMeshOwner(v string) *DeleteVirtualGatewayInput {
s.MeshOwner = &v
return s
}
// SetVirtualGatewayName sets the VirtualGatewayName field's value.
func (s *DeleteVirtualGatewayInput) SetVirtualGatewayName(v string) *DeleteVirtualGatewayInput {
s.VirtualGatewayName = &v
return s
}
type DeleteVirtualGatewayOutput struct {
_ struct{} `type:"structure" payload:"VirtualGateway"`
// The virtual gateway that was deleted.
//
// VirtualGateway is a required field
VirtualGateway *VirtualGatewayData `locationName:"virtualGateway" type:"structure" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DeleteVirtualGatewayOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DeleteVirtualGatewayOutput) GoString() string {
return s.String()
}
// SetVirtualGateway sets the VirtualGateway field's value.
func (s *DeleteVirtualGatewayOutput) SetVirtualGateway(v *VirtualGatewayData) *DeleteVirtualGatewayOutput {
s.VirtualGateway = v
return s
}
// Deletes a virtual node input.
type DeleteVirtualNodeInput struct {
_ struct{} `type:"structure"`
// The name of the service mesh to delete the virtual node in.
//
// MeshName is a required field
MeshName *string `location:"uri" locationName:"meshName" min:"1" type:"string" required:"true"`
// The AWS IAM account ID of the service mesh owner. If the account ID is not
// your own, then it's the ID of the account that shared the mesh with your
// account. For more information about mesh sharing, see Working with shared
// meshes (https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html).
MeshOwner *string `location:"querystring" locationName:"meshOwner" min:"12" type:"string"`
// The name of the virtual node to delete.
//
// VirtualNodeName is a required field
VirtualNodeName *string `location:"uri" locationName:"virtualNodeName" min:"1" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DeleteVirtualNodeInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DeleteVirtualNodeInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *DeleteVirtualNodeInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "DeleteVirtualNodeInput"}
if s.MeshName == nil {
invalidParams.Add(request.NewErrParamRequired("MeshName"))
}
if s.MeshName != nil && len(*s.MeshName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("MeshName", 1))
}
if s.MeshOwner != nil && len(*s.MeshOwner) < 12 {
invalidParams.Add(request.NewErrParamMinLen("MeshOwner", 12))
}
if s.VirtualNodeName == nil {
invalidParams.Add(request.NewErrParamRequired("VirtualNodeName"))
}
if s.VirtualNodeName != nil && len(*s.VirtualNodeName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("VirtualNodeName", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetMeshName sets the MeshName field's value.
func (s *DeleteVirtualNodeInput) SetMeshName(v string) *DeleteVirtualNodeInput {
s.MeshName = &v
return s
}
// SetMeshOwner sets the MeshOwner field's value.
func (s *DeleteVirtualNodeInput) SetMeshOwner(v string) *DeleteVirtualNodeInput {
s.MeshOwner = &v
return s
}
// SetVirtualNodeName sets the VirtualNodeName field's value.
func (s *DeleteVirtualNodeInput) SetVirtualNodeName(v string) *DeleteVirtualNodeInput {
s.VirtualNodeName = &v
return s
}
type DeleteVirtualNodeOutput struct {
_ struct{} `type:"structure" payload:"VirtualNode"`
// The virtual node that was deleted.
//
// VirtualNode is a required field
VirtualNode *VirtualNodeData `locationName:"virtualNode" type:"structure" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DeleteVirtualNodeOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DeleteVirtualNodeOutput) GoString() string {
return s.String()
}
// SetVirtualNode sets the VirtualNode field's value.
func (s *DeleteVirtualNodeOutput) SetVirtualNode(v *VirtualNodeData) *DeleteVirtualNodeOutput {
s.VirtualNode = v
return s
}
type DeleteVirtualRouterInput struct {
_ struct{} `type:"structure"`
// The name of the service mesh to delete the virtual router in.
//
// MeshName is a required field
MeshName *string `location:"uri" locationName:"meshName" min:"1" type:"string" required:"true"`
// The AWS IAM account ID of the service mesh owner. If the account ID is not
// your own, then it's the ID of the account that shared the mesh with your
// account. For more information about mesh sharing, see Working with shared
// meshes (https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html).
MeshOwner *string `location:"querystring" locationName:"meshOwner" min:"12" type:"string"`
// The name of the virtual router to delete.
//
// VirtualRouterName is a required field
VirtualRouterName *string `location:"uri" locationName:"virtualRouterName" min:"1" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DeleteVirtualRouterInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DeleteVirtualRouterInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *DeleteVirtualRouterInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "DeleteVirtualRouterInput"}
if s.MeshName == nil {
invalidParams.Add(request.NewErrParamRequired("MeshName"))
}
if s.MeshName != nil && len(*s.MeshName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("MeshName", 1))
}
if s.MeshOwner != nil && len(*s.MeshOwner) < 12 {
invalidParams.Add(request.NewErrParamMinLen("MeshOwner", 12))
}
if s.VirtualRouterName == nil {
invalidParams.Add(request.NewErrParamRequired("VirtualRouterName"))
}
if s.VirtualRouterName != nil && len(*s.VirtualRouterName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("VirtualRouterName", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetMeshName sets the MeshName field's value.
func (s *DeleteVirtualRouterInput) SetMeshName(v string) *DeleteVirtualRouterInput {
s.MeshName = &v
return s
}
// SetMeshOwner sets the MeshOwner field's value.
func (s *DeleteVirtualRouterInput) SetMeshOwner(v string) *DeleteVirtualRouterInput {
s.MeshOwner = &v
return s
}
// SetVirtualRouterName sets the VirtualRouterName field's value.
func (s *DeleteVirtualRouterInput) SetVirtualRouterName(v string) *DeleteVirtualRouterInput {
s.VirtualRouterName = &v
return s
}
type DeleteVirtualRouterOutput struct {
_ struct{} `type:"structure" payload:"VirtualRouter"`
// The virtual router that was deleted.
//
// VirtualRouter is a required field
VirtualRouter *VirtualRouterData `locationName:"virtualRouter" type:"structure" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DeleteVirtualRouterOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DeleteVirtualRouterOutput) GoString() string {
return s.String()
}
// SetVirtualRouter sets the VirtualRouter field's value.
func (s *DeleteVirtualRouterOutput) SetVirtualRouter(v *VirtualRouterData) *DeleteVirtualRouterOutput {
s.VirtualRouter = v
return s
}
type DeleteVirtualServiceInput struct {
_ struct{} `type:"structure"`
// The name of the service mesh to delete the virtual service in.
//
// MeshName is a required field
MeshName *string `location:"uri" locationName:"meshName" min:"1" type:"string" required:"true"`
// The AWS IAM account ID of the service mesh owner. If the account ID is not
// your own, then it's the ID of the account that shared the mesh with your
// account. For more information about mesh sharing, see Working with shared
// meshes (https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html).
MeshOwner *string `location:"querystring" locationName:"meshOwner" min:"12" type:"string"`
// The name of the virtual service to delete.
//
// VirtualServiceName is a required field
VirtualServiceName *string `location:"uri" locationName:"virtualServiceName" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DeleteVirtualServiceInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DeleteVirtualServiceInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *DeleteVirtualServiceInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "DeleteVirtualServiceInput"}
if s.MeshName == nil {
invalidParams.Add(request.NewErrParamRequired("MeshName"))
}
if s.MeshName != nil && len(*s.MeshName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("MeshName", 1))
}
if s.MeshOwner != nil && len(*s.MeshOwner) < 12 {
invalidParams.Add(request.NewErrParamMinLen("MeshOwner", 12))
}
if s.VirtualServiceName == nil {
invalidParams.Add(request.NewErrParamRequired("VirtualServiceName"))
}
if s.VirtualServiceName != nil && len(*s.VirtualServiceName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("VirtualServiceName", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetMeshName sets the MeshName field's value.
func (s *DeleteVirtualServiceInput) SetMeshName(v string) *DeleteVirtualServiceInput {
s.MeshName = &v
return s
}
// SetMeshOwner sets the MeshOwner field's value.
func (s *DeleteVirtualServiceInput) SetMeshOwner(v string) *DeleteVirtualServiceInput {
s.MeshOwner = &v
return s
}
// SetVirtualServiceName sets the VirtualServiceName field's value.
func (s *DeleteVirtualServiceInput) SetVirtualServiceName(v string) *DeleteVirtualServiceInput {
s.VirtualServiceName = &v
return s
}
type DeleteVirtualServiceOutput struct {
_ struct{} `type:"structure" payload:"VirtualService"`
// The virtual service that was deleted.
//
// VirtualService is a required field
VirtualService *VirtualServiceData `locationName:"virtualService" type:"structure" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DeleteVirtualServiceOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DeleteVirtualServiceOutput) GoString() string {
return s.String()
}
// SetVirtualService sets the VirtualService field's value.
func (s *DeleteVirtualServiceOutput) SetVirtualService(v *VirtualServiceData) *DeleteVirtualServiceOutput {
s.VirtualService = v
return s
}
type DescribeGatewayRouteInput struct {
_ struct{} `type:"structure"`
// The name of the gateway route to describe.
//
// GatewayRouteName is a required field
GatewayRouteName *string `location:"uri" locationName:"gatewayRouteName" min:"1" type:"string" required:"true"`
// The name of the service mesh that the gateway route resides in.
//
// MeshName is a required field
MeshName *string `location:"uri" locationName:"meshName" min:"1" type:"string" required:"true"`
// The AWS IAM account ID of the service mesh owner. If the account ID is not
// your own, then it's the ID of the account that shared the mesh with your
// account. For more information about mesh sharing, see Working with shared
// meshes (https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html).
MeshOwner *string `location:"querystring" locationName:"meshOwner" min:"12" type:"string"`
// The name of the virtual gateway that the gateway route is associated with.
//
// VirtualGatewayName is a required field
VirtualGatewayName *string `location:"uri" locationName:"virtualGatewayName" min:"1" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DescribeGatewayRouteInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DescribeGatewayRouteInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *DescribeGatewayRouteInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "DescribeGatewayRouteInput"}
if s.GatewayRouteName == nil {
invalidParams.Add(request.NewErrParamRequired("GatewayRouteName"))
}
if s.GatewayRouteName != nil && len(*s.GatewayRouteName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("GatewayRouteName", 1))
}
if s.MeshName == nil {
invalidParams.Add(request.NewErrParamRequired("MeshName"))
}
if s.MeshName != nil && len(*s.MeshName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("MeshName", 1))
}
if s.MeshOwner != nil && len(*s.MeshOwner) < 12 {
invalidParams.Add(request.NewErrParamMinLen("MeshOwner", 12))
}
if s.VirtualGatewayName == nil {
invalidParams.Add(request.NewErrParamRequired("VirtualGatewayName"))
}
if s.VirtualGatewayName != nil && len(*s.VirtualGatewayName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("VirtualGatewayName", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetGatewayRouteName sets the GatewayRouteName field's value.
func (s *DescribeGatewayRouteInput) SetGatewayRouteName(v string) *DescribeGatewayRouteInput {
s.GatewayRouteName = &v
return s
}
// SetMeshName sets the MeshName field's value.
func (s *DescribeGatewayRouteInput) SetMeshName(v string) *DescribeGatewayRouteInput {
s.MeshName = &v
return s
}
// SetMeshOwner sets the MeshOwner field's value.
func (s *DescribeGatewayRouteInput) SetMeshOwner(v string) *DescribeGatewayRouteInput {
s.MeshOwner = &v
return s
}
// SetVirtualGatewayName sets the VirtualGatewayName field's value.
func (s *DescribeGatewayRouteInput) SetVirtualGatewayName(v string) *DescribeGatewayRouteInput {
s.VirtualGatewayName = &v
return s
}
type DescribeGatewayRouteOutput struct {
_ struct{} `type:"structure" payload:"GatewayRoute"`
// The full description of your gateway route.
//
// GatewayRoute is a required field
GatewayRoute *GatewayRouteData `locationName:"gatewayRoute" type:"structure" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DescribeGatewayRouteOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DescribeGatewayRouteOutput) GoString() string {
return s.String()
}
// SetGatewayRoute sets the GatewayRoute field's value.
func (s *DescribeGatewayRouteOutput) SetGatewayRoute(v *GatewayRouteData) *DescribeGatewayRouteOutput {
s.GatewayRoute = v
return s
}
type DescribeMeshInput struct {
_ struct{} `type:"structure"`
// The name of the service mesh to describe.
//
// MeshName is a required field
MeshName *string `location:"uri" locationName:"meshName" min:"1" type:"string" required:"true"`
// The AWS IAM account ID of the service mesh owner. If the account ID is not
// your own, then it's the ID of the account that shared the mesh with your
// account. For more information about mesh sharing, see Working with shared
// meshes (https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html).
MeshOwner *string `location:"querystring" locationName:"meshOwner" min:"12" type:"string"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DescribeMeshInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DescribeMeshInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *DescribeMeshInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "DescribeMeshInput"}
if s.MeshName == nil {
invalidParams.Add(request.NewErrParamRequired("MeshName"))
}
if s.MeshName != nil && len(*s.MeshName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("MeshName", 1))
}
if s.MeshOwner != nil && len(*s.MeshOwner) < 12 {
invalidParams.Add(request.NewErrParamMinLen("MeshOwner", 12))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetMeshName sets the MeshName field's value.
func (s *DescribeMeshInput) SetMeshName(v string) *DescribeMeshInput {
s.MeshName = &v
return s
}
// SetMeshOwner sets the MeshOwner field's value.
func (s *DescribeMeshInput) SetMeshOwner(v string) *DescribeMeshInput {
s.MeshOwner = &v
return s
}
type DescribeMeshOutput struct {
_ struct{} `type:"structure" payload:"Mesh"`
// The full description of your service mesh.
//
// Mesh is a required field
Mesh *MeshData `locationName:"mesh" type:"structure" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DescribeMeshOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DescribeMeshOutput) GoString() string {
return s.String()
}
// SetMesh sets the Mesh field's value.
func (s *DescribeMeshOutput) SetMesh(v *MeshData) *DescribeMeshOutput {
s.Mesh = v
return s
}
type DescribeRouteInput struct {
_ struct{} `type:"structure"`
// The name of the service mesh that the route resides in.
//
// MeshName is a required field
MeshName *string `location:"uri" locationName:"meshName" min:"1" type:"string" required:"true"`
// The AWS IAM account ID of the service mesh owner. If the account ID is not
// your own, then it's the ID of the account that shared the mesh with your
// account. For more information about mesh sharing, see Working with shared
// meshes (https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html).
MeshOwner *string `location:"querystring" locationName:"meshOwner" min:"12" type:"string"`
// The name of the route to describe.
//
// RouteName is a required field
RouteName *string `location:"uri" locationName:"routeName" min:"1" type:"string" required:"true"`
// The name of the virtual router that the route is associated with.
//
// VirtualRouterName is a required field
VirtualRouterName *string `location:"uri" locationName:"virtualRouterName" min:"1" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DescribeRouteInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DescribeRouteInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *DescribeRouteInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "DescribeRouteInput"}
if s.MeshName == nil {
invalidParams.Add(request.NewErrParamRequired("MeshName"))
}
if s.MeshName != nil && len(*s.MeshName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("MeshName", 1))
}
if s.MeshOwner != nil && len(*s.MeshOwner) < 12 {
invalidParams.Add(request.NewErrParamMinLen("MeshOwner", 12))
}
if s.RouteName == nil {
invalidParams.Add(request.NewErrParamRequired("RouteName"))
}
if s.RouteName != nil && len(*s.RouteName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("RouteName", 1))
}
if s.VirtualRouterName == nil {
invalidParams.Add(request.NewErrParamRequired("VirtualRouterName"))
}
if s.VirtualRouterName != nil && len(*s.VirtualRouterName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("VirtualRouterName", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetMeshName sets the MeshName field's value.
func (s *DescribeRouteInput) SetMeshName(v string) *DescribeRouteInput {
s.MeshName = &v
return s
}
// SetMeshOwner sets the MeshOwner field's value.
func (s *DescribeRouteInput) SetMeshOwner(v string) *DescribeRouteInput {
s.MeshOwner = &v
return s
}
// SetRouteName sets the RouteName field's value.
func (s *DescribeRouteInput) SetRouteName(v string) *DescribeRouteInput {
s.RouteName = &v
return s
}
// SetVirtualRouterName sets the VirtualRouterName field's value.
func (s *DescribeRouteInput) SetVirtualRouterName(v string) *DescribeRouteInput {
s.VirtualRouterName = &v
return s
}
type DescribeRouteOutput struct {
_ struct{} `type:"structure" payload:"Route"`
// The full description of your route.
//
// Route is a required field
Route *RouteData `locationName:"route" type:"structure" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DescribeRouteOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DescribeRouteOutput) GoString() string {
return s.String()
}
// SetRoute sets the Route field's value.
func (s *DescribeRouteOutput) SetRoute(v *RouteData) *DescribeRouteOutput {
s.Route = v
return s
}
type DescribeVirtualGatewayInput struct {
_ struct{} `type:"structure"`
// The name of the service mesh that the gateway route resides in.
//
// MeshName is a required field
MeshName *string `location:"uri" locationName:"meshName" min:"1" type:"string" required:"true"`
// The AWS IAM account ID of the service mesh owner. If the account ID is not
// your own, then it's the ID of the account that shared the mesh with your
// account. For more information about mesh sharing, see Working with shared
// meshes (https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html).
MeshOwner *string `location:"querystring" locationName:"meshOwner" min:"12" type:"string"`
// The name of the virtual gateway to describe.
//
// VirtualGatewayName is a required field
VirtualGatewayName *string `location:"uri" locationName:"virtualGatewayName" min:"1" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DescribeVirtualGatewayInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DescribeVirtualGatewayInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *DescribeVirtualGatewayInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "DescribeVirtualGatewayInput"}
if s.MeshName == nil {
invalidParams.Add(request.NewErrParamRequired("MeshName"))
}
if s.MeshName != nil && len(*s.MeshName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("MeshName", 1))
}
if s.MeshOwner != nil && len(*s.MeshOwner) < 12 {
invalidParams.Add(request.NewErrParamMinLen("MeshOwner", 12))
}
if s.VirtualGatewayName == nil {
invalidParams.Add(request.NewErrParamRequired("VirtualGatewayName"))
}
if s.VirtualGatewayName != nil && len(*s.VirtualGatewayName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("VirtualGatewayName", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetMeshName sets the MeshName field's value.
func (s *DescribeVirtualGatewayInput) SetMeshName(v string) *DescribeVirtualGatewayInput {
s.MeshName = &v
return s
}
// SetMeshOwner sets the MeshOwner field's value.
func (s *DescribeVirtualGatewayInput) SetMeshOwner(v string) *DescribeVirtualGatewayInput {
s.MeshOwner = &v
return s
}
// SetVirtualGatewayName sets the VirtualGatewayName field's value.
func (s *DescribeVirtualGatewayInput) SetVirtualGatewayName(v string) *DescribeVirtualGatewayInput {
s.VirtualGatewayName = &v
return s
}
type DescribeVirtualGatewayOutput struct {
_ struct{} `type:"structure" payload:"VirtualGateway"`
// The full description of your virtual gateway.
//
// VirtualGateway is a required field
VirtualGateway *VirtualGatewayData `locationName:"virtualGateway" type:"structure" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DescribeVirtualGatewayOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DescribeVirtualGatewayOutput) GoString() string {
return s.String()
}
// SetVirtualGateway sets the VirtualGateway field's value.
func (s *DescribeVirtualGatewayOutput) SetVirtualGateway(v *VirtualGatewayData) *DescribeVirtualGatewayOutput {
s.VirtualGateway = v
return s
}
type DescribeVirtualNodeInput struct {
_ struct{} `type:"structure"`
// The name of the service mesh that the virtual node resides in.
//
// MeshName is a required field
MeshName *string `location:"uri" locationName:"meshName" min:"1" type:"string" required:"true"`
// The AWS IAM account ID of the service mesh owner. If the account ID is not
// your own, then it's the ID of the account that shared the mesh with your
// account. For more information about mesh sharing, see Working with shared
// meshes (https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html).
MeshOwner *string `location:"querystring" locationName:"meshOwner" min:"12" type:"string"`
// The name of the virtual node to describe.
//
// VirtualNodeName is a required field
VirtualNodeName *string `location:"uri" locationName:"virtualNodeName" min:"1" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DescribeVirtualNodeInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DescribeVirtualNodeInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *DescribeVirtualNodeInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "DescribeVirtualNodeInput"}
if s.MeshName == nil {
invalidParams.Add(request.NewErrParamRequired("MeshName"))
}
if s.MeshName != nil && len(*s.MeshName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("MeshName", 1))
}
if s.MeshOwner != nil && len(*s.MeshOwner) < 12 {
invalidParams.Add(request.NewErrParamMinLen("MeshOwner", 12))
}
if s.VirtualNodeName == nil {
invalidParams.Add(request.NewErrParamRequired("VirtualNodeName"))
}
if s.VirtualNodeName != nil && len(*s.VirtualNodeName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("VirtualNodeName", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetMeshName sets the MeshName field's value.
func (s *DescribeVirtualNodeInput) SetMeshName(v string) *DescribeVirtualNodeInput {
s.MeshName = &v
return s
}
// SetMeshOwner sets the MeshOwner field's value.
func (s *DescribeVirtualNodeInput) SetMeshOwner(v string) *DescribeVirtualNodeInput {
s.MeshOwner = &v
return s
}
// SetVirtualNodeName sets the VirtualNodeName field's value.
func (s *DescribeVirtualNodeInput) SetVirtualNodeName(v string) *DescribeVirtualNodeInput {
s.VirtualNodeName = &v
return s
}
type DescribeVirtualNodeOutput struct {
_ struct{} `type:"structure" payload:"VirtualNode"`
// The full description of your virtual node.
//
// VirtualNode is a required field
VirtualNode *VirtualNodeData `locationName:"virtualNode" type:"structure" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DescribeVirtualNodeOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DescribeVirtualNodeOutput) GoString() string {
return s.String()
}
// SetVirtualNode sets the VirtualNode field's value.
func (s *DescribeVirtualNodeOutput) SetVirtualNode(v *VirtualNodeData) *DescribeVirtualNodeOutput {
s.VirtualNode = v
return s
}
type DescribeVirtualRouterInput struct {
_ struct{} `type:"structure"`
// The name of the service mesh that the virtual router resides in.
//
// MeshName is a required field
MeshName *string `location:"uri" locationName:"meshName" min:"1" type:"string" required:"true"`
// The AWS IAM account ID of the service mesh owner. If the account ID is not
// your own, then it's the ID of the account that shared the mesh with your
// account. For more information about mesh sharing, see Working with shared
// meshes (https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html).
MeshOwner *string `location:"querystring" locationName:"meshOwner" min:"12" type:"string"`
// The name of the virtual router to describe.
//
// VirtualRouterName is a required field
VirtualRouterName *string `location:"uri" locationName:"virtualRouterName" min:"1" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DescribeVirtualRouterInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DescribeVirtualRouterInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *DescribeVirtualRouterInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "DescribeVirtualRouterInput"}
if s.MeshName == nil {
invalidParams.Add(request.NewErrParamRequired("MeshName"))
}
if s.MeshName != nil && len(*s.MeshName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("MeshName", 1))
}
if s.MeshOwner != nil && len(*s.MeshOwner) < 12 {
invalidParams.Add(request.NewErrParamMinLen("MeshOwner", 12))
}
if s.VirtualRouterName == nil {
invalidParams.Add(request.NewErrParamRequired("VirtualRouterName"))
}
if s.VirtualRouterName != nil && len(*s.VirtualRouterName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("VirtualRouterName", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetMeshName sets the MeshName field's value.
func (s *DescribeVirtualRouterInput) SetMeshName(v string) *DescribeVirtualRouterInput {
s.MeshName = &v
return s
}
// SetMeshOwner sets the MeshOwner field's value.
func (s *DescribeVirtualRouterInput) SetMeshOwner(v string) *DescribeVirtualRouterInput {
s.MeshOwner = &v
return s
}
// SetVirtualRouterName sets the VirtualRouterName field's value.
func (s *DescribeVirtualRouterInput) SetVirtualRouterName(v string) *DescribeVirtualRouterInput {
s.VirtualRouterName = &v
return s
}
type DescribeVirtualRouterOutput struct {
_ struct{} `type:"structure" payload:"VirtualRouter"`
// The full description of your virtual router.
//
// VirtualRouter is a required field
VirtualRouter *VirtualRouterData `locationName:"virtualRouter" type:"structure" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DescribeVirtualRouterOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DescribeVirtualRouterOutput) GoString() string {
return s.String()
}
// SetVirtualRouter sets the VirtualRouter field's value.
func (s *DescribeVirtualRouterOutput) SetVirtualRouter(v *VirtualRouterData) *DescribeVirtualRouterOutput {
s.VirtualRouter = v
return s
}
type DescribeVirtualServiceInput struct {
_ struct{} `type:"structure"`
// The name of the service mesh that the virtual service resides in.
//
// MeshName is a required field
MeshName *string `location:"uri" locationName:"meshName" min:"1" type:"string" required:"true"`
// The AWS IAM account ID of the service mesh owner. If the account ID is not
// your own, then it's the ID of the account that shared the mesh with your
// account. For more information about mesh sharing, see Working with shared
// meshes (https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html).
MeshOwner *string `location:"querystring" locationName:"meshOwner" min:"12" type:"string"`
// The name of the virtual service to describe.
//
// VirtualServiceName is a required field
VirtualServiceName *string `location:"uri" locationName:"virtualServiceName" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DescribeVirtualServiceInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DescribeVirtualServiceInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *DescribeVirtualServiceInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "DescribeVirtualServiceInput"}
if s.MeshName == nil {
invalidParams.Add(request.NewErrParamRequired("MeshName"))
}
if s.MeshName != nil && len(*s.MeshName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("MeshName", 1))
}
if s.MeshOwner != nil && len(*s.MeshOwner) < 12 {
invalidParams.Add(request.NewErrParamMinLen("MeshOwner", 12))
}
if s.VirtualServiceName == nil {
invalidParams.Add(request.NewErrParamRequired("VirtualServiceName"))
}
if s.VirtualServiceName != nil && len(*s.VirtualServiceName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("VirtualServiceName", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetMeshName sets the MeshName field's value.
func (s *DescribeVirtualServiceInput) SetMeshName(v string) *DescribeVirtualServiceInput {
s.MeshName = &v
return s
}
// SetMeshOwner sets the MeshOwner field's value.
func (s *DescribeVirtualServiceInput) SetMeshOwner(v string) *DescribeVirtualServiceInput {
s.MeshOwner = &v
return s
}
// SetVirtualServiceName sets the VirtualServiceName field's value.
func (s *DescribeVirtualServiceInput) SetVirtualServiceName(v string) *DescribeVirtualServiceInput {
s.VirtualServiceName = &v
return s
}
type DescribeVirtualServiceOutput struct {
_ struct{} `type:"structure" payload:"VirtualService"`
// The full description of your virtual service.
//
// VirtualService is a required field
VirtualService *VirtualServiceData `locationName:"virtualService" type:"structure" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DescribeVirtualServiceOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DescribeVirtualServiceOutput) GoString() string {
return s.String()
}
// SetVirtualService sets the VirtualService field's value.
func (s *DescribeVirtualServiceOutput) SetVirtualService(v *VirtualServiceData) *DescribeVirtualServiceOutput {
s.VirtualService = v
return s
}
// An object that represents the DNS service discovery information for your
// virtual node.
type DnsServiceDiscovery struct {
_ struct{} `type:"structure"`
// Specifies the DNS service discovery hostname for the virtual node.
//
// Hostname is a required field
Hostname *string `locationName:"hostname" type:"string" required:"true"`
// Specifies the DNS response type for the virtual node.
ResponseType *string `locationName:"responseType" type:"string" enum:"DnsResponseType"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DnsServiceDiscovery) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DnsServiceDiscovery) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *DnsServiceDiscovery) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "DnsServiceDiscovery"}
if s.Hostname == nil {
invalidParams.Add(request.NewErrParamRequired("Hostname"))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetHostname sets the Hostname field's value.
func (s *DnsServiceDiscovery) SetHostname(v string) *DnsServiceDiscovery {
s.Hostname = &v
return s
}
// SetResponseType sets the ResponseType field's value.
func (s *DnsServiceDiscovery) SetResponseType(v string) *DnsServiceDiscovery {
s.ResponseType = &v
return s
}
// An object that represents a duration of time.
type Duration struct {
_ struct{} `type:"structure"`
// A unit of time.
Unit *string `locationName:"unit" type:"string" enum:"DurationUnit"`
// A number of time units.
Value *int64 `locationName:"value" type:"long"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s Duration) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s Duration) GoString() string {
return s.String()
}
// SetUnit sets the Unit field's value.
func (s *Duration) SetUnit(v string) *Duration {
s.Unit = &v
return s
}
// SetValue sets the Value field's value.
func (s *Duration) SetValue(v int64) *Duration {
s.Value = &v
return s
}
// An object that represents the egress filter rules for a service mesh.
type EgressFilter struct {
_ struct{} `type:"structure"`
// The egress filter type. By default, the type is DROP_ALL, which allows egress
// only from virtual nodes to other defined resources in the service mesh (and
// any traffic to *.amazonaws.com for Amazon Web Services API calls). You can
// set the egress filter type to ALLOW_ALL to allow egress to any endpoint inside
// or outside of the service mesh.
//
// Type is a required field
Type *string `locationName:"type" type:"string" required:"true" enum:"EgressFilterType"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s EgressFilter) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s EgressFilter) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *EgressFilter) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "EgressFilter"}
if s.Type == nil {
invalidParams.Add(request.NewErrParamRequired("Type"))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetType sets the Type field's value.
func (s *EgressFilter) SetType(v string) *EgressFilter {
s.Type = &v
return s
}
// An object that represents an access log file.
type FileAccessLog struct {
_ struct{} `type:"structure"`
// The file path to write access logs to. You can use /dev/stdout to send access
// logs to standard out and configure your Envoy container to use a log driver,
// such as awslogs, to export the access logs to a log storage service such
// as Amazon CloudWatch Logs. You can also specify a path in the Envoy container's
// file system to write the files to disk.
//
// The Envoy process must have write permissions to the path that you specify
// here. Otherwise, Envoy fails to bootstrap properly.
//
// Path is a required field
Path *string `locationName:"path" min:"1" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s FileAccessLog) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s FileAccessLog) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *FileAccessLog) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "FileAccessLog"}
if s.Path == nil {
invalidParams.Add(request.NewErrParamRequired("Path"))
}
if s.Path != nil && len(*s.Path) < 1 {
invalidParams.Add(request.NewErrParamMinLen("Path", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetPath sets the Path field's value.
func (s *FileAccessLog) SetPath(v string) *FileAccessLog {
s.Path = &v
return s
}
// You don't have permissions to perform this action.
type ForbiddenException struct {
_ struct{} `type:"structure"`
RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"`
Message_ *string `locationName:"message" type:"string"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ForbiddenException) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ForbiddenException) GoString() string {
return s.String()
}
func newErrorForbiddenException(v protocol.ResponseMetadata) error {
return &ForbiddenException{
RespMetadata: v,
}
}
// Code returns the exception type name.
func (s *ForbiddenException) Code() string {
return "ForbiddenException"
}
// Message returns the exception's message.
func (s *ForbiddenException) Message() string {
if s.Message_ != nil {
return *s.Message_
}
return ""
}
// OrigErr always returns nil, satisfies awserr.Error interface.
func (s *ForbiddenException) OrigErr() error {
return nil
}
func (s *ForbiddenException) Error() string {
return fmt.Sprintf("%s: %s", s.Code(), s.Message())
}
// Status code returns the HTTP status code for the request's response error.
func (s *ForbiddenException) StatusCode() int {
return s.RespMetadata.StatusCode
}
// RequestID returns the service's response RequestID for request.
func (s *ForbiddenException) RequestID() string {
return s.RespMetadata.RequestID
}
// An object that represents a gateway route returned by a describe operation.
type GatewayRouteData struct {
_ struct{} `type:"structure"`
// The name of the gateway route.
//
// GatewayRouteName is a required field
GatewayRouteName *string `locationName:"gatewayRouteName" min:"1" type:"string" required:"true"`
// The name of the service mesh that the resource resides in.
//
// MeshName is a required field
MeshName *string `locationName:"meshName" min:"1" type:"string" required:"true"`
// An object that represents metadata for a resource.
//
// Metadata is a required field
Metadata *ResourceMetadata `locationName:"metadata" type:"structure" required:"true"`
// The specifications of the gateway route.
//
// Spec is a required field
Spec *GatewayRouteSpec `locationName:"spec" type:"structure" required:"true"`
// The status of the gateway route.
//
// Status is a required field
Status *GatewayRouteStatus `locationName:"status" type:"structure" required:"true"`
// The virtual gateway that the gateway route is associated with.
//
// VirtualGatewayName is a required field
VirtualGatewayName *string `locationName:"virtualGatewayName" min:"1" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GatewayRouteData) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GatewayRouteData) GoString() string {
return s.String()
}
// SetGatewayRouteName sets the GatewayRouteName field's value.
func (s *GatewayRouteData) SetGatewayRouteName(v string) *GatewayRouteData {
s.GatewayRouteName = &v
return s
}
// SetMeshName sets the MeshName field's value.
func (s *GatewayRouteData) SetMeshName(v string) *GatewayRouteData {
s.MeshName = &v
return s
}
// SetMetadata sets the Metadata field's value.
func (s *GatewayRouteData) SetMetadata(v *ResourceMetadata) *GatewayRouteData {
s.Metadata = v
return s
}
// SetSpec sets the Spec field's value.
func (s *GatewayRouteData) SetSpec(v *GatewayRouteSpec) *GatewayRouteData {
s.Spec = v
return s
}
// SetStatus sets the Status field's value.
func (s *GatewayRouteData) SetStatus(v *GatewayRouteStatus) *GatewayRouteData {
s.Status = v
return s
}
// SetVirtualGatewayName sets the VirtualGatewayName field's value.
func (s *GatewayRouteData) SetVirtualGatewayName(v string) *GatewayRouteData {
s.VirtualGatewayName = &v
return s
}
// An object representing the gateway route host name to match.
type GatewayRouteHostnameMatch struct {
_ struct{} `type:"structure"`
// The exact host name to match on.
Exact *string `locationName:"exact" min:"1" type:"string"`
// The specified ending characters of the host name to match on.
Suffix *string `locationName:"suffix" min:"1" type:"string"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GatewayRouteHostnameMatch) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GatewayRouteHostnameMatch) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *GatewayRouteHostnameMatch) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "GatewayRouteHostnameMatch"}
if s.Exact != nil && len(*s.Exact) < 1 {
invalidParams.Add(request.NewErrParamMinLen("Exact", 1))
}
if s.Suffix != nil && len(*s.Suffix) < 1 {
invalidParams.Add(request.NewErrParamMinLen("Suffix", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetExact sets the Exact field's value.
func (s *GatewayRouteHostnameMatch) SetExact(v string) *GatewayRouteHostnameMatch {
s.Exact = &v
return s
}
// SetSuffix sets the Suffix field's value.
func (s *GatewayRouteHostnameMatch) SetSuffix(v string) *GatewayRouteHostnameMatch {
s.Suffix = &v
return s
}
// An object representing the gateway route host name to rewrite.
type GatewayRouteHostnameRewrite struct {
_ struct{} `type:"structure"`
// The default target host name to write to.
DefaultTargetHostname *string `locationName:"defaultTargetHostname" type:"string" enum:"DefaultGatewayRouteRewrite"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GatewayRouteHostnameRewrite) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GatewayRouteHostnameRewrite) GoString() string {
return s.String()
}
// SetDefaultTargetHostname sets the DefaultTargetHostname field's value.
func (s *GatewayRouteHostnameRewrite) SetDefaultTargetHostname(v string) *GatewayRouteHostnameRewrite {
s.DefaultTargetHostname = &v
return s
}
// An object that represents a gateway route returned by a list operation.
type GatewayRouteRef struct {
_ struct{} `type:"structure"`
// The full Amazon Resource Name (ARN) for the gateway route.
//
// Arn is a required field
Arn *string `locationName:"arn" type:"string" required:"true"`
// The Unix epoch timestamp in seconds for when the resource was created.
//
// CreatedAt is a required field
CreatedAt *time.Time `locationName:"createdAt" type:"timestamp" required:"true"`
// The name of the gateway route.
//
// GatewayRouteName is a required field
GatewayRouteName *string `locationName:"gatewayRouteName" min:"1" type:"string" required:"true"`
// The Unix epoch timestamp in seconds for when the resource was last updated.
//
// LastUpdatedAt is a required field
LastUpdatedAt *time.Time `locationName:"lastUpdatedAt" type:"timestamp" required:"true"`
// The name of the service mesh that the resource resides in.
//
// MeshName is a required field
MeshName *string `locationName:"meshName" min:"1" type:"string" required:"true"`
// The AWS IAM account ID of the service mesh owner. If the account ID is not
// your own, then it's the ID of the account that shared the mesh with your
// account. For more information about mesh sharing, see Working with shared
// meshes (https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html).
//
// MeshOwner is a required field
MeshOwner *string `locationName:"meshOwner" min:"12" type:"string" required:"true"`
// The AWS IAM account ID of the resource owner. If the account ID is not your
// own, then it's the ID of the mesh owner or of another account that the mesh
// is shared with. For more information about mesh sharing, see Working with
// shared meshes (https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html).
//
// ResourceOwner is a required field
ResourceOwner *string `locationName:"resourceOwner" min:"12" type:"string" required:"true"`
// The version of the resource. Resources are created at version 1, and this
// version is incremented each time that they're updated.
//
// Version is a required field
Version *int64 `locationName:"version" type:"long" required:"true"`
// The virtual gateway that the gateway route is associated with.
//
// VirtualGatewayName is a required field
VirtualGatewayName *string `locationName:"virtualGatewayName" min:"1" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GatewayRouteRef) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GatewayRouteRef) GoString() string {
return s.String()
}
// SetArn sets the Arn field's value.
func (s *GatewayRouteRef) SetArn(v string) *GatewayRouteRef {
s.Arn = &v
return s
}
// SetCreatedAt sets the CreatedAt field's value.
func (s *GatewayRouteRef) SetCreatedAt(v time.Time) *GatewayRouteRef {
s.CreatedAt = &v
return s
}
// SetGatewayRouteName sets the GatewayRouteName field's value.
func (s *GatewayRouteRef) SetGatewayRouteName(v string) *GatewayRouteRef {
s.GatewayRouteName = &v
return s
}
// SetLastUpdatedAt sets the LastUpdatedAt field's value.
func (s *GatewayRouteRef) SetLastUpdatedAt(v time.Time) *GatewayRouteRef {
s.LastUpdatedAt = &v
return s
}
// SetMeshName sets the MeshName field's value.
func (s *GatewayRouteRef) SetMeshName(v string) *GatewayRouteRef {
s.MeshName = &v
return s
}
// SetMeshOwner sets the MeshOwner field's value.
func (s *GatewayRouteRef) SetMeshOwner(v string) *GatewayRouteRef {
s.MeshOwner = &v
return s
}
// SetResourceOwner sets the ResourceOwner field's value.
func (s *GatewayRouteRef) SetResourceOwner(v string) *GatewayRouteRef {
s.ResourceOwner = &v
return s
}
// SetVersion sets the Version field's value.
func (s *GatewayRouteRef) SetVersion(v int64) *GatewayRouteRef {
s.Version = &v
return s
}
// SetVirtualGatewayName sets the VirtualGatewayName field's value.
func (s *GatewayRouteRef) SetVirtualGatewayName(v string) *GatewayRouteRef {
s.VirtualGatewayName = &v
return s
}
// An object that represents a gateway route specification. Specify one gateway
// route type.
type GatewayRouteSpec struct {
_ struct{} `type:"structure"`
// An object that represents the specification of a gRPC gateway route.
GrpcRoute *GrpcGatewayRoute `locationName:"grpcRoute" type:"structure"`
// An object that represents the specification of an HTTP/2 gateway route.
Http2Route *HttpGatewayRoute `locationName:"http2Route" type:"structure"`
// An object that represents the specification of an HTTP gateway route.
HttpRoute *HttpGatewayRoute `locationName:"httpRoute" type:"structure"`
// The ordering of the gateway routes spec.
Priority *int64 `locationName:"priority" type:"integer"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GatewayRouteSpec) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GatewayRouteSpec) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *GatewayRouteSpec) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "GatewayRouteSpec"}
if s.GrpcRoute != nil {
if err := s.GrpcRoute.Validate(); err != nil {
invalidParams.AddNested("GrpcRoute", err.(request.ErrInvalidParams))
}
}
if s.Http2Route != nil {
if err := s.Http2Route.Validate(); err != nil {
invalidParams.AddNested("Http2Route", err.(request.ErrInvalidParams))
}
}
if s.HttpRoute != nil {
if err := s.HttpRoute.Validate(); err != nil {
invalidParams.AddNested("HttpRoute", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetGrpcRoute sets the GrpcRoute field's value.
func (s *GatewayRouteSpec) SetGrpcRoute(v *GrpcGatewayRoute) *GatewayRouteSpec {
s.GrpcRoute = v
return s
}
// SetHttp2Route sets the Http2Route field's value.
func (s *GatewayRouteSpec) SetHttp2Route(v *HttpGatewayRoute) *GatewayRouteSpec {
s.Http2Route = v
return s
}
// SetHttpRoute sets the HttpRoute field's value.
func (s *GatewayRouteSpec) SetHttpRoute(v *HttpGatewayRoute) *GatewayRouteSpec {
s.HttpRoute = v
return s
}
// SetPriority sets the Priority field's value.
func (s *GatewayRouteSpec) SetPriority(v int64) *GatewayRouteSpec {
s.Priority = &v
return s
}
// An object that represents the current status of a gateway route.
type GatewayRouteStatus struct {
_ struct{} `type:"structure"`
// The current status for the gateway route.
//
// Status is a required field
Status *string `locationName:"status" type:"string" required:"true" enum:"GatewayRouteStatusCode"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GatewayRouteStatus) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GatewayRouteStatus) GoString() string {
return s.String()
}
// SetStatus sets the Status field's value.
func (s *GatewayRouteStatus) SetStatus(v string) *GatewayRouteStatus {
s.Status = &v
return s
}
// An object that represents a gateway route target.
type GatewayRouteTarget struct {
_ struct{} `type:"structure"`
// An object that represents a virtual service gateway route target.
//
// VirtualService is a required field
VirtualService *GatewayRouteVirtualService `locationName:"virtualService" type:"structure" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GatewayRouteTarget) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GatewayRouteTarget) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *GatewayRouteTarget) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "GatewayRouteTarget"}
if s.VirtualService == nil {
invalidParams.Add(request.NewErrParamRequired("VirtualService"))
}
if s.VirtualService != nil {
if err := s.VirtualService.Validate(); err != nil {
invalidParams.AddNested("VirtualService", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetVirtualService sets the VirtualService field's value.
func (s *GatewayRouteTarget) SetVirtualService(v *GatewayRouteVirtualService) *GatewayRouteTarget {
s.VirtualService = v
return s
}
// An object that represents the virtual service that traffic is routed to.
type GatewayRouteVirtualService struct {
_ struct{} `type:"structure"`
// The name of the virtual service that traffic is routed to.
//
// VirtualServiceName is a required field
VirtualServiceName *string `locationName:"virtualServiceName" min:"1" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GatewayRouteVirtualService) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GatewayRouteVirtualService) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *GatewayRouteVirtualService) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "GatewayRouteVirtualService"}
if s.VirtualServiceName == nil {
invalidParams.Add(request.NewErrParamRequired("VirtualServiceName"))
}
if s.VirtualServiceName != nil && len(*s.VirtualServiceName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("VirtualServiceName", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetVirtualServiceName sets the VirtualServiceName field's value.
func (s *GatewayRouteVirtualService) SetVirtualServiceName(v string) *GatewayRouteVirtualService {
s.VirtualServiceName = &v
return s
}
// An object that represents a gRPC gateway route.
type GrpcGatewayRoute struct {
_ struct{} `type:"structure"`
// An object that represents the action to take if a match is determined.
//
// Action is a required field
Action *GrpcGatewayRouteAction `locationName:"action" type:"structure" required:"true"`
// An object that represents the criteria for determining a request match.
//
// Match is a required field
Match *GrpcGatewayRouteMatch `locationName:"match" type:"structure" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GrpcGatewayRoute) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GrpcGatewayRoute) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *GrpcGatewayRoute) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "GrpcGatewayRoute"}
if s.Action == nil {
invalidParams.Add(request.NewErrParamRequired("Action"))
}
if s.Match == nil {
invalidParams.Add(request.NewErrParamRequired("Match"))
}
if s.Action != nil {
if err := s.Action.Validate(); err != nil {
invalidParams.AddNested("Action", err.(request.ErrInvalidParams))
}
}
if s.Match != nil {
if err := s.Match.Validate(); err != nil {
invalidParams.AddNested("Match", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetAction sets the Action field's value.
func (s *GrpcGatewayRoute) SetAction(v *GrpcGatewayRouteAction) *GrpcGatewayRoute {
s.Action = v
return s
}
// SetMatch sets the Match field's value.
func (s *GrpcGatewayRoute) SetMatch(v *GrpcGatewayRouteMatch) *GrpcGatewayRoute {
s.Match = v
return s
}
// An object that represents the action to take if a match is determined.
type GrpcGatewayRouteAction struct {
_ struct{} `type:"structure"`
// The gateway route action to rewrite.
Rewrite *GrpcGatewayRouteRewrite `locationName:"rewrite" type:"structure"`
// An object that represents the target that traffic is routed to when a request
// matches the gateway route.
//
// Target is a required field
Target *GatewayRouteTarget `locationName:"target" type:"structure" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GrpcGatewayRouteAction) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GrpcGatewayRouteAction) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *GrpcGatewayRouteAction) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "GrpcGatewayRouteAction"}
if s.Target == nil {
invalidParams.Add(request.NewErrParamRequired("Target"))
}
if s.Target != nil {
if err := s.Target.Validate(); err != nil {
invalidParams.AddNested("Target", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetRewrite sets the Rewrite field's value.
func (s *GrpcGatewayRouteAction) SetRewrite(v *GrpcGatewayRouteRewrite) *GrpcGatewayRouteAction {
s.Rewrite = v
return s
}
// SetTarget sets the Target field's value.
func (s *GrpcGatewayRouteAction) SetTarget(v *GatewayRouteTarget) *GrpcGatewayRouteAction {
s.Target = v
return s
}
// An object that represents the criteria for determining a request match.
type GrpcGatewayRouteMatch struct {
_ struct{} `type:"structure"`
// The gateway route host name to be matched on.
Hostname *GatewayRouteHostnameMatch `locationName:"hostname" type:"structure"`
// The gateway route metadata to be matched on.
Metadata []*GrpcGatewayRouteMetadata `locationName:"metadata" min:"1" type:"list"`
// The fully qualified domain name for the service to match from the request.
ServiceName *string `locationName:"serviceName" type:"string"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GrpcGatewayRouteMatch) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GrpcGatewayRouteMatch) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *GrpcGatewayRouteMatch) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "GrpcGatewayRouteMatch"}
if s.Metadata != nil && len(s.Metadata) < 1 {
invalidParams.Add(request.NewErrParamMinLen("Metadata", 1))
}
if s.Hostname != nil {
if err := s.Hostname.Validate(); err != nil {
invalidParams.AddNested("Hostname", err.(request.ErrInvalidParams))
}
}
if s.Metadata != nil {
for i, v := range s.Metadata {
if v == nil {
continue
}
if err := v.Validate(); err != nil {
invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Metadata", i), err.(request.ErrInvalidParams))
}
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetHostname sets the Hostname field's value.
func (s *GrpcGatewayRouteMatch) SetHostname(v *GatewayRouteHostnameMatch) *GrpcGatewayRouteMatch {
s.Hostname = v
return s
}
// SetMetadata sets the Metadata field's value.
func (s *GrpcGatewayRouteMatch) SetMetadata(v []*GrpcGatewayRouteMetadata) *GrpcGatewayRouteMatch {
s.Metadata = v
return s
}
// SetServiceName sets the ServiceName field's value.
func (s *GrpcGatewayRouteMatch) SetServiceName(v string) *GrpcGatewayRouteMatch {
s.ServiceName = &v
return s
}
// An object representing the metadata of the gateway route.
type GrpcGatewayRouteMetadata struct {
_ struct{} `type:"structure"`
// Specify True to match anything except the match criteria. The default value
// is False.
Invert *bool `locationName:"invert" type:"boolean"`
// The criteria for determining a metadata match.
Match *GrpcMetadataMatchMethod `locationName:"match" type:"structure"`
// A name for the gateway route metadata.
//
// Name is a required field
Name *string `locationName:"name" min:"1" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GrpcGatewayRouteMetadata) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GrpcGatewayRouteMetadata) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *GrpcGatewayRouteMetadata) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "GrpcGatewayRouteMetadata"}
if s.Name == nil {
invalidParams.Add(request.NewErrParamRequired("Name"))
}
if s.Name != nil && len(*s.Name) < 1 {
invalidParams.Add(request.NewErrParamMinLen("Name", 1))
}
if s.Match != nil {
if err := s.Match.Validate(); err != nil {
invalidParams.AddNested("Match", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetInvert sets the Invert field's value.
func (s *GrpcGatewayRouteMetadata) SetInvert(v bool) *GrpcGatewayRouteMetadata {
s.Invert = &v
return s
}
// SetMatch sets the Match field's value.
func (s *GrpcGatewayRouteMetadata) SetMatch(v *GrpcMetadataMatchMethod) *GrpcGatewayRouteMetadata {
s.Match = v
return s
}
// SetName sets the Name field's value.
func (s *GrpcGatewayRouteMetadata) SetName(v string) *GrpcGatewayRouteMetadata {
s.Name = &v
return s
}
// An object that represents the gateway route to rewrite.
type GrpcGatewayRouteRewrite struct {
_ struct{} `type:"structure"`
// The host name of the gateway route to rewrite.
Hostname *GatewayRouteHostnameRewrite `locationName:"hostname" type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GrpcGatewayRouteRewrite) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GrpcGatewayRouteRewrite) GoString() string {
return s.String()
}
// SetHostname sets the Hostname field's value.
func (s *GrpcGatewayRouteRewrite) SetHostname(v *GatewayRouteHostnameRewrite) *GrpcGatewayRouteRewrite {
s.Hostname = v
return s
}
// An object representing the method header to be matched.
type GrpcMetadataMatchMethod struct {
_ struct{} `type:"structure"`
// The exact method header to be matched on.
Exact *string `locationName:"exact" min:"1" type:"string"`
// The specified beginning characters of the method header to be matched on.
Prefix *string `locationName:"prefix" min:"1" type:"string"`
// An object that represents the range of values to match on. The first character
// of the range is included in the range, though the last character is not.
// For example, if the range specified were 1-100, only values 1-99 would be
// matched.
Range *MatchRange `locationName:"range" type:"structure"`
// The regex used to match the method header.
Regex *string `locationName:"regex" min:"1" type:"string"`
// The specified ending characters of the method header to match on.
Suffix *string `locationName:"suffix" min:"1" type:"string"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GrpcMetadataMatchMethod) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GrpcMetadataMatchMethod) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *GrpcMetadataMatchMethod) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "GrpcMetadataMatchMethod"}
if s.Exact != nil && len(*s.Exact) < 1 {
invalidParams.Add(request.NewErrParamMinLen("Exact", 1))
}
if s.Prefix != nil && len(*s.Prefix) < 1 {
invalidParams.Add(request.NewErrParamMinLen("Prefix", 1))
}
if s.Regex != nil && len(*s.Regex) < 1 {
invalidParams.Add(request.NewErrParamMinLen("Regex", 1))
}
if s.Suffix != nil && len(*s.Suffix) < 1 {
invalidParams.Add(request.NewErrParamMinLen("Suffix", 1))
}
if s.Range != nil {
if err := s.Range.Validate(); err != nil {
invalidParams.AddNested("Range", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetExact sets the Exact field's value.
func (s *GrpcMetadataMatchMethod) SetExact(v string) *GrpcMetadataMatchMethod {
s.Exact = &v
return s
}
// SetPrefix sets the Prefix field's value.
func (s *GrpcMetadataMatchMethod) SetPrefix(v string) *GrpcMetadataMatchMethod {
s.Prefix = &v
return s
}
// SetRange sets the Range field's value.
func (s *GrpcMetadataMatchMethod) SetRange(v *MatchRange) *GrpcMetadataMatchMethod {
s.Range = v
return s
}
// SetRegex sets the Regex field's value.
func (s *GrpcMetadataMatchMethod) SetRegex(v string) *GrpcMetadataMatchMethod {
s.Regex = &v
return s
}
// SetSuffix sets the Suffix field's value.
func (s *GrpcMetadataMatchMethod) SetSuffix(v string) *GrpcMetadataMatchMethod {
s.Suffix = &v
return s
}
// An object that represents a retry policy. Specify at least one value for
// at least one of the types of RetryEvents, a value for maxRetries, and a value
// for perRetryTimeout. Both server-error and gateway-error under httpRetryEvents
// include the Envoy reset policy. For more information on the reset policy,
// see the Envoy documentation (https://www.envoyproxy.io/docs/envoy/latest/configuration/http/http_filters/router_filter#x-envoy-retry-on).
type GrpcRetryPolicy struct {
_ struct{} `type:"structure"`
// Specify at least one of the valid values.
GrpcRetryEvents []*string `locationName:"grpcRetryEvents" min:"1" type:"list"`
// Specify at least one of the following values.
//
// * server-error – HTTP status codes 500, 501, 502, 503, 504, 505, 506,
// 507, 508, 510, and 511
//
// * gateway-error – HTTP status codes 502, 503, and 504
//
// * client-error – HTTP status code 409
//
// * stream-error – Retry on refused stream
HttpRetryEvents []*string `locationName:"httpRetryEvents" min:"1" type:"list"`
// The maximum number of retry attempts.
//
// MaxRetries is a required field
MaxRetries *int64 `locationName:"maxRetries" type:"long" required:"true"`
// The timeout for each retry attempt.
//
// PerRetryTimeout is a required field
PerRetryTimeout *Duration `locationName:"perRetryTimeout" type:"structure" required:"true"`
// Specify a valid value. The event occurs before any processing of a request
// has started and is encountered when the upstream is temporarily or permanently
// unavailable.
TcpRetryEvents []*string `locationName:"tcpRetryEvents" min:"1" type:"list"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GrpcRetryPolicy) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GrpcRetryPolicy) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *GrpcRetryPolicy) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "GrpcRetryPolicy"}
if s.GrpcRetryEvents != nil && len(s.GrpcRetryEvents) < 1 {
invalidParams.Add(request.NewErrParamMinLen("GrpcRetryEvents", 1))
}
if s.HttpRetryEvents != nil && len(s.HttpRetryEvents) < 1 {
invalidParams.Add(request.NewErrParamMinLen("HttpRetryEvents", 1))
}
if s.MaxRetries == nil {
invalidParams.Add(request.NewErrParamRequired("MaxRetries"))
}
if s.PerRetryTimeout == nil {
invalidParams.Add(request.NewErrParamRequired("PerRetryTimeout"))
}
if s.TcpRetryEvents != nil && len(s.TcpRetryEvents) < 1 {
invalidParams.Add(request.NewErrParamMinLen("TcpRetryEvents", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetGrpcRetryEvents sets the GrpcRetryEvents field's value.
func (s *GrpcRetryPolicy) SetGrpcRetryEvents(v []*string) *GrpcRetryPolicy {
s.GrpcRetryEvents = v
return s
}
// SetHttpRetryEvents sets the HttpRetryEvents field's value.
func (s *GrpcRetryPolicy) SetHttpRetryEvents(v []*string) *GrpcRetryPolicy {
s.HttpRetryEvents = v
return s
}
// SetMaxRetries sets the MaxRetries field's value.
func (s *GrpcRetryPolicy) SetMaxRetries(v int64) *GrpcRetryPolicy {
s.MaxRetries = &v
return s
}
// SetPerRetryTimeout sets the PerRetryTimeout field's value.
func (s *GrpcRetryPolicy) SetPerRetryTimeout(v *Duration) *GrpcRetryPolicy {
s.PerRetryTimeout = v
return s
}
// SetTcpRetryEvents sets the TcpRetryEvents field's value.
func (s *GrpcRetryPolicy) SetTcpRetryEvents(v []*string) *GrpcRetryPolicy {
s.TcpRetryEvents = v
return s
}
// An object that represents a gRPC route type.
type GrpcRoute struct {
_ struct{} `type:"structure"`
// An object that represents the action to take if a match is determined.
//
// Action is a required field
Action *GrpcRouteAction `locationName:"action" type:"structure" required:"true"`
// An object that represents the criteria for determining a request match.
//
// Match is a required field
Match *GrpcRouteMatch `locationName:"match" type:"structure" required:"true"`
// An object that represents a retry policy.
RetryPolicy *GrpcRetryPolicy `locationName:"retryPolicy" type:"structure"`
// An object that represents types of timeouts.
Timeout *GrpcTimeout `locationName:"timeout" type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GrpcRoute) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GrpcRoute) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *GrpcRoute) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "GrpcRoute"}
if s.Action == nil {
invalidParams.Add(request.NewErrParamRequired("Action"))
}
if s.Match == nil {
invalidParams.Add(request.NewErrParamRequired("Match"))
}
if s.Action != nil {
if err := s.Action.Validate(); err != nil {
invalidParams.AddNested("Action", err.(request.ErrInvalidParams))
}
}
if s.Match != nil {
if err := s.Match.Validate(); err != nil {
invalidParams.AddNested("Match", err.(request.ErrInvalidParams))
}
}
if s.RetryPolicy != nil {
if err := s.RetryPolicy.Validate(); err != nil {
invalidParams.AddNested("RetryPolicy", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetAction sets the Action field's value.
func (s *GrpcRoute) SetAction(v *GrpcRouteAction) *GrpcRoute {
s.Action = v
return s
}
// SetMatch sets the Match field's value.
func (s *GrpcRoute) SetMatch(v *GrpcRouteMatch) *GrpcRoute {
s.Match = v
return s
}
// SetRetryPolicy sets the RetryPolicy field's value.
func (s *GrpcRoute) SetRetryPolicy(v *GrpcRetryPolicy) *GrpcRoute {
s.RetryPolicy = v
return s
}
// SetTimeout sets the Timeout field's value.
func (s *GrpcRoute) SetTimeout(v *GrpcTimeout) *GrpcRoute {
s.Timeout = v
return s
}
// An object that represents the action to take if a match is determined.
type GrpcRouteAction struct {
_ struct{} `type:"structure"`
// An object that represents the targets that traffic is routed to when a request
// matches the route.
//
// WeightedTargets is a required field
WeightedTargets []*WeightedTarget `locationName:"weightedTargets" min:"1" type:"list" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GrpcRouteAction) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GrpcRouteAction) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *GrpcRouteAction) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "GrpcRouteAction"}
if s.WeightedTargets == nil {
invalidParams.Add(request.NewErrParamRequired("WeightedTargets"))
}
if s.WeightedTargets != nil && len(s.WeightedTargets) < 1 {
invalidParams.Add(request.NewErrParamMinLen("WeightedTargets", 1))
}
if s.WeightedTargets != nil {
for i, v := range s.WeightedTargets {
if v == nil {
continue
}
if err := v.Validate(); err != nil {
invalidParams.AddNested(fmt.Sprintf("%s[%v]", "WeightedTargets", i), err.(request.ErrInvalidParams))
}
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetWeightedTargets sets the WeightedTargets field's value.
func (s *GrpcRouteAction) SetWeightedTargets(v []*WeightedTarget) *GrpcRouteAction {
s.WeightedTargets = v
return s
}
// An object that represents the criteria for determining a request match.
type GrpcRouteMatch struct {
_ struct{} `type:"structure"`
// An object that represents the data to match from the request.
Metadata []*GrpcRouteMetadata `locationName:"metadata" min:"1" type:"list"`
// The method name to match from the request. If you specify a name, you must
// also specify a serviceName.
MethodName *string `locationName:"methodName" min:"1" type:"string"`
// The fully qualified domain name for the service to match from the request.
ServiceName *string `locationName:"serviceName" type:"string"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GrpcRouteMatch) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GrpcRouteMatch) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *GrpcRouteMatch) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "GrpcRouteMatch"}
if s.Metadata != nil && len(s.Metadata) < 1 {
invalidParams.Add(request.NewErrParamMinLen("Metadata", 1))
}
if s.MethodName != nil && len(*s.MethodName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("MethodName", 1))
}
if s.Metadata != nil {
for i, v := range s.Metadata {
if v == nil {
continue
}
if err := v.Validate(); err != nil {
invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Metadata", i), err.(request.ErrInvalidParams))
}
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetMetadata sets the Metadata field's value.
func (s *GrpcRouteMatch) SetMetadata(v []*GrpcRouteMetadata) *GrpcRouteMatch {
s.Metadata = v
return s
}
// SetMethodName sets the MethodName field's value.
func (s *GrpcRouteMatch) SetMethodName(v string) *GrpcRouteMatch {
s.MethodName = &v
return s
}
// SetServiceName sets the ServiceName field's value.
func (s *GrpcRouteMatch) SetServiceName(v string) *GrpcRouteMatch {
s.ServiceName = &v
return s
}
// An object that represents the match metadata for the route.
type GrpcRouteMetadata struct {
_ struct{} `type:"structure"`
// Specify True to match anything except the match criteria. The default value
// is False.
Invert *bool `locationName:"invert" type:"boolean"`
// An object that represents the data to match from the request.
Match *GrpcRouteMetadataMatchMethod `locationName:"match" type:"structure"`
// The name of the route.
//
// Name is a required field
Name *string `locationName:"name" min:"1" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GrpcRouteMetadata) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GrpcRouteMetadata) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *GrpcRouteMetadata) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "GrpcRouteMetadata"}
if s.Name == nil {
invalidParams.Add(request.NewErrParamRequired("Name"))
}
if s.Name != nil && len(*s.Name) < 1 {
invalidParams.Add(request.NewErrParamMinLen("Name", 1))
}
if s.Match != nil {
if err := s.Match.Validate(); err != nil {
invalidParams.AddNested("Match", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetInvert sets the Invert field's value.
func (s *GrpcRouteMetadata) SetInvert(v bool) *GrpcRouteMetadata {
s.Invert = &v
return s
}
// SetMatch sets the Match field's value.
func (s *GrpcRouteMetadata) SetMatch(v *GrpcRouteMetadataMatchMethod) *GrpcRouteMetadata {
s.Match = v
return s
}
// SetName sets the Name field's value.
func (s *GrpcRouteMetadata) SetName(v string) *GrpcRouteMetadata {
s.Name = &v
return s
}
// An object that represents the match method. Specify one of the match values.
type GrpcRouteMetadataMatchMethod struct {
_ struct{} `type:"structure"`
// The value sent by the client must match the specified value exactly.
Exact *string `locationName:"exact" min:"1" type:"string"`
// The value sent by the client must begin with the specified characters.
Prefix *string `locationName:"prefix" min:"1" type:"string"`
// An object that represents the range of values to match on.
Range *MatchRange `locationName:"range" type:"structure"`
// The value sent by the client must include the specified characters.
Regex *string `locationName:"regex" min:"1" type:"string"`
// The value sent by the client must end with the specified characters.
Suffix *string `locationName:"suffix" min:"1" type:"string"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GrpcRouteMetadataMatchMethod) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GrpcRouteMetadataMatchMethod) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *GrpcRouteMetadataMatchMethod) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "GrpcRouteMetadataMatchMethod"}
if s.Exact != nil && len(*s.Exact) < 1 {
invalidParams.Add(request.NewErrParamMinLen("Exact", 1))
}
if s.Prefix != nil && len(*s.Prefix) < 1 {
invalidParams.Add(request.NewErrParamMinLen("Prefix", 1))
}
if s.Regex != nil && len(*s.Regex) < 1 {
invalidParams.Add(request.NewErrParamMinLen("Regex", 1))
}
if s.Suffix != nil && len(*s.Suffix) < 1 {
invalidParams.Add(request.NewErrParamMinLen("Suffix", 1))
}
if s.Range != nil {
if err := s.Range.Validate(); err != nil {
invalidParams.AddNested("Range", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetExact sets the Exact field's value.
func (s *GrpcRouteMetadataMatchMethod) SetExact(v string) *GrpcRouteMetadataMatchMethod {
s.Exact = &v
return s
}
// SetPrefix sets the Prefix field's value.
func (s *GrpcRouteMetadataMatchMethod) SetPrefix(v string) *GrpcRouteMetadataMatchMethod {
s.Prefix = &v
return s
}
// SetRange sets the Range field's value.
func (s *GrpcRouteMetadataMatchMethod) SetRange(v *MatchRange) *GrpcRouteMetadataMatchMethod {
s.Range = v
return s
}
// SetRegex sets the Regex field's value.
func (s *GrpcRouteMetadataMatchMethod) SetRegex(v string) *GrpcRouteMetadataMatchMethod {
s.Regex = &v
return s
}
// SetSuffix sets the Suffix field's value.
func (s *GrpcRouteMetadataMatchMethod) SetSuffix(v string) *GrpcRouteMetadataMatchMethod {
s.Suffix = &v
return s
}
// An object that represents types of timeouts.
type GrpcTimeout struct {
_ struct{} `type:"structure"`
// An object that represents an idle timeout. An idle timeout bounds the amount
// of time that a connection may be idle. The default value is none.
Idle *Duration `locationName:"idle" type:"structure"`
// An object that represents a per request timeout. The default value is 15
// seconds. If you set a higher timeout, then make sure that the higher value
// is set for each App Mesh resource in a conversation. For example, if a virtual
// node backend uses a virtual router provider to route to another virtual node,
// then the timeout should be greater than 15 seconds for the source and destination
// virtual node and the route.
PerRequest *Duration `locationName:"perRequest" type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GrpcTimeout) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GrpcTimeout) GoString() string {
return s.String()
}
// SetIdle sets the Idle field's value.
func (s *GrpcTimeout) SetIdle(v *Duration) *GrpcTimeout {
s.Idle = v
return s
}
// SetPerRequest sets the PerRequest field's value.
func (s *GrpcTimeout) SetPerRequest(v *Duration) *GrpcTimeout {
s.PerRequest = v
return s
}
// An object that represents the method and value to match with the header value
// sent in a request. Specify one match method.
type HeaderMatchMethod struct {
_ struct{} `type:"structure"`
// The value sent by the client must match the specified value exactly.
Exact *string `locationName:"exact" min:"1" type:"string"`
// The value sent by the client must begin with the specified characters.
Prefix *string `locationName:"prefix" min:"1" type:"string"`
// An object that represents the range of values to match on.
Range *MatchRange `locationName:"range" type:"structure"`
// The value sent by the client must include the specified characters.
Regex *string `locationName:"regex" min:"1" type:"string"`
// The value sent by the client must end with the specified characters.
Suffix *string `locationName:"suffix" min:"1" type:"string"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s HeaderMatchMethod) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s HeaderMatchMethod) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *HeaderMatchMethod) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "HeaderMatchMethod"}
if s.Exact != nil && len(*s.Exact) < 1 {
invalidParams.Add(request.NewErrParamMinLen("Exact", 1))
}
if s.Prefix != nil && len(*s.Prefix) < 1 {
invalidParams.Add(request.NewErrParamMinLen("Prefix", 1))
}
if s.Regex != nil && len(*s.Regex) < 1 {
invalidParams.Add(request.NewErrParamMinLen("Regex", 1))
}
if s.Suffix != nil && len(*s.Suffix) < 1 {
invalidParams.Add(request.NewErrParamMinLen("Suffix", 1))
}
if s.Range != nil {
if err := s.Range.Validate(); err != nil {
invalidParams.AddNested("Range", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetExact sets the Exact field's value.
func (s *HeaderMatchMethod) SetExact(v string) *HeaderMatchMethod {
s.Exact = &v
return s
}
// SetPrefix sets the Prefix field's value.
func (s *HeaderMatchMethod) SetPrefix(v string) *HeaderMatchMethod {
s.Prefix = &v
return s
}
// SetRange sets the Range field's value.
func (s *HeaderMatchMethod) SetRange(v *MatchRange) *HeaderMatchMethod {
s.Range = v
return s
}
// SetRegex sets the Regex field's value.
func (s *HeaderMatchMethod) SetRegex(v string) *HeaderMatchMethod {
s.Regex = &v
return s
}
// SetSuffix sets the Suffix field's value.
func (s *HeaderMatchMethod) SetSuffix(v string) *HeaderMatchMethod {
s.Suffix = &v
return s
}
// An object that represents the health check policy for a virtual node's listener.
type HealthCheckPolicy struct {
_ struct{} `type:"structure"`
// The number of consecutive successful health checks that must occur before
// declaring listener healthy.
//
// HealthyThreshold is a required field
HealthyThreshold *int64 `locationName:"healthyThreshold" min:"2" type:"integer" required:"true"`
// The time period in milliseconds between each health check execution.
//
// IntervalMillis is a required field
IntervalMillis *int64 `locationName:"intervalMillis" min:"5000" type:"long" required:"true"`
// The destination path for the health check request. This value is only used
// if the specified protocol is HTTP or HTTP/2. For any other protocol, this
// value is ignored.
Path *string `locationName:"path" type:"string"`
// The destination port for the health check request. This port must match the
// port defined in the PortMapping for the listener.
Port *int64 `locationName:"port" min:"1" type:"integer"`
// The protocol for the health check request. If you specify grpc, then your
// service must conform to the GRPC Health Checking Protocol (https://github.com/grpc/grpc/blob/master/doc/health-checking.md).
//
// Protocol is a required field
Protocol *string `locationName:"protocol" type:"string" required:"true" enum:"PortProtocol"`
// The amount of time to wait when receiving a response from the health check,
// in milliseconds.
//
// TimeoutMillis is a required field
TimeoutMillis *int64 `locationName:"timeoutMillis" min:"2000" type:"long" required:"true"`
// The number of consecutive failed health checks that must occur before declaring
// a virtual node unhealthy.
//
// UnhealthyThreshold is a required field
UnhealthyThreshold *int64 `locationName:"unhealthyThreshold" min:"2" type:"integer" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s HealthCheckPolicy) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s HealthCheckPolicy) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *HealthCheckPolicy) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "HealthCheckPolicy"}
if s.HealthyThreshold == nil {
invalidParams.Add(request.NewErrParamRequired("HealthyThreshold"))
}
if s.HealthyThreshold != nil && *s.HealthyThreshold < 2 {
invalidParams.Add(request.NewErrParamMinValue("HealthyThreshold", 2))
}
if s.IntervalMillis == nil {
invalidParams.Add(request.NewErrParamRequired("IntervalMillis"))
}
if s.IntervalMillis != nil && *s.IntervalMillis < 5000 {
invalidParams.Add(request.NewErrParamMinValue("IntervalMillis", 5000))
}
if s.Port != nil && *s.Port < 1 {
invalidParams.Add(request.NewErrParamMinValue("Port", 1))
}
if s.Protocol == nil {
invalidParams.Add(request.NewErrParamRequired("Protocol"))
}
if s.TimeoutMillis == nil {
invalidParams.Add(request.NewErrParamRequired("TimeoutMillis"))
}
if s.TimeoutMillis != nil && *s.TimeoutMillis < 2000 {
invalidParams.Add(request.NewErrParamMinValue("TimeoutMillis", 2000))
}
if s.UnhealthyThreshold == nil {
invalidParams.Add(request.NewErrParamRequired("UnhealthyThreshold"))
}
if s.UnhealthyThreshold != nil && *s.UnhealthyThreshold < 2 {
invalidParams.Add(request.NewErrParamMinValue("UnhealthyThreshold", 2))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetHealthyThreshold sets the HealthyThreshold field's value.
func (s *HealthCheckPolicy) SetHealthyThreshold(v int64) *HealthCheckPolicy {
s.HealthyThreshold = &v
return s
}
// SetIntervalMillis sets the IntervalMillis field's value.
func (s *HealthCheckPolicy) SetIntervalMillis(v int64) *HealthCheckPolicy {
s.IntervalMillis = &v
return s
}
// SetPath sets the Path field's value.
func (s *HealthCheckPolicy) SetPath(v string) *HealthCheckPolicy {
s.Path = &v
return s
}
// SetPort sets the Port field's value.
func (s *HealthCheckPolicy) SetPort(v int64) *HealthCheckPolicy {
s.Port = &v
return s
}
// SetProtocol sets the Protocol field's value.
func (s *HealthCheckPolicy) SetProtocol(v string) *HealthCheckPolicy {
s.Protocol = &v
return s
}
// SetTimeoutMillis sets the TimeoutMillis field's value.
func (s *HealthCheckPolicy) SetTimeoutMillis(v int64) *HealthCheckPolicy {
s.TimeoutMillis = &v
return s
}
// SetUnhealthyThreshold sets the UnhealthyThreshold field's value.
func (s *HealthCheckPolicy) SetUnhealthyThreshold(v int64) *HealthCheckPolicy {
s.UnhealthyThreshold = &v
return s
}
// An object that represents an HTTP gateway route.
type HttpGatewayRoute struct {
_ struct{} `type:"structure"`
// An object that represents the action to take if a match is determined.
//
// Action is a required field
Action *HttpGatewayRouteAction `locationName:"action" type:"structure" required:"true"`
// An object that represents the criteria for determining a request match.
//
// Match is a required field
Match *HttpGatewayRouteMatch `locationName:"match" type:"structure" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s HttpGatewayRoute) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s HttpGatewayRoute) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *HttpGatewayRoute) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "HttpGatewayRoute"}
if s.Action == nil {
invalidParams.Add(request.NewErrParamRequired("Action"))
}
if s.Match == nil {
invalidParams.Add(request.NewErrParamRequired("Match"))
}
if s.Action != nil {
if err := s.Action.Validate(); err != nil {
invalidParams.AddNested("Action", err.(request.ErrInvalidParams))
}
}
if s.Match != nil {
if err := s.Match.Validate(); err != nil {
invalidParams.AddNested("Match", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetAction sets the Action field's value.
func (s *HttpGatewayRoute) SetAction(v *HttpGatewayRouteAction) *HttpGatewayRoute {
s.Action = v
return s
}
// SetMatch sets the Match field's value.
func (s *HttpGatewayRoute) SetMatch(v *HttpGatewayRouteMatch) *HttpGatewayRoute {
s.Match = v
return s
}
// An object that represents the action to take if a match is determined.
type HttpGatewayRouteAction struct {
_ struct{} `type:"structure"`
// The gateway route action to rewrite.
Rewrite *HttpGatewayRouteRewrite `locationName:"rewrite" type:"structure"`
// An object that represents the target that traffic is routed to when a request
// matches the gateway route.
//
// Target is a required field
Target *GatewayRouteTarget `locationName:"target" type:"structure" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s HttpGatewayRouteAction) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s HttpGatewayRouteAction) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *HttpGatewayRouteAction) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "HttpGatewayRouteAction"}
if s.Target == nil {
invalidParams.Add(request.NewErrParamRequired("Target"))
}
if s.Rewrite != nil {
if err := s.Rewrite.Validate(); err != nil {
invalidParams.AddNested("Rewrite", err.(request.ErrInvalidParams))
}
}
if s.Target != nil {
if err := s.Target.Validate(); err != nil {
invalidParams.AddNested("Target", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetRewrite sets the Rewrite field's value.
func (s *HttpGatewayRouteAction) SetRewrite(v *HttpGatewayRouteRewrite) *HttpGatewayRouteAction {
s.Rewrite = v
return s
}
// SetTarget sets the Target field's value.
func (s *HttpGatewayRouteAction) SetTarget(v *GatewayRouteTarget) *HttpGatewayRouteAction {
s.Target = v
return s
}
// An object that represents the HTTP header in the gateway route.
type HttpGatewayRouteHeader struct {
_ struct{} `type:"structure"`
// Specify True to match anything except the match criteria. The default value
// is False.
Invert *bool `locationName:"invert" type:"boolean"`
// An object that represents the method and value to match with the header value
// sent in a request. Specify one match method.
Match *HeaderMatchMethod `locationName:"match" type:"structure"`
// A name for the HTTP header in the gateway route that will be matched on.
//
// Name is a required field
Name *string `locationName:"name" min:"1" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s HttpGatewayRouteHeader) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s HttpGatewayRouteHeader) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *HttpGatewayRouteHeader) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "HttpGatewayRouteHeader"}
if s.Name == nil {
invalidParams.Add(request.NewErrParamRequired("Name"))
}
if s.Name != nil && len(*s.Name) < 1 {
invalidParams.Add(request.NewErrParamMinLen("Name", 1))
}
if s.Match != nil {
if err := s.Match.Validate(); err != nil {
invalidParams.AddNested("Match", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetInvert sets the Invert field's value.
func (s *HttpGatewayRouteHeader) SetInvert(v bool) *HttpGatewayRouteHeader {
s.Invert = &v
return s
}
// SetMatch sets the Match field's value.
func (s *HttpGatewayRouteHeader) SetMatch(v *HeaderMatchMethod) *HttpGatewayRouteHeader {
s.Match = v
return s
}
// SetName sets the Name field's value.
func (s *HttpGatewayRouteHeader) SetName(v string) *HttpGatewayRouteHeader {
s.Name = &v
return s
}
// An object that represents the criteria for determining a request match.
type HttpGatewayRouteMatch struct {
_ struct{} `type:"structure"`
// The client request headers to match on.
Headers []*HttpGatewayRouteHeader `locationName:"headers" min:"1" type:"list"`
// The host name to match on.
Hostname *GatewayRouteHostnameMatch `locationName:"hostname" type:"structure"`
// The method to match on.
Method *string `locationName:"method" type:"string" enum:"HttpMethod"`
// The path to match on.
Path *HttpPathMatch `locationName:"path" type:"structure"`
// Specifies the path to match requests with. This parameter must always start
// with /, which by itself matches all requests to the virtual service name.
// You can also match for path-based routing of requests. For example, if your
// virtual service name is my-service.local and you want the route to match
// requests to my-service.local/metrics, your prefix should be /metrics.
Prefix *string `locationName:"prefix" type:"string"`
// The query parameter to match on.
QueryParameters []*HttpQueryParameter `locationName:"queryParameters" min:"1" type:"list"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s HttpGatewayRouteMatch) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s HttpGatewayRouteMatch) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *HttpGatewayRouteMatch) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "HttpGatewayRouteMatch"}
if s.Headers != nil && len(s.Headers) < 1 {
invalidParams.Add(request.NewErrParamMinLen("Headers", 1))
}
if s.QueryParameters != nil && len(s.QueryParameters) < 1 {
invalidParams.Add(request.NewErrParamMinLen("QueryParameters", 1))
}
if s.Headers != nil {
for i, v := range s.Headers {
if v == nil {
continue
}
if err := v.Validate(); err != nil {
invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Headers", i), err.(request.ErrInvalidParams))
}
}
}
if s.Hostname != nil {
if err := s.Hostname.Validate(); err != nil {
invalidParams.AddNested("Hostname", err.(request.ErrInvalidParams))
}
}
if s.Path != nil {
if err := s.Path.Validate(); err != nil {
invalidParams.AddNested("Path", err.(request.ErrInvalidParams))
}
}
if s.QueryParameters != nil {
for i, v := range s.QueryParameters {
if v == nil {
continue
}
if err := v.Validate(); err != nil {
invalidParams.AddNested(fmt.Sprintf("%s[%v]", "QueryParameters", i), err.(request.ErrInvalidParams))
}
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetHeaders sets the Headers field's value.
func (s *HttpGatewayRouteMatch) SetHeaders(v []*HttpGatewayRouteHeader) *HttpGatewayRouteMatch {
s.Headers = v
return s
}
// SetHostname sets the Hostname field's value.
func (s *HttpGatewayRouteMatch) SetHostname(v *GatewayRouteHostnameMatch) *HttpGatewayRouteMatch {
s.Hostname = v
return s
}
// SetMethod sets the Method field's value.
func (s *HttpGatewayRouteMatch) SetMethod(v string) *HttpGatewayRouteMatch {
s.Method = &v
return s
}
// SetPath sets the Path field's value.
func (s *HttpGatewayRouteMatch) SetPath(v *HttpPathMatch) *HttpGatewayRouteMatch {
s.Path = v
return s
}
// SetPrefix sets the Prefix field's value.
func (s *HttpGatewayRouteMatch) SetPrefix(v string) *HttpGatewayRouteMatch {
s.Prefix = &v
return s
}
// SetQueryParameters sets the QueryParameters field's value.
func (s *HttpGatewayRouteMatch) SetQueryParameters(v []*HttpQueryParameter) *HttpGatewayRouteMatch {
s.QueryParameters = v
return s
}
// An object that represents the path to rewrite.
type HttpGatewayRoutePathRewrite struct {
_ struct{} `type:"structure"`
// The exact path to rewrite.
Exact *string `locationName:"exact" min:"1" type:"string"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s HttpGatewayRoutePathRewrite) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s HttpGatewayRoutePathRewrite) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *HttpGatewayRoutePathRewrite) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "HttpGatewayRoutePathRewrite"}
if s.Exact != nil && len(*s.Exact) < 1 {
invalidParams.Add(request.NewErrParamMinLen("Exact", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetExact sets the Exact field's value.
func (s *HttpGatewayRoutePathRewrite) SetExact(v string) *HttpGatewayRoutePathRewrite {
s.Exact = &v
return s
}
// An object representing the beginning characters of the route to rewrite.
type HttpGatewayRoutePrefixRewrite struct {
_ struct{} `type:"structure"`
// The default prefix used to replace the incoming route prefix when rewritten.
DefaultPrefix *string `locationName:"defaultPrefix" type:"string" enum:"DefaultGatewayRouteRewrite"`
// The value used to replace the incoming route prefix when rewritten.
Value *string `locationName:"value" min:"1" type:"string"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s HttpGatewayRoutePrefixRewrite) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s HttpGatewayRoutePrefixRewrite) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *HttpGatewayRoutePrefixRewrite) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "HttpGatewayRoutePrefixRewrite"}
if s.Value != nil && len(*s.Value) < 1 {
invalidParams.Add(request.NewErrParamMinLen("Value", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetDefaultPrefix sets the DefaultPrefix field's value.
func (s *HttpGatewayRoutePrefixRewrite) SetDefaultPrefix(v string) *HttpGatewayRoutePrefixRewrite {
s.DefaultPrefix = &v
return s
}
// SetValue sets the Value field's value.
func (s *HttpGatewayRoutePrefixRewrite) SetValue(v string) *HttpGatewayRoutePrefixRewrite {
s.Value = &v
return s
}
// An object representing the gateway route to rewrite.
type HttpGatewayRouteRewrite struct {
_ struct{} `type:"structure"`
// The host name to rewrite.
Hostname *GatewayRouteHostnameRewrite `locationName:"hostname" type:"structure"`
// The path to rewrite.
Path *HttpGatewayRoutePathRewrite `locationName:"path" type:"structure"`
// The specified beginning characters to rewrite.
Prefix *HttpGatewayRoutePrefixRewrite `locationName:"prefix" type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s HttpGatewayRouteRewrite) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s HttpGatewayRouteRewrite) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *HttpGatewayRouteRewrite) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "HttpGatewayRouteRewrite"}
if s.Path != nil {
if err := s.Path.Validate(); err != nil {
invalidParams.AddNested("Path", err.(request.ErrInvalidParams))
}
}
if s.Prefix != nil {
if err := s.Prefix.Validate(); err != nil {
invalidParams.AddNested("Prefix", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetHostname sets the Hostname field's value.
func (s *HttpGatewayRouteRewrite) SetHostname(v *GatewayRouteHostnameRewrite) *HttpGatewayRouteRewrite {
s.Hostname = v
return s
}
// SetPath sets the Path field's value.
func (s *HttpGatewayRouteRewrite) SetPath(v *HttpGatewayRoutePathRewrite) *HttpGatewayRouteRewrite {
s.Path = v
return s
}
// SetPrefix sets the Prefix field's value.
func (s *HttpGatewayRouteRewrite) SetPrefix(v *HttpGatewayRoutePrefixRewrite) *HttpGatewayRouteRewrite {
s.Prefix = v
return s
}
// An object representing the path to match in the request.
type HttpPathMatch struct {
_ struct{} `type:"structure"`
// The exact path to match on.
Exact *string `locationName:"exact" min:"1" type:"string"`
// The regex used to match the path.
Regex *string `locationName:"regex" min:"1" type:"string"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s HttpPathMatch) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s HttpPathMatch) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *HttpPathMatch) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "HttpPathMatch"}
if s.Exact != nil && len(*s.Exact) < 1 {
invalidParams.Add(request.NewErrParamMinLen("Exact", 1))
}
if s.Regex != nil && len(*s.Regex) < 1 {
invalidParams.Add(request.NewErrParamMinLen("Regex", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetExact sets the Exact field's value.
func (s *HttpPathMatch) SetExact(v string) *HttpPathMatch {
s.Exact = &v
return s
}
// SetRegex sets the Regex field's value.
func (s *HttpPathMatch) SetRegex(v string) *HttpPathMatch {
s.Regex = &v
return s
}
// An object that represents the query parameter in the request.
type HttpQueryParameter struct {
_ struct{} `type:"structure"`
// The query parameter to match on.
Match *QueryParameterMatch `locationName:"match" type:"structure"`
// A name for the query parameter that will be matched on.
//
// Name is a required field
Name *string `locationName:"name" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s HttpQueryParameter) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s HttpQueryParameter) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *HttpQueryParameter) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "HttpQueryParameter"}
if s.Name == nil {
invalidParams.Add(request.NewErrParamRequired("Name"))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetMatch sets the Match field's value.
func (s *HttpQueryParameter) SetMatch(v *QueryParameterMatch) *HttpQueryParameter {
s.Match = v
return s
}
// SetName sets the Name field's value.
func (s *HttpQueryParameter) SetName(v string) *HttpQueryParameter {
s.Name = &v
return s
}
// An object that represents a retry policy. Specify at least one value for
// at least one of the types of RetryEvents, a value for maxRetries, and a value
// for perRetryTimeout. Both server-error and gateway-error under httpRetryEvents
// include the Envoy reset policy. For more information on the reset policy,
// see the Envoy documentation (https://www.envoyproxy.io/docs/envoy/latest/configuration/http/http_filters/router_filter#x-envoy-retry-on).
type HttpRetryPolicy struct {
_ struct{} `type:"structure"`
// Specify at least one of the following values.
//
// * server-error – HTTP status codes 500, 501, 502, 503, 504, 505, 506,
// 507, 508, 510, and 511
//
// * gateway-error – HTTP status codes 502, 503, and 504
//
// * client-error – HTTP status code 409
//
// * stream-error – Retry on refused stream
HttpRetryEvents []*string `locationName:"httpRetryEvents" min:"1" type:"list"`
// The maximum number of retry attempts.
//
// MaxRetries is a required field
MaxRetries *int64 `locationName:"maxRetries" type:"long" required:"true"`
// The timeout for each retry attempt.
//
// PerRetryTimeout is a required field
PerRetryTimeout *Duration `locationName:"perRetryTimeout" type:"structure" required:"true"`
// Specify a valid value. The event occurs before any processing of a request
// has started and is encountered when the upstream is temporarily or permanently
// unavailable.
TcpRetryEvents []*string `locationName:"tcpRetryEvents" min:"1" type:"list"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s HttpRetryPolicy) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s HttpRetryPolicy) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *HttpRetryPolicy) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "HttpRetryPolicy"}
if s.HttpRetryEvents != nil && len(s.HttpRetryEvents) < 1 {
invalidParams.Add(request.NewErrParamMinLen("HttpRetryEvents", 1))
}
if s.MaxRetries == nil {
invalidParams.Add(request.NewErrParamRequired("MaxRetries"))
}
if s.PerRetryTimeout == nil {
invalidParams.Add(request.NewErrParamRequired("PerRetryTimeout"))
}
if s.TcpRetryEvents != nil && len(s.TcpRetryEvents) < 1 {
invalidParams.Add(request.NewErrParamMinLen("TcpRetryEvents", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetHttpRetryEvents sets the HttpRetryEvents field's value.
func (s *HttpRetryPolicy) SetHttpRetryEvents(v []*string) *HttpRetryPolicy {
s.HttpRetryEvents = v
return s
}
// SetMaxRetries sets the MaxRetries field's value.
func (s *HttpRetryPolicy) SetMaxRetries(v int64) *HttpRetryPolicy {
s.MaxRetries = &v
return s
}
// SetPerRetryTimeout sets the PerRetryTimeout field's value.
func (s *HttpRetryPolicy) SetPerRetryTimeout(v *Duration) *HttpRetryPolicy {
s.PerRetryTimeout = v
return s
}
// SetTcpRetryEvents sets the TcpRetryEvents field's value.
func (s *HttpRetryPolicy) SetTcpRetryEvents(v []*string) *HttpRetryPolicy {
s.TcpRetryEvents = v
return s
}
// An object that represents an HTTP or HTTP/2 route type.
type HttpRoute struct {
_ struct{} `type:"structure"`
// An object that represents the action to take if a match is determined.
//
// Action is a required field
Action *HttpRouteAction `locationName:"action" type:"structure" required:"true"`
// An object that represents the criteria for determining a request match.
//
// Match is a required field
Match *HttpRouteMatch `locationName:"match" type:"structure" required:"true"`
// An object that represents a retry policy.
RetryPolicy *HttpRetryPolicy `locationName:"retryPolicy" type:"structure"`
// An object that represents types of timeouts.
Timeout *HttpTimeout `locationName:"timeout" type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s HttpRoute) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s HttpRoute) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *HttpRoute) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "HttpRoute"}
if s.Action == nil {
invalidParams.Add(request.NewErrParamRequired("Action"))
}
if s.Match == nil {
invalidParams.Add(request.NewErrParamRequired("Match"))
}
if s.Action != nil {
if err := s.Action.Validate(); err != nil {
invalidParams.AddNested("Action", err.(request.ErrInvalidParams))
}
}
if s.Match != nil {
if err := s.Match.Validate(); err != nil {
invalidParams.AddNested("Match", err.(request.ErrInvalidParams))
}
}
if s.RetryPolicy != nil {
if err := s.RetryPolicy.Validate(); err != nil {
invalidParams.AddNested("RetryPolicy", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetAction sets the Action field's value.
func (s *HttpRoute) SetAction(v *HttpRouteAction) *HttpRoute {
s.Action = v
return s
}
// SetMatch sets the Match field's value.
func (s *HttpRoute) SetMatch(v *HttpRouteMatch) *HttpRoute {
s.Match = v
return s
}
// SetRetryPolicy sets the RetryPolicy field's value.
func (s *HttpRoute) SetRetryPolicy(v *HttpRetryPolicy) *HttpRoute {
s.RetryPolicy = v
return s
}
// SetTimeout sets the Timeout field's value.
func (s *HttpRoute) SetTimeout(v *HttpTimeout) *HttpRoute {
s.Timeout = v
return s
}
// An object that represents the action to take if a match is determined.
type HttpRouteAction struct {
_ struct{} `type:"structure"`
// An object that represents the targets that traffic is routed to when a request
// matches the route.
//
// WeightedTargets is a required field
WeightedTargets []*WeightedTarget `locationName:"weightedTargets" min:"1" type:"list" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s HttpRouteAction) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s HttpRouteAction) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *HttpRouteAction) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "HttpRouteAction"}
if s.WeightedTargets == nil {
invalidParams.Add(request.NewErrParamRequired("WeightedTargets"))
}
if s.WeightedTargets != nil && len(s.WeightedTargets) < 1 {
invalidParams.Add(request.NewErrParamMinLen("WeightedTargets", 1))
}
if s.WeightedTargets != nil {
for i, v := range s.WeightedTargets {
if v == nil {
continue
}
if err := v.Validate(); err != nil {
invalidParams.AddNested(fmt.Sprintf("%s[%v]", "WeightedTargets", i), err.(request.ErrInvalidParams))
}
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetWeightedTargets sets the WeightedTargets field's value.
func (s *HttpRouteAction) SetWeightedTargets(v []*WeightedTarget) *HttpRouteAction {
s.WeightedTargets = v
return s
}
// An object that represents the HTTP header in the request.
type HttpRouteHeader struct {
_ struct{} `type:"structure"`
// Specify True to match anything except the match criteria. The default value
// is False.
Invert *bool `locationName:"invert" type:"boolean"`
// The HeaderMatchMethod object.
Match *HeaderMatchMethod `locationName:"match" type:"structure"`
// A name for the HTTP header in the client request that will be matched on.
//
// Name is a required field
Name *string `locationName:"name" min:"1" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s HttpRouteHeader) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s HttpRouteHeader) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *HttpRouteHeader) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "HttpRouteHeader"}
if s.Name == nil {
invalidParams.Add(request.NewErrParamRequired("Name"))
}
if s.Name != nil && len(*s.Name) < 1 {
invalidParams.Add(request.NewErrParamMinLen("Name", 1))
}
if s.Match != nil {
if err := s.Match.Validate(); err != nil {
invalidParams.AddNested("Match", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetInvert sets the Invert field's value.
func (s *HttpRouteHeader) SetInvert(v bool) *HttpRouteHeader {
s.Invert = &v
return s
}
// SetMatch sets the Match field's value.
func (s *HttpRouteHeader) SetMatch(v *HeaderMatchMethod) *HttpRouteHeader {
s.Match = v
return s
}
// SetName sets the Name field's value.
func (s *HttpRouteHeader) SetName(v string) *HttpRouteHeader {
s.Name = &v
return s
}
// An object that represents the requirements for a route to match HTTP requests
// for a virtual router.
type HttpRouteMatch struct {
_ struct{} `type:"structure"`
// The client request headers to match on.
Headers []*HttpRouteHeader `locationName:"headers" min:"1" type:"list"`
// The client request method to match on. Specify only one.
Method *string `locationName:"method" type:"string" enum:"HttpMethod"`
// The client request path to match on.
Path *HttpPathMatch `locationName:"path" type:"structure"`
// Specifies the path to match requests with. This parameter must always start
// with /, which by itself matches all requests to the virtual service name.
// You can also match for path-based routing of requests. For example, if your
// virtual service name is my-service.local and you want the route to match
// requests to my-service.local/metrics, your prefix should be /metrics.
Prefix *string `locationName:"prefix" type:"string"`
// The client request query parameters to match on.
QueryParameters []*HttpQueryParameter `locationName:"queryParameters" min:"1" type:"list"`
// The client request scheme to match on. Specify only one. Applicable only
// for HTTP2 routes.
Scheme *string `locationName:"scheme" type:"string" enum:"HttpScheme"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s HttpRouteMatch) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s HttpRouteMatch) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *HttpRouteMatch) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "HttpRouteMatch"}
if s.Headers != nil && len(s.Headers) < 1 {
invalidParams.Add(request.NewErrParamMinLen("Headers", 1))
}
if s.QueryParameters != nil && len(s.QueryParameters) < 1 {
invalidParams.Add(request.NewErrParamMinLen("QueryParameters", 1))
}
if s.Headers != nil {
for i, v := range s.Headers {
if v == nil {
continue
}
if err := v.Validate(); err != nil {
invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Headers", i), err.(request.ErrInvalidParams))
}
}
}
if s.Path != nil {
if err := s.Path.Validate(); err != nil {
invalidParams.AddNested("Path", err.(request.ErrInvalidParams))
}
}
if s.QueryParameters != nil {
for i, v := range s.QueryParameters {
if v == nil {
continue
}
if err := v.Validate(); err != nil {
invalidParams.AddNested(fmt.Sprintf("%s[%v]", "QueryParameters", i), err.(request.ErrInvalidParams))
}
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetHeaders sets the Headers field's value.
func (s *HttpRouteMatch) SetHeaders(v []*HttpRouteHeader) *HttpRouteMatch {
s.Headers = v
return s
}
// SetMethod sets the Method field's value.
func (s *HttpRouteMatch) SetMethod(v string) *HttpRouteMatch {
s.Method = &v
return s
}
// SetPath sets the Path field's value.
func (s *HttpRouteMatch) SetPath(v *HttpPathMatch) *HttpRouteMatch {
s.Path = v
return s
}
// SetPrefix sets the Prefix field's value.
func (s *HttpRouteMatch) SetPrefix(v string) *HttpRouteMatch {
s.Prefix = &v
return s
}
// SetQueryParameters sets the QueryParameters field's value.
func (s *HttpRouteMatch) SetQueryParameters(v []*HttpQueryParameter) *HttpRouteMatch {
s.QueryParameters = v
return s
}
// SetScheme sets the Scheme field's value.
func (s *HttpRouteMatch) SetScheme(v string) *HttpRouteMatch {
s.Scheme = &v
return s
}
// An object that represents types of timeouts.
type HttpTimeout struct {
_ struct{} `type:"structure"`
// An object that represents an idle timeout. An idle timeout bounds the amount
// of time that a connection may be idle. The default value is none.
Idle *Duration `locationName:"idle" type:"structure"`
// An object that represents a per request timeout. The default value is 15
// seconds. If you set a higher timeout, then make sure that the higher value
// is set for each App Mesh resource in a conversation. For example, if a virtual
// node backend uses a virtual router provider to route to another virtual node,
// then the timeout should be greater than 15 seconds for the source and destination
// virtual node and the route.
PerRequest *Duration `locationName:"perRequest" type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s HttpTimeout) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s HttpTimeout) GoString() string {
return s.String()
}
// SetIdle sets the Idle field's value.
func (s *HttpTimeout) SetIdle(v *Duration) *HttpTimeout {
s.Idle = v
return s
}
// SetPerRequest sets the PerRequest field's value.
func (s *HttpTimeout) SetPerRequest(v *Duration) *HttpTimeout {
s.PerRequest = v
return s
}
// The request processing has failed because of an unknown error, exception,
// or failure.
type InternalServerErrorException struct {
_ struct{} `type:"structure"`
RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"`
Message_ *string `locationName:"message" type:"string"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s InternalServerErrorException) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s InternalServerErrorException) GoString() string {
return s.String()
}
func newErrorInternalServerErrorException(v protocol.ResponseMetadata) error {
return &InternalServerErrorException{
RespMetadata: v,
}
}
// Code returns the exception type name.
func (s *InternalServerErrorException) Code() string {
return "InternalServerErrorException"
}
// Message returns the exception's message.
func (s *InternalServerErrorException) Message() string {
if s.Message_ != nil {
return *s.Message_
}
return ""
}
// OrigErr always returns nil, satisfies awserr.Error interface.
func (s *InternalServerErrorException) OrigErr() error {
return nil
}
func (s *InternalServerErrorException) Error() string {
return fmt.Sprintf("%s: %s", s.Code(), s.Message())
}
// Status code returns the HTTP status code for the request's response error.
func (s *InternalServerErrorException) StatusCode() int {
return s.RespMetadata.StatusCode
}
// RequestID returns the service's response RequestID for request.
func (s *InternalServerErrorException) RequestID() string {
return s.RespMetadata.RequestID
}
// You have exceeded a service limit for your account. For more information,
// see Service Limits (https://docs.aws.amazon.com/app-mesh/latest/userguide/service-quotas.html)
// in the AWS App Mesh User Guide.
type LimitExceededException struct {
_ struct{} `type:"structure"`
RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"`
Message_ *string `locationName:"message" type:"string"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s LimitExceededException) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s LimitExceededException) GoString() string {
return s.String()
}
func newErrorLimitExceededException(v protocol.ResponseMetadata) error {
return &LimitExceededException{
RespMetadata: v,
}
}
// Code returns the exception type name.
func (s *LimitExceededException) Code() string {
return "LimitExceededException"
}
// Message returns the exception's message.
func (s *LimitExceededException) Message() string {
if s.Message_ != nil {
return *s.Message_
}
return ""
}
// OrigErr always returns nil, satisfies awserr.Error interface.
func (s *LimitExceededException) OrigErr() error {
return nil
}
func (s *LimitExceededException) Error() string {
return fmt.Sprintf("%s: %s", s.Code(), s.Message())
}
// Status code returns the HTTP status code for the request's response error.
func (s *LimitExceededException) StatusCode() int {
return s.RespMetadata.StatusCode
}
// RequestID returns the service's response RequestID for request.
func (s *LimitExceededException) RequestID() string {
return s.RespMetadata.RequestID
}
type ListGatewayRoutesInput struct {
_ struct{} `type:"structure"`
// The maximum number of results returned by ListGatewayRoutes in paginated
// output. When you use this parameter, ListGatewayRoutes returns only limit
// results in a single page along with a nextToken response element. You can
// see the remaining results of the initial request by sending another ListGatewayRoutes
// request with the returned nextToken value. This value can be between 1 and
// 100. If you don't use this parameter, ListGatewayRoutes returns up to 100
// results and a nextToken value if applicable.
Limit *int64 `location:"querystring" locationName:"limit" min:"1" type:"integer"`
// The name of the service mesh to list gateway routes in.
//
// MeshName is a required field
MeshName *string `location:"uri" locationName:"meshName" min:"1" type:"string" required:"true"`
// The AWS IAM account ID of the service mesh owner. If the account ID is not
// your own, then it's the ID of the account that shared the mesh with your
// account. For more information about mesh sharing, see Working with shared
// meshes (https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html).
MeshOwner *string `location:"querystring" locationName:"meshOwner" min:"12" type:"string"`
// The nextToken value returned from a previous paginated ListGatewayRoutes
// request where limit was used and the results exceeded the value of that parameter.
// Pagination continues from the end of the previous results that returned the
// nextToken value.
NextToken *string `location:"querystring" locationName:"nextToken" type:"string"`
// The name of the virtual gateway to list gateway routes in.
//
// VirtualGatewayName is a required field
VirtualGatewayName *string `location:"uri" locationName:"virtualGatewayName" min:"1" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListGatewayRoutesInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListGatewayRoutesInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *ListGatewayRoutesInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "ListGatewayRoutesInput"}
if s.Limit != nil && *s.Limit < 1 {
invalidParams.Add(request.NewErrParamMinValue("Limit", 1))
}
if s.MeshName == nil {
invalidParams.Add(request.NewErrParamRequired("MeshName"))
}
if s.MeshName != nil && len(*s.MeshName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("MeshName", 1))
}
if s.MeshOwner != nil && len(*s.MeshOwner) < 12 {
invalidParams.Add(request.NewErrParamMinLen("MeshOwner", 12))
}
if s.VirtualGatewayName == nil {
invalidParams.Add(request.NewErrParamRequired("VirtualGatewayName"))
}
if s.VirtualGatewayName != nil && len(*s.VirtualGatewayName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("VirtualGatewayName", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetLimit sets the Limit field's value.
func (s *ListGatewayRoutesInput) SetLimit(v int64) *ListGatewayRoutesInput {
s.Limit = &v
return s
}
// SetMeshName sets the MeshName field's value.
func (s *ListGatewayRoutesInput) SetMeshName(v string) *ListGatewayRoutesInput {
s.MeshName = &v
return s
}
// SetMeshOwner sets the MeshOwner field's value.
func (s *ListGatewayRoutesInput) SetMeshOwner(v string) *ListGatewayRoutesInput {
s.MeshOwner = &v
return s
}
// SetNextToken sets the NextToken field's value.
func (s *ListGatewayRoutesInput) SetNextToken(v string) *ListGatewayRoutesInput {
s.NextToken = &v
return s
}
// SetVirtualGatewayName sets the VirtualGatewayName field's value.
func (s *ListGatewayRoutesInput) SetVirtualGatewayName(v string) *ListGatewayRoutesInput {
s.VirtualGatewayName = &v
return s
}
type ListGatewayRoutesOutput struct {
_ struct{} `type:"structure"`
// The list of existing gateway routes for the specified service mesh and virtual
// gateway.
//
// GatewayRoutes is a required field
GatewayRoutes []*GatewayRouteRef `locationName:"gatewayRoutes" type:"list" required:"true"`
// The nextToken value to include in a future ListGatewayRoutes request. When
// the results of a ListGatewayRoutes request exceed limit, you can use this
// value to retrieve the next page of results. This value is null when there
// are no more results to return.
NextToken *string `locationName:"nextToken" type:"string"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListGatewayRoutesOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListGatewayRoutesOutput) GoString() string {
return s.String()
}
// SetGatewayRoutes sets the GatewayRoutes field's value.
func (s *ListGatewayRoutesOutput) SetGatewayRoutes(v []*GatewayRouteRef) *ListGatewayRoutesOutput {
s.GatewayRoutes = v
return s
}
// SetNextToken sets the NextToken field's value.
func (s *ListGatewayRoutesOutput) SetNextToken(v string) *ListGatewayRoutesOutput {
s.NextToken = &v
return s
}
type ListMeshesInput struct {
_ struct{} `type:"structure"`
// The maximum number of results returned by ListMeshes in paginated output.
// When you use this parameter, ListMeshes returns only limit results in a single
// page along with a nextToken response element. You can see the remaining results
// of the initial request by sending another ListMeshes request with the returned
// nextToken value. This value can be between 1 and 100. If you don't use this
// parameter, ListMeshes returns up to 100 results and a nextToken value if
// applicable.
Limit *int64 `location:"querystring" locationName:"limit" min:"1" type:"integer"`
// The nextToken value returned from a previous paginated ListMeshes request
// where limit was used and the results exceeded the value of that parameter.
// Pagination continues from the end of the previous results that returned the
// nextToken value.
//
// This token should be treated as an opaque identifier that is used only to
// retrieve the next items in a list and not for other programmatic purposes.
NextToken *string `location:"querystring" locationName:"nextToken" type:"string"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListMeshesInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListMeshesInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *ListMeshesInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "ListMeshesInput"}
if s.Limit != nil && *s.Limit < 1 {
invalidParams.Add(request.NewErrParamMinValue("Limit", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetLimit sets the Limit field's value.
func (s *ListMeshesInput) SetLimit(v int64) *ListMeshesInput {
s.Limit = &v
return s
}
// SetNextToken sets the NextToken field's value.
func (s *ListMeshesInput) SetNextToken(v string) *ListMeshesInput {
s.NextToken = &v
return s
}
type ListMeshesOutput struct {
_ struct{} `type:"structure"`
// The list of existing service meshes.
//
// Meshes is a required field
Meshes []*MeshRef `locationName:"meshes" type:"list" required:"true"`
// The nextToken value to include in a future ListMeshes request. When the results
// of a ListMeshes request exceed limit, you can use this value to retrieve
// the next page of results. This value is null when there are no more results
// to return.
NextToken *string `locationName:"nextToken" type:"string"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListMeshesOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListMeshesOutput) GoString() string {
return s.String()
}
// SetMeshes sets the Meshes field's value.
func (s *ListMeshesOutput) SetMeshes(v []*MeshRef) *ListMeshesOutput {
s.Meshes = v
return s
}
// SetNextToken sets the NextToken field's value.
func (s *ListMeshesOutput) SetNextToken(v string) *ListMeshesOutput {
s.NextToken = &v
return s
}
type ListRoutesInput struct {
_ struct{} `type:"structure"`
// The maximum number of results returned by ListRoutes in paginated output.
// When you use this parameter, ListRoutes returns only limit results in a single
// page along with a nextToken response element. You can see the remaining results
// of the initial request by sending another ListRoutes request with the returned
// nextToken value. This value can be between 1 and 100. If you don't use this
// parameter, ListRoutes returns up to 100 results and a nextToken value if
// applicable.
Limit *int64 `location:"querystring" locationName:"limit" min:"1" type:"integer"`
// The name of the service mesh to list routes in.
//
// MeshName is a required field
MeshName *string `location:"uri" locationName:"meshName" min:"1" type:"string" required:"true"`
// The AWS IAM account ID of the service mesh owner. If the account ID is not
// your own, then it's the ID of the account that shared the mesh with your
// account. For more information about mesh sharing, see Working with shared
// meshes (https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html).
MeshOwner *string `location:"querystring" locationName:"meshOwner" min:"12" type:"string"`
// The nextToken value returned from a previous paginated ListRoutes request
// where limit was used and the results exceeded the value of that parameter.
// Pagination continues from the end of the previous results that returned the
// nextToken value.
NextToken *string `location:"querystring" locationName:"nextToken" type:"string"`
// The name of the virtual router to list routes in.
//
// VirtualRouterName is a required field
VirtualRouterName *string `location:"uri" locationName:"virtualRouterName" min:"1" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListRoutesInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListRoutesInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *ListRoutesInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "ListRoutesInput"}
if s.Limit != nil && *s.Limit < 1 {
invalidParams.Add(request.NewErrParamMinValue("Limit", 1))
}
if s.MeshName == nil {
invalidParams.Add(request.NewErrParamRequired("MeshName"))
}
if s.MeshName != nil && len(*s.MeshName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("MeshName", 1))
}
if s.MeshOwner != nil && len(*s.MeshOwner) < 12 {
invalidParams.Add(request.NewErrParamMinLen("MeshOwner", 12))
}
if s.VirtualRouterName == nil {
invalidParams.Add(request.NewErrParamRequired("VirtualRouterName"))
}
if s.VirtualRouterName != nil && len(*s.VirtualRouterName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("VirtualRouterName", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetLimit sets the Limit field's value.
func (s *ListRoutesInput) SetLimit(v int64) *ListRoutesInput {
s.Limit = &v
return s
}
// SetMeshName sets the MeshName field's value.
func (s *ListRoutesInput) SetMeshName(v string) *ListRoutesInput {
s.MeshName = &v
return s
}
// SetMeshOwner sets the MeshOwner field's value.
func (s *ListRoutesInput) SetMeshOwner(v string) *ListRoutesInput {
s.MeshOwner = &v
return s
}
// SetNextToken sets the NextToken field's value.
func (s *ListRoutesInput) SetNextToken(v string) *ListRoutesInput {
s.NextToken = &v
return s
}
// SetVirtualRouterName sets the VirtualRouterName field's value.
func (s *ListRoutesInput) SetVirtualRouterName(v string) *ListRoutesInput {
s.VirtualRouterName = &v
return s
}
type ListRoutesOutput struct {
_ struct{} `type:"structure"`
// The nextToken value to include in a future ListRoutes request. When the results
// of a ListRoutes request exceed limit, you can use this value to retrieve
// the next page of results. This value is null when there are no more results
// to return.
NextToken *string `locationName:"nextToken" type:"string"`
// The list of existing routes for the specified service mesh and virtual router.
//
// Routes is a required field
Routes []*RouteRef `locationName:"routes" type:"list" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListRoutesOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListRoutesOutput) GoString() string {
return s.String()
}
// SetNextToken sets the NextToken field's value.
func (s *ListRoutesOutput) SetNextToken(v string) *ListRoutesOutput {
s.NextToken = &v
return s
}
// SetRoutes sets the Routes field's value.
func (s *ListRoutesOutput) SetRoutes(v []*RouteRef) *ListRoutesOutput {
s.Routes = v
return s
}
type ListTagsForResourceInput struct {
_ struct{} `type:"structure"`
// The maximum number of tag results returned by ListTagsForResource in paginated
// output. When this parameter is used, ListTagsForResource returns only limit
// results in a single page along with a nextToken response element. You can
// see the remaining results of the initial request by sending another ListTagsForResource
// request with the returned nextToken value. This value can be between 1 and
// 100. If you don't use this parameter, ListTagsForResource returns up to 100
// results and a nextToken value if applicable.
Limit *int64 `location:"querystring" locationName:"limit" min:"1" type:"integer"`
// The nextToken value returned from a previous paginated ListTagsForResource
// request where limit was used and the results exceeded the value of that parameter.
// Pagination continues from the end of the previous results that returned the
// nextToken value.
NextToken *string `location:"querystring" locationName:"nextToken" type:"string"`
// The Amazon Resource Name (ARN) that identifies the resource to list the tags
// for.
//
// ResourceArn is a required field
ResourceArn *string `location:"querystring" locationName:"resourceArn" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListTagsForResourceInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListTagsForResourceInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *ListTagsForResourceInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "ListTagsForResourceInput"}
if s.Limit != nil && *s.Limit < 1 {
invalidParams.Add(request.NewErrParamMinValue("Limit", 1))
}
if s.ResourceArn == nil {
invalidParams.Add(request.NewErrParamRequired("ResourceArn"))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetLimit sets the Limit field's value.
func (s *ListTagsForResourceInput) SetLimit(v int64) *ListTagsForResourceInput {
s.Limit = &v
return s
}
// SetNextToken sets the NextToken field's value.
func (s *ListTagsForResourceInput) SetNextToken(v string) *ListTagsForResourceInput {
s.NextToken = &v
return s
}
// SetResourceArn sets the ResourceArn field's value.
func (s *ListTagsForResourceInput) SetResourceArn(v string) *ListTagsForResourceInput {
s.ResourceArn = &v
return s
}
type ListTagsForResourceOutput struct {
_ struct{} `type:"structure"`
// The nextToken value to include in a future ListTagsForResource request. When
// the results of a ListTagsForResource request exceed limit, you can use this
// value to retrieve the next page of results. This value is null when there
// are no more results to return.
NextToken *string `locationName:"nextToken" type:"string"`
// The tags for the resource.
//
// Tags is a required field
Tags []*TagRef `locationName:"tags" type:"list" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListTagsForResourceOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListTagsForResourceOutput) GoString() string {
return s.String()
}
// SetNextToken sets the NextToken field's value.
func (s *ListTagsForResourceOutput) SetNextToken(v string) *ListTagsForResourceOutput {
s.NextToken = &v
return s
}
// SetTags sets the Tags field's value.
func (s *ListTagsForResourceOutput) SetTags(v []*TagRef) *ListTagsForResourceOutput {
s.Tags = v
return s
}
type ListVirtualGatewaysInput struct {
_ struct{} `type:"structure"`
// The maximum number of results returned by ListVirtualGateways in paginated
// output. When you use this parameter, ListVirtualGateways returns only limit
// results in a single page along with a nextToken response element. You can
// see the remaining results of the initial request by sending another ListVirtualGateways
// request with the returned nextToken value. This value can be between 1 and
// 100. If you don't use this parameter, ListVirtualGateways returns up to 100
// results and a nextToken value if applicable.
Limit *int64 `location:"querystring" locationName:"limit" min:"1" type:"integer"`
// The name of the service mesh to list virtual gateways in.
//
// MeshName is a required field
MeshName *string `location:"uri" locationName:"meshName" min:"1" type:"string" required:"true"`
// The AWS IAM account ID of the service mesh owner. If the account ID is not
// your own, then it's the ID of the account that shared the mesh with your
// account. For more information about mesh sharing, see Working with shared
// meshes (https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html).
MeshOwner *string `location:"querystring" locationName:"meshOwner" min:"12" type:"string"`
// The nextToken value returned from a previous paginated ListVirtualGateways
// request where limit was used and the results exceeded the value of that parameter.
// Pagination continues from the end of the previous results that returned the
// nextToken value.
NextToken *string `location:"querystring" locationName:"nextToken" type:"string"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListVirtualGatewaysInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListVirtualGatewaysInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *ListVirtualGatewaysInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "ListVirtualGatewaysInput"}
if s.Limit != nil && *s.Limit < 1 {
invalidParams.Add(request.NewErrParamMinValue("Limit", 1))
}
if s.MeshName == nil {
invalidParams.Add(request.NewErrParamRequired("MeshName"))
}
if s.MeshName != nil && len(*s.MeshName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("MeshName", 1))
}
if s.MeshOwner != nil && len(*s.MeshOwner) < 12 {
invalidParams.Add(request.NewErrParamMinLen("MeshOwner", 12))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetLimit sets the Limit field's value.
func (s *ListVirtualGatewaysInput) SetLimit(v int64) *ListVirtualGatewaysInput {
s.Limit = &v
return s
}
// SetMeshName sets the MeshName field's value.
func (s *ListVirtualGatewaysInput) SetMeshName(v string) *ListVirtualGatewaysInput {
s.MeshName = &v
return s
}
// SetMeshOwner sets the MeshOwner field's value.
func (s *ListVirtualGatewaysInput) SetMeshOwner(v string) *ListVirtualGatewaysInput {
s.MeshOwner = &v
return s
}
// SetNextToken sets the NextToken field's value.
func (s *ListVirtualGatewaysInput) SetNextToken(v string) *ListVirtualGatewaysInput {
s.NextToken = &v
return s
}
type ListVirtualGatewaysOutput struct {
_ struct{} `type:"structure"`
// The nextToken value to include in a future ListVirtualGateways request. When
// the results of a ListVirtualGateways request exceed limit, you can use this
// value to retrieve the next page of results. This value is null when there
// are no more results to return.
NextToken *string `locationName:"nextToken" type:"string"`
// The list of existing virtual gateways for the specified service mesh.
//
// VirtualGateways is a required field
VirtualGateways []*VirtualGatewayRef `locationName:"virtualGateways" type:"list" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListVirtualGatewaysOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListVirtualGatewaysOutput) GoString() string {
return s.String()
}
// SetNextToken sets the NextToken field's value.
func (s *ListVirtualGatewaysOutput) SetNextToken(v string) *ListVirtualGatewaysOutput {
s.NextToken = &v
return s
}
// SetVirtualGateways sets the VirtualGateways field's value.
func (s *ListVirtualGatewaysOutput) SetVirtualGateways(v []*VirtualGatewayRef) *ListVirtualGatewaysOutput {
s.VirtualGateways = v
return s
}
type ListVirtualNodesInput struct {
_ struct{} `type:"structure"`
// The maximum number of results returned by ListVirtualNodes in paginated output.
// When you use this parameter, ListVirtualNodes returns only limit results
// in a single page along with a nextToken response element. You can see the
// remaining results of the initial request by sending another ListVirtualNodes
// request with the returned nextToken value. This value can be between 1 and
// 100. If you don't use this parameter, ListVirtualNodes returns up to 100
// results and a nextToken value if applicable.
Limit *int64 `location:"querystring" locationName:"limit" min:"1" type:"integer"`
// The name of the service mesh to list virtual nodes in.
//
// MeshName is a required field
MeshName *string `location:"uri" locationName:"meshName" min:"1" type:"string" required:"true"`
// The AWS IAM account ID of the service mesh owner. If the account ID is not
// your own, then it's the ID of the account that shared the mesh with your
// account. For more information about mesh sharing, see Working with shared
// meshes (https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html).
MeshOwner *string `location:"querystring" locationName:"meshOwner" min:"12" type:"string"`
// The nextToken value returned from a previous paginated ListVirtualNodes request
// where limit was used and the results exceeded the value of that parameter.
// Pagination continues from the end of the previous results that returned the
// nextToken value.
NextToken *string `location:"querystring" locationName:"nextToken" type:"string"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListVirtualNodesInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListVirtualNodesInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *ListVirtualNodesInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "ListVirtualNodesInput"}
if s.Limit != nil && *s.Limit < 1 {
invalidParams.Add(request.NewErrParamMinValue("Limit", 1))
}
if s.MeshName == nil {
invalidParams.Add(request.NewErrParamRequired("MeshName"))
}
if s.MeshName != nil && len(*s.MeshName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("MeshName", 1))
}
if s.MeshOwner != nil && len(*s.MeshOwner) < 12 {
invalidParams.Add(request.NewErrParamMinLen("MeshOwner", 12))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetLimit sets the Limit field's value.
func (s *ListVirtualNodesInput) SetLimit(v int64) *ListVirtualNodesInput {
s.Limit = &v
return s
}
// SetMeshName sets the MeshName field's value.
func (s *ListVirtualNodesInput) SetMeshName(v string) *ListVirtualNodesInput {
s.MeshName = &v
return s
}
// SetMeshOwner sets the MeshOwner field's value.
func (s *ListVirtualNodesInput) SetMeshOwner(v string) *ListVirtualNodesInput {
s.MeshOwner = &v
return s
}
// SetNextToken sets the NextToken field's value.
func (s *ListVirtualNodesInput) SetNextToken(v string) *ListVirtualNodesInput {
s.NextToken = &v
return s
}
type ListVirtualNodesOutput struct {
_ struct{} `type:"structure"`
// The nextToken value to include in a future ListVirtualNodes request. When
// the results of a ListVirtualNodes request exceed limit, you can use this
// value to retrieve the next page of results. This value is null when there
// are no more results to return.
NextToken *string `locationName:"nextToken" type:"string"`
// The list of existing virtual nodes for the specified service mesh.
//
// VirtualNodes is a required field
VirtualNodes []*VirtualNodeRef `locationName:"virtualNodes" type:"list" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListVirtualNodesOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListVirtualNodesOutput) GoString() string {
return s.String()
}
// SetNextToken sets the NextToken field's value.
func (s *ListVirtualNodesOutput) SetNextToken(v string) *ListVirtualNodesOutput {
s.NextToken = &v
return s
}
// SetVirtualNodes sets the VirtualNodes field's value.
func (s *ListVirtualNodesOutput) SetVirtualNodes(v []*VirtualNodeRef) *ListVirtualNodesOutput {
s.VirtualNodes = v
return s
}
type ListVirtualRoutersInput struct {
_ struct{} `type:"structure"`
// The maximum number of results returned by ListVirtualRouters in paginated
// output. When you use this parameter, ListVirtualRouters returns only limit
// results in a single page along with a nextToken response element. You can
// see the remaining results of the initial request by sending another ListVirtualRouters
// request with the returned nextToken value. This value can be between 1 and
// 100. If you don't use this parameter, ListVirtualRouters returns up to 100
// results and a nextToken value if applicable.
Limit *int64 `location:"querystring" locationName:"limit" min:"1" type:"integer"`
// The name of the service mesh to list virtual routers in.
//
// MeshName is a required field
MeshName *string `location:"uri" locationName:"meshName" min:"1" type:"string" required:"true"`
// The AWS IAM account ID of the service mesh owner. If the account ID is not
// your own, then it's the ID of the account that shared the mesh with your
// account. For more information about mesh sharing, see Working with shared
// meshes (https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html).
MeshOwner *string `location:"querystring" locationName:"meshOwner" min:"12" type:"string"`
// The nextToken value returned from a previous paginated ListVirtualRouters
// request where limit was used and the results exceeded the value of that parameter.
// Pagination continues from the end of the previous results that returned the
// nextToken value.
NextToken *string `location:"querystring" locationName:"nextToken" type:"string"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListVirtualRoutersInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListVirtualRoutersInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *ListVirtualRoutersInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "ListVirtualRoutersInput"}
if s.Limit != nil && *s.Limit < 1 {
invalidParams.Add(request.NewErrParamMinValue("Limit", 1))
}
if s.MeshName == nil {
invalidParams.Add(request.NewErrParamRequired("MeshName"))
}
if s.MeshName != nil && len(*s.MeshName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("MeshName", 1))
}
if s.MeshOwner != nil && len(*s.MeshOwner) < 12 {
invalidParams.Add(request.NewErrParamMinLen("MeshOwner", 12))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetLimit sets the Limit field's value.
func (s *ListVirtualRoutersInput) SetLimit(v int64) *ListVirtualRoutersInput {
s.Limit = &v
return s
}
// SetMeshName sets the MeshName field's value.
func (s *ListVirtualRoutersInput) SetMeshName(v string) *ListVirtualRoutersInput {
s.MeshName = &v
return s
}
// SetMeshOwner sets the MeshOwner field's value.
func (s *ListVirtualRoutersInput) SetMeshOwner(v string) *ListVirtualRoutersInput {
s.MeshOwner = &v
return s
}
// SetNextToken sets the NextToken field's value.
func (s *ListVirtualRoutersInput) SetNextToken(v string) *ListVirtualRoutersInput {
s.NextToken = &v
return s
}
type ListVirtualRoutersOutput struct {
_ struct{} `type:"structure"`
// The nextToken value to include in a future ListVirtualRouters request. When
// the results of a ListVirtualRouters request exceed limit, you can use this
// value to retrieve the next page of results. This value is null when there
// are no more results to return.
NextToken *string `locationName:"nextToken" type:"string"`
// The list of existing virtual routers for the specified service mesh.
//
// VirtualRouters is a required field
VirtualRouters []*VirtualRouterRef `locationName:"virtualRouters" type:"list" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListVirtualRoutersOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListVirtualRoutersOutput) GoString() string {
return s.String()
}
// SetNextToken sets the NextToken field's value.
func (s *ListVirtualRoutersOutput) SetNextToken(v string) *ListVirtualRoutersOutput {
s.NextToken = &v
return s
}
// SetVirtualRouters sets the VirtualRouters field's value.
func (s *ListVirtualRoutersOutput) SetVirtualRouters(v []*VirtualRouterRef) *ListVirtualRoutersOutput {
s.VirtualRouters = v
return s
}
type ListVirtualServicesInput struct {
_ struct{} `type:"structure"`
// The maximum number of results returned by ListVirtualServices in paginated
// output. When you use this parameter, ListVirtualServices returns only limit
// results in a single page along with a nextToken response element. You can
// see the remaining results of the initial request by sending another ListVirtualServices
// request with the returned nextToken value. This value can be between 1 and
// 100. If you don't use this parameter, ListVirtualServices returns up to 100
// results and a nextToken value if applicable.
Limit *int64 `location:"querystring" locationName:"limit" min:"1" type:"integer"`
// The name of the service mesh to list virtual services in.
//
// MeshName is a required field
MeshName *string `location:"uri" locationName:"meshName" min:"1" type:"string" required:"true"`
// The AWS IAM account ID of the service mesh owner. If the account ID is not
// your own, then it's the ID of the account that shared the mesh with your
// account. For more information about mesh sharing, see Working with shared
// meshes (https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html).
MeshOwner *string `location:"querystring" locationName:"meshOwner" min:"12" type:"string"`
// The nextToken value returned from a previous paginated ListVirtualServices
// request where limit was used and the results exceeded the value of that parameter.
// Pagination continues from the end of the previous results that returned the
// nextToken value.
NextToken *string `location:"querystring" locationName:"nextToken" type:"string"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListVirtualServicesInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListVirtualServicesInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *ListVirtualServicesInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "ListVirtualServicesInput"}
if s.Limit != nil && *s.Limit < 1 {
invalidParams.Add(request.NewErrParamMinValue("Limit", 1))
}
if s.MeshName == nil {
invalidParams.Add(request.NewErrParamRequired("MeshName"))
}
if s.MeshName != nil && len(*s.MeshName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("MeshName", 1))
}
if s.MeshOwner != nil && len(*s.MeshOwner) < 12 {
invalidParams.Add(request.NewErrParamMinLen("MeshOwner", 12))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetLimit sets the Limit field's value.
func (s *ListVirtualServicesInput) SetLimit(v int64) *ListVirtualServicesInput {
s.Limit = &v
return s
}
// SetMeshName sets the MeshName field's value.
func (s *ListVirtualServicesInput) SetMeshName(v string) *ListVirtualServicesInput {
s.MeshName = &v
return s
}
// SetMeshOwner sets the MeshOwner field's value.
func (s *ListVirtualServicesInput) SetMeshOwner(v string) *ListVirtualServicesInput {
s.MeshOwner = &v
return s
}
// SetNextToken sets the NextToken field's value.
func (s *ListVirtualServicesInput) SetNextToken(v string) *ListVirtualServicesInput {
s.NextToken = &v
return s
}
type ListVirtualServicesOutput struct {
_ struct{} `type:"structure"`
// The nextToken value to include in a future ListVirtualServices request. When
// the results of a ListVirtualServices request exceed limit, you can use this
// value to retrieve the next page of results. This value is null when there
// are no more results to return.
NextToken *string `locationName:"nextToken" type:"string"`
// The list of existing virtual services for the specified service mesh.
//
// VirtualServices is a required field
VirtualServices []*VirtualServiceRef `locationName:"virtualServices" type:"list" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListVirtualServicesOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListVirtualServicesOutput) GoString() string {
return s.String()
}
// SetNextToken sets the NextToken field's value.
func (s *ListVirtualServicesOutput) SetNextToken(v string) *ListVirtualServicesOutput {
s.NextToken = &v
return s
}
// SetVirtualServices sets the VirtualServices field's value.
func (s *ListVirtualServicesOutput) SetVirtualServices(v []*VirtualServiceRef) *ListVirtualServicesOutput {
s.VirtualServices = v
return s
}
// An object that represents a listener for a virtual node.
type Listener struct {
_ struct{} `type:"structure"`
// The connection pool information for the listener.
ConnectionPool *VirtualNodeConnectionPool `locationName:"connectionPool" type:"structure"`
// The health check information for the listener.
HealthCheck *HealthCheckPolicy `locationName:"healthCheck" type:"structure"`
// The outlier detection information for the listener.
OutlierDetection *OutlierDetection `locationName:"outlierDetection" type:"structure"`
// The port mapping information for the listener.
//
// PortMapping is a required field
PortMapping *PortMapping `locationName:"portMapping" type:"structure" required:"true"`
// An object that represents timeouts for different protocols.
Timeout *ListenerTimeout `locationName:"timeout" type:"structure"`
// A reference to an object that represents the Transport Layer Security (TLS)
// properties for a listener.
Tls *ListenerTls `locationName:"tls" type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s Listener) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s Listener) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *Listener) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "Listener"}
if s.PortMapping == nil {
invalidParams.Add(request.NewErrParamRequired("PortMapping"))
}
if s.ConnectionPool != nil {
if err := s.ConnectionPool.Validate(); err != nil {
invalidParams.AddNested("ConnectionPool", err.(request.ErrInvalidParams))
}
}
if s.HealthCheck != nil {
if err := s.HealthCheck.Validate(); err != nil {
invalidParams.AddNested("HealthCheck", err.(request.ErrInvalidParams))
}
}
if s.OutlierDetection != nil {
if err := s.OutlierDetection.Validate(); err != nil {
invalidParams.AddNested("OutlierDetection", err.(request.ErrInvalidParams))
}
}
if s.PortMapping != nil {
if err := s.PortMapping.Validate(); err != nil {
invalidParams.AddNested("PortMapping", err.(request.ErrInvalidParams))
}
}
if s.Tls != nil {
if err := s.Tls.Validate(); err != nil {
invalidParams.AddNested("Tls", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetConnectionPool sets the ConnectionPool field's value.
func (s *Listener) SetConnectionPool(v *VirtualNodeConnectionPool) *Listener {
s.ConnectionPool = v
return s
}
// SetHealthCheck sets the HealthCheck field's value.
func (s *Listener) SetHealthCheck(v *HealthCheckPolicy) *Listener {
s.HealthCheck = v
return s
}
// SetOutlierDetection sets the OutlierDetection field's value.
func (s *Listener) SetOutlierDetection(v *OutlierDetection) *Listener {
s.OutlierDetection = v
return s
}
// SetPortMapping sets the PortMapping field's value.
func (s *Listener) SetPortMapping(v *PortMapping) *Listener {
s.PortMapping = v
return s
}
// SetTimeout sets the Timeout field's value.
func (s *Listener) SetTimeout(v *ListenerTimeout) *Listener {
s.Timeout = v
return s
}
// SetTls sets the Tls field's value.
func (s *Listener) SetTls(v *ListenerTls) *Listener {
s.Tls = v
return s
}
// An object that represents timeouts for different protocols.
type ListenerTimeout struct {
_ struct{} `type:"structure"`
// An object that represents types of timeouts.
Grpc *GrpcTimeout `locationName:"grpc" type:"structure"`
// An object that represents types of timeouts.
Http *HttpTimeout `locationName:"http" type:"structure"`
// An object that represents types of timeouts.
Http2 *HttpTimeout `locationName:"http2" type:"structure"`
// An object that represents types of timeouts.
Tcp *TcpTimeout `locationName:"tcp" type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListenerTimeout) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListenerTimeout) GoString() string {
return s.String()
}
// SetGrpc sets the Grpc field's value.
func (s *ListenerTimeout) SetGrpc(v *GrpcTimeout) *ListenerTimeout {
s.Grpc = v
return s
}
// SetHttp sets the Http field's value.
func (s *ListenerTimeout) SetHttp(v *HttpTimeout) *ListenerTimeout {
s.Http = v
return s
}
// SetHttp2 sets the Http2 field's value.
func (s *ListenerTimeout) SetHttp2(v *HttpTimeout) *ListenerTimeout {
s.Http2 = v
return s
}
// SetTcp sets the Tcp field's value.
func (s *ListenerTimeout) SetTcp(v *TcpTimeout) *ListenerTimeout {
s.Tcp = v
return s
}
// An object that represents the Transport Layer Security (TLS) properties for
// a listener.
type ListenerTls struct {
_ struct{} `type:"structure"`
// A reference to an object that represents a listener's Transport Layer Security
// (TLS) certificate.
//
// Certificate is a required field
Certificate *ListenerTlsCertificate `locationName:"certificate" type:"structure" required:"true"`
// Specify one of the following modes.
//
// * STRICT – Listener only accepts connections with TLS enabled.
//
// * PERMISSIVE – Listener accepts connections with or without TLS enabled.
//
// * DISABLED – Listener only accepts connections without TLS.
//
// Mode is a required field
Mode *string `locationName:"mode" type:"string" required:"true" enum:"ListenerTlsMode"`
// A reference to an object that represents a listener's Transport Layer Security
// (TLS) validation context.
Validation *ListenerTlsValidationContext `locationName:"validation" type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListenerTls) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListenerTls) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *ListenerTls) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "ListenerTls"}
if s.Certificate == nil {
invalidParams.Add(request.NewErrParamRequired("Certificate"))
}
if s.Mode == nil {
invalidParams.Add(request.NewErrParamRequired("Mode"))
}
if s.Certificate != nil {
if err := s.Certificate.Validate(); err != nil {
invalidParams.AddNested("Certificate", err.(request.ErrInvalidParams))
}
}
if s.Validation != nil {
if err := s.Validation.Validate(); err != nil {
invalidParams.AddNested("Validation", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetCertificate sets the Certificate field's value.
func (s *ListenerTls) SetCertificate(v *ListenerTlsCertificate) *ListenerTls {
s.Certificate = v
return s
}
// SetMode sets the Mode field's value.
func (s *ListenerTls) SetMode(v string) *ListenerTls {
s.Mode = &v
return s
}
// SetValidation sets the Validation field's value.
func (s *ListenerTls) SetValidation(v *ListenerTlsValidationContext) *ListenerTls {
s.Validation = v
return s
}
// An object that represents an AWS Certicate Manager (ACM) certificate.
type ListenerTlsAcmCertificate struct {
_ struct{} `type:"structure"`
// The Amazon Resource Name (ARN) for the certificate. The certificate must
// meet specific requirements and you must have proxy authorization enabled.
// For more information, see Transport Layer Security (TLS) (https://docs.aws.amazon.com/app-mesh/latest/userguide/tls.html#virtual-node-tls-prerequisites).
//
// CertificateArn is a required field
CertificateArn *string `locationName:"certificateArn" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListenerTlsAcmCertificate) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListenerTlsAcmCertificate) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *ListenerTlsAcmCertificate) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "ListenerTlsAcmCertificate"}
if s.CertificateArn == nil {
invalidParams.Add(request.NewErrParamRequired("CertificateArn"))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetCertificateArn sets the CertificateArn field's value.
func (s *ListenerTlsAcmCertificate) SetCertificateArn(v string) *ListenerTlsAcmCertificate {
s.CertificateArn = &v
return s
}
// An object that represents a listener's Transport Layer Security (TLS) certificate.
type ListenerTlsCertificate struct {
_ struct{} `type:"structure"`
// A reference to an object that represents an AWS Certicate Manager (ACM) certificate.
Acm *ListenerTlsAcmCertificate `locationName:"acm" type:"structure"`
// A reference to an object that represents a local file certificate.
File *ListenerTlsFileCertificate `locationName:"file" type:"structure"`
// A reference to an object that represents a listener's Secret Discovery Service
// certificate.
Sds *ListenerTlsSdsCertificate `locationName:"sds" type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListenerTlsCertificate) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListenerTlsCertificate) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *ListenerTlsCertificate) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "ListenerTlsCertificate"}
if s.Acm != nil {
if err := s.Acm.Validate(); err != nil {
invalidParams.AddNested("Acm", err.(request.ErrInvalidParams))
}
}
if s.File != nil {
if err := s.File.Validate(); err != nil {
invalidParams.AddNested("File", err.(request.ErrInvalidParams))
}
}
if s.Sds != nil {
if err := s.Sds.Validate(); err != nil {
invalidParams.AddNested("Sds", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetAcm sets the Acm field's value.
func (s *ListenerTlsCertificate) SetAcm(v *ListenerTlsAcmCertificate) *ListenerTlsCertificate {
s.Acm = v
return s
}
// SetFile sets the File field's value.
func (s *ListenerTlsCertificate) SetFile(v *ListenerTlsFileCertificate) *ListenerTlsCertificate {
s.File = v
return s
}
// SetSds sets the Sds field's value.
func (s *ListenerTlsCertificate) SetSds(v *ListenerTlsSdsCertificate) *ListenerTlsCertificate {
s.Sds = v
return s
}
// An object that represents a local file certificate. The certificate must
// meet specific requirements and you must have proxy authorization enabled.
// For more information, see Transport Layer Security (TLS) (https://docs.aws.amazon.com/app-mesh/latest/userguide/tls.html#virtual-node-tls-prerequisites).
type ListenerTlsFileCertificate struct {
_ struct{} `type:"structure"`
// The certificate chain for the certificate.
//
// CertificateChain is a required field
CertificateChain *string `locationName:"certificateChain" min:"1" type:"string" required:"true"`
// The private key for a certificate stored on the file system of the virtual
// node that the proxy is running on.
//
// PrivateKey is a required field
PrivateKey *string `locationName:"privateKey" min:"1" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListenerTlsFileCertificate) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListenerTlsFileCertificate) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *ListenerTlsFileCertificate) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "ListenerTlsFileCertificate"}
if s.CertificateChain == nil {
invalidParams.Add(request.NewErrParamRequired("CertificateChain"))
}
if s.CertificateChain != nil && len(*s.CertificateChain) < 1 {
invalidParams.Add(request.NewErrParamMinLen("CertificateChain", 1))
}
if s.PrivateKey == nil {
invalidParams.Add(request.NewErrParamRequired("PrivateKey"))
}
if s.PrivateKey != nil && len(*s.PrivateKey) < 1 {
invalidParams.Add(request.NewErrParamMinLen("PrivateKey", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetCertificateChain sets the CertificateChain field's value.
func (s *ListenerTlsFileCertificate) SetCertificateChain(v string) *ListenerTlsFileCertificate {
s.CertificateChain = &v
return s
}
// SetPrivateKey sets the PrivateKey field's value.
func (s *ListenerTlsFileCertificate) SetPrivateKey(v string) *ListenerTlsFileCertificate {
s.PrivateKey = &v
return s
}
// An object that represents the listener's Secret Discovery Service certificate.
// The proxy must be configured with a local SDS provider via a Unix Domain
// Socket. See App Mesh TLS documentation (https://docs.aws.amazon.com/app-mesh/latest/userguide/tls.html)
// for more info.
type ListenerTlsSdsCertificate struct {
_ struct{} `type:"structure"`
// A reference to an object that represents the name of the secret requested
// from the Secret Discovery Service provider representing Transport Layer Security
// (TLS) materials like a certificate or certificate chain.
//
// SecretName is a required field
SecretName *string `locationName:"secretName" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListenerTlsSdsCertificate) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListenerTlsSdsCertificate) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *ListenerTlsSdsCertificate) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "ListenerTlsSdsCertificate"}
if s.SecretName == nil {
invalidParams.Add(request.NewErrParamRequired("SecretName"))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetSecretName sets the SecretName field's value.
func (s *ListenerTlsSdsCertificate) SetSecretName(v string) *ListenerTlsSdsCertificate {
s.SecretName = &v
return s
}
// An object that represents a listener's Transport Layer Security (TLS) validation
// context.
type ListenerTlsValidationContext struct {
_ struct{} `type:"structure"`
// A reference to an object that represents the SANs for a listener's Transport
// Layer Security (TLS) validation context.
SubjectAlternativeNames *SubjectAlternativeNames `locationName:"subjectAlternativeNames" type:"structure"`
// A reference to where to retrieve the trust chain when validating a peer’s
// Transport Layer Security (TLS) certificate.
//
// Trust is a required field
Trust *ListenerTlsValidationContextTrust `locationName:"trust" type:"structure" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListenerTlsValidationContext) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListenerTlsValidationContext) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *ListenerTlsValidationContext) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "ListenerTlsValidationContext"}
if s.Trust == nil {
invalidParams.Add(request.NewErrParamRequired("Trust"))
}
if s.SubjectAlternativeNames != nil {
if err := s.SubjectAlternativeNames.Validate(); err != nil {
invalidParams.AddNested("SubjectAlternativeNames", err.(request.ErrInvalidParams))
}
}
if s.Trust != nil {
if err := s.Trust.Validate(); err != nil {
invalidParams.AddNested("Trust", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetSubjectAlternativeNames sets the SubjectAlternativeNames field's value.
func (s *ListenerTlsValidationContext) SetSubjectAlternativeNames(v *SubjectAlternativeNames) *ListenerTlsValidationContext {
s.SubjectAlternativeNames = v
return s
}
// SetTrust sets the Trust field's value.
func (s *ListenerTlsValidationContext) SetTrust(v *ListenerTlsValidationContextTrust) *ListenerTlsValidationContext {
s.Trust = v
return s
}
// An object that represents a listener's Transport Layer Security (TLS) validation
// context trust.
type ListenerTlsValidationContextTrust struct {
_ struct{} `type:"structure"`
// An object that represents a Transport Layer Security (TLS) validation context
// trust for a local file.
File *TlsValidationContextFileTrust `locationName:"file" type:"structure"`
// A reference to an object that represents a listener's Transport Layer Security
// (TLS) Secret Discovery Service validation context trust.
Sds *TlsValidationContextSdsTrust `locationName:"sds" type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListenerTlsValidationContextTrust) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListenerTlsValidationContextTrust) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *ListenerTlsValidationContextTrust) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "ListenerTlsValidationContextTrust"}
if s.File != nil {
if err := s.File.Validate(); err != nil {
invalidParams.AddNested("File", err.(request.ErrInvalidParams))
}
}
if s.Sds != nil {
if err := s.Sds.Validate(); err != nil {
invalidParams.AddNested("Sds", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetFile sets the File field's value.
func (s *ListenerTlsValidationContextTrust) SetFile(v *TlsValidationContextFileTrust) *ListenerTlsValidationContextTrust {
s.File = v
return s
}
// SetSds sets the Sds field's value.
func (s *ListenerTlsValidationContextTrust) SetSds(v *TlsValidationContextSdsTrust) *ListenerTlsValidationContextTrust {
s.Sds = v
return s
}
// An object that represents the logging information for a virtual node.
type Logging struct {
_ struct{} `type:"structure"`
// The access log configuration for a virtual node.
AccessLog *AccessLog `locationName:"accessLog" type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s Logging) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s Logging) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *Logging) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "Logging"}
if s.AccessLog != nil {
if err := s.AccessLog.Validate(); err != nil {
invalidParams.AddNested("AccessLog", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetAccessLog sets the AccessLog field's value.
func (s *Logging) SetAccessLog(v *AccessLog) *Logging {
s.AccessLog = v
return s
}
// An object that represents the range of values to match on. The first character
// of the range is included in the range, though the last character is not.
// For example, if the range specified were 1-100, only values 1-99 would be
// matched.
type MatchRange struct {
_ struct{} `type:"structure"`
// The end of the range.
//
// End is a required field
End *int64 `locationName:"end" type:"long" required:"true"`
// The start of the range.
//
// Start is a required field
Start *int64 `locationName:"start" type:"long" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s MatchRange) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s MatchRange) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *MatchRange) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "MatchRange"}
if s.End == nil {
invalidParams.Add(request.NewErrParamRequired("End"))
}
if s.Start == nil {
invalidParams.Add(request.NewErrParamRequired("Start"))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetEnd sets the End field's value.
func (s *MatchRange) SetEnd(v int64) *MatchRange {
s.End = &v
return s
}
// SetStart sets the Start field's value.
func (s *MatchRange) SetStart(v int64) *MatchRange {
s.Start = &v
return s
}
// An object that represents a service mesh returned by a describe operation.
type MeshData struct {
_ struct{} `type:"structure"`
// The name of the service mesh.
//
// MeshName is a required field
MeshName *string `locationName:"meshName" min:"1" type:"string" required:"true"`
// The associated metadata for the service mesh.
//
// Metadata is a required field
Metadata *ResourceMetadata `locationName:"metadata" type:"structure" required:"true"`
// The associated specification for the service mesh.
//
// Spec is a required field
Spec *MeshSpec `locationName:"spec" type:"structure" required:"true"`
// The status of the service mesh.
//
// Status is a required field
Status *MeshStatus `locationName:"status" type:"structure" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s MeshData) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s MeshData) GoString() string {
return s.String()
}
// SetMeshName sets the MeshName field's value.
func (s *MeshData) SetMeshName(v string) *MeshData {
s.MeshName = &v
return s
}
// SetMetadata sets the Metadata field's value.
func (s *MeshData) SetMetadata(v *ResourceMetadata) *MeshData {
s.Metadata = v
return s
}
// SetSpec sets the Spec field's value.
func (s *MeshData) SetSpec(v *MeshSpec) *MeshData {
s.Spec = v
return s
}
// SetStatus sets the Status field's value.
func (s *MeshData) SetStatus(v *MeshStatus) *MeshData {
s.Status = v
return s
}
// An object that represents a service mesh returned by a list operation.
type MeshRef struct {
_ struct{} `type:"structure"`
// The full Amazon Resource Name (ARN) of the service mesh.
//
// Arn is a required field
Arn *string `locationName:"arn" type:"string" required:"true"`
// The Unix epoch timestamp in seconds for when the resource was created.
//
// CreatedAt is a required field
CreatedAt *time.Time `locationName:"createdAt" type:"timestamp" required:"true"`
// The Unix epoch timestamp in seconds for when the resource was last updated.
//
// LastUpdatedAt is a required field
LastUpdatedAt *time.Time `locationName:"lastUpdatedAt" type:"timestamp" required:"true"`
// The name of the service mesh.
//
// MeshName is a required field
MeshName *string `locationName:"meshName" min:"1" type:"string" required:"true"`
// The AWS IAM account ID of the service mesh owner. If the account ID is not
// your own, then it's the ID of the account that shared the mesh with your
// account. For more information about mesh sharing, see Working with shared
// meshes (https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html).
//
// MeshOwner is a required field
MeshOwner *string `locationName:"meshOwner" min:"12" type:"string" required:"true"`
// The AWS IAM account ID of the resource owner. If the account ID is not your
// own, then it's the ID of the mesh owner or of another account that the mesh
// is shared with. For more information about mesh sharing, see Working with
// shared meshes (https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html).
//
// ResourceOwner is a required field
ResourceOwner *string `locationName:"resourceOwner" min:"12" type:"string" required:"true"`
// The version of the resource. Resources are created at version 1, and this
// version is incremented each time that they're updated.
//
// Version is a required field
Version *int64 `locationName:"version" type:"long" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s MeshRef) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s MeshRef) GoString() string {
return s.String()
}
// SetArn sets the Arn field's value.
func (s *MeshRef) SetArn(v string) *MeshRef {
s.Arn = &v
return s
}
// SetCreatedAt sets the CreatedAt field's value.
func (s *MeshRef) SetCreatedAt(v time.Time) *MeshRef {
s.CreatedAt = &v
return s
}
// SetLastUpdatedAt sets the LastUpdatedAt field's value.
func (s *MeshRef) SetLastUpdatedAt(v time.Time) *MeshRef {
s.LastUpdatedAt = &v
return s
}
// SetMeshName sets the MeshName field's value.
func (s *MeshRef) SetMeshName(v string) *MeshRef {
s.MeshName = &v
return s
}
// SetMeshOwner sets the MeshOwner field's value.
func (s *MeshRef) SetMeshOwner(v string) *MeshRef {
s.MeshOwner = &v
return s
}
// SetResourceOwner sets the ResourceOwner field's value.
func (s *MeshRef) SetResourceOwner(v string) *MeshRef {
s.ResourceOwner = &v
return s
}
// SetVersion sets the Version field's value.
func (s *MeshRef) SetVersion(v int64) *MeshRef {
s.Version = &v
return s
}
// An object that represents the specification of a service mesh.
type MeshSpec struct {
_ struct{} `type:"structure"`
// The egress filter rules for the service mesh.
EgressFilter *EgressFilter `locationName:"egressFilter" type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s MeshSpec) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s MeshSpec) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *MeshSpec) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "MeshSpec"}
if s.EgressFilter != nil {
if err := s.EgressFilter.Validate(); err != nil {
invalidParams.AddNested("EgressFilter", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetEgressFilter sets the EgressFilter field's value.
func (s *MeshSpec) SetEgressFilter(v *EgressFilter) *MeshSpec {
s.EgressFilter = v
return s
}
// An object that represents the status of a service mesh.
type MeshStatus struct {
_ struct{} `type:"structure"`
// The current mesh status.
Status *string `locationName:"status" type:"string" enum:"MeshStatusCode"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s MeshStatus) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s MeshStatus) GoString() string {
return s.String()
}
// SetStatus sets the Status field's value.
func (s *MeshStatus) SetStatus(v string) *MeshStatus {
s.Status = &v
return s
}
// The specified resource doesn't exist. Check your request syntax and try again.
type NotFoundException struct {
_ struct{} `type:"structure"`
RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"`
Message_ *string `locationName:"message" type:"string"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s NotFoundException) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s NotFoundException) GoString() string {
return s.String()
}
func newErrorNotFoundException(v protocol.ResponseMetadata) error {
return &NotFoundException{
RespMetadata: v,
}
}
// Code returns the exception type name.
func (s *NotFoundException) Code() string {
return "NotFoundException"
}
// Message returns the exception's message.
func (s *NotFoundException) Message() string {
if s.Message_ != nil {
return *s.Message_
}
return ""
}
// OrigErr always returns nil, satisfies awserr.Error interface.
func (s *NotFoundException) OrigErr() error {
return nil
}
func (s *NotFoundException) Error() string {
return fmt.Sprintf("%s: %s", s.Code(), s.Message())
}
// Status code returns the HTTP status code for the request's response error.
func (s *NotFoundException) StatusCode() int {
return s.RespMetadata.StatusCode
}
// RequestID returns the service's response RequestID for request.
func (s *NotFoundException) RequestID() string {
return s.RespMetadata.RequestID
}
// An object that represents the outlier detection for a virtual node's listener.
type OutlierDetection struct {
_ struct{} `type:"structure"`
// The base amount of time for which a host is ejected.
//
// BaseEjectionDuration is a required field
BaseEjectionDuration *Duration `locationName:"baseEjectionDuration" type:"structure" required:"true"`
// The time interval between ejection sweep analysis.
//
// Interval is a required field
Interval *Duration `locationName:"interval" type:"structure" required:"true"`
// Maximum percentage of hosts in load balancing pool for upstream service that
// can be ejected. Will eject at least one host regardless of the value.
//
// MaxEjectionPercent is a required field
MaxEjectionPercent *int64 `locationName:"maxEjectionPercent" type:"integer" required:"true"`
// Number of consecutive 5xx errors required for ejection.
//
// MaxServerErrors is a required field
MaxServerErrors *int64 `locationName:"maxServerErrors" min:"1" type:"long" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s OutlierDetection) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s OutlierDetection) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *OutlierDetection) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "OutlierDetection"}
if s.BaseEjectionDuration == nil {
invalidParams.Add(request.NewErrParamRequired("BaseEjectionDuration"))
}
if s.Interval == nil {
invalidParams.Add(request.NewErrParamRequired("Interval"))
}
if s.MaxEjectionPercent == nil {
invalidParams.Add(request.NewErrParamRequired("MaxEjectionPercent"))
}
if s.MaxServerErrors == nil {
invalidParams.Add(request.NewErrParamRequired("MaxServerErrors"))
}
if s.MaxServerErrors != nil && *s.MaxServerErrors < 1 {
invalidParams.Add(request.NewErrParamMinValue("MaxServerErrors", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetBaseEjectionDuration sets the BaseEjectionDuration field's value.
func (s *OutlierDetection) SetBaseEjectionDuration(v *Duration) *OutlierDetection {
s.BaseEjectionDuration = v
return s
}
// SetInterval sets the Interval field's value.
func (s *OutlierDetection) SetInterval(v *Duration) *OutlierDetection {
s.Interval = v
return s
}
// SetMaxEjectionPercent sets the MaxEjectionPercent field's value.
func (s *OutlierDetection) SetMaxEjectionPercent(v int64) *OutlierDetection {
s.MaxEjectionPercent = &v
return s
}
// SetMaxServerErrors sets the MaxServerErrors field's value.
func (s *OutlierDetection) SetMaxServerErrors(v int64) *OutlierDetection {
s.MaxServerErrors = &v
return s
}
// An object that represents a port mapping.
type PortMapping struct {
_ struct{} `type:"structure"`
// The port used for the port mapping.
//
// Port is a required field
Port *int64 `locationName:"port" min:"1" type:"integer" required:"true"`
// The protocol used for the port mapping. Specify one protocol.
//
// Protocol is a required field
Protocol *string `locationName:"protocol" type:"string" required:"true" enum:"PortProtocol"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s PortMapping) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s PortMapping) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *PortMapping) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "PortMapping"}
if s.Port == nil {
invalidParams.Add(request.NewErrParamRequired("Port"))
}
if s.Port != nil && *s.Port < 1 {
invalidParams.Add(request.NewErrParamMinValue("Port", 1))
}
if s.Protocol == nil {
invalidParams.Add(request.NewErrParamRequired("Protocol"))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetPort sets the Port field's value.
func (s *PortMapping) SetPort(v int64) *PortMapping {
s.Port = &v
return s
}
// SetProtocol sets the Protocol field's value.
func (s *PortMapping) SetProtocol(v string) *PortMapping {
s.Protocol = &v
return s
}
// An object representing the query parameter to match.
type QueryParameterMatch struct {
_ struct{} `type:"structure"`
// The exact query parameter to match on.
Exact *string `locationName:"exact" type:"string"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s QueryParameterMatch) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s QueryParameterMatch) GoString() string {
return s.String()
}
// SetExact sets the Exact field's value.
func (s *QueryParameterMatch) SetExact(v string) *QueryParameterMatch {
s.Exact = &v
return s
}
// You can't delete the specified resource because it's in use or required by
// another resource.
type ResourceInUseException struct {
_ struct{} `type:"structure"`
RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"`
Message_ *string `locationName:"message" type:"string"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ResourceInUseException) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ResourceInUseException) GoString() string {
return s.String()
}
func newErrorResourceInUseException(v protocol.ResponseMetadata) error {
return &ResourceInUseException{
RespMetadata: v,
}
}
// Code returns the exception type name.
func (s *ResourceInUseException) Code() string {
return "ResourceInUseException"
}
// Message returns the exception's message.
func (s *ResourceInUseException) Message() string {
if s.Message_ != nil {
return *s.Message_
}
return ""
}
// OrigErr always returns nil, satisfies awserr.Error interface.
func (s *ResourceInUseException) OrigErr() error {
return nil
}
func (s *ResourceInUseException) Error() string {
return fmt.Sprintf("%s: %s", s.Code(), s.Message())
}
// Status code returns the HTTP status code for the request's response error.
func (s *ResourceInUseException) StatusCode() int {
return s.RespMetadata.StatusCode
}
// RequestID returns the service's response RequestID for request.
func (s *ResourceInUseException) RequestID() string {
return s.RespMetadata.RequestID
}
// An object that represents metadata for a resource.
type ResourceMetadata struct {
_ struct{} `type:"structure"`
// The full Amazon Resource Name (ARN) for the resource.
//
// Arn is a required field
Arn *string `locationName:"arn" type:"string" required:"true"`
// The Unix epoch timestamp in seconds for when the resource was created.
//
// CreatedAt is a required field
CreatedAt *time.Time `locationName:"createdAt" type:"timestamp" required:"true"`
// The Unix epoch timestamp in seconds for when the resource was last updated.
//
// LastUpdatedAt is a required field
LastUpdatedAt *time.Time `locationName:"lastUpdatedAt" type:"timestamp" required:"true"`
// The AWS IAM account ID of the service mesh owner. If the account ID is not
// your own, then it's the ID of the account that shared the mesh with your
// account. For more information about mesh sharing, see Working with shared
// meshes (https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html).
//
// MeshOwner is a required field
MeshOwner *string `locationName:"meshOwner" min:"12" type:"string" required:"true"`
// The AWS IAM account ID of the resource owner. If the account ID is not your
// own, then it's the ID of the mesh owner or of another account that the mesh
// is shared with. For more information about mesh sharing, see Working with
// shared meshes (https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html).
//
// ResourceOwner is a required field
ResourceOwner *string `locationName:"resourceOwner" min:"12" type:"string" required:"true"`
// The unique identifier for the resource.
//
// Uid is a required field
Uid *string `locationName:"uid" type:"string" required:"true"`
// The version of the resource. Resources are created at version 1, and this
// version is incremented each time that they're updated.
//
// Version is a required field
Version *int64 `locationName:"version" type:"long" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ResourceMetadata) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ResourceMetadata) GoString() string {
return s.String()
}
// SetArn sets the Arn field's value.
func (s *ResourceMetadata) SetArn(v string) *ResourceMetadata {
s.Arn = &v
return s
}
// SetCreatedAt sets the CreatedAt field's value.
func (s *ResourceMetadata) SetCreatedAt(v time.Time) *ResourceMetadata {
s.CreatedAt = &v
return s
}
// SetLastUpdatedAt sets the LastUpdatedAt field's value.
func (s *ResourceMetadata) SetLastUpdatedAt(v time.Time) *ResourceMetadata {
s.LastUpdatedAt = &v
return s
}
// SetMeshOwner sets the MeshOwner field's value.
func (s *ResourceMetadata) SetMeshOwner(v string) *ResourceMetadata {
s.MeshOwner = &v
return s
}
// SetResourceOwner sets the ResourceOwner field's value.
func (s *ResourceMetadata) SetResourceOwner(v string) *ResourceMetadata {
s.ResourceOwner = &v
return s
}
// SetUid sets the Uid field's value.
func (s *ResourceMetadata) SetUid(v string) *ResourceMetadata {
s.Uid = &v
return s
}
// SetVersion sets the Version field's value.
func (s *ResourceMetadata) SetVersion(v int64) *ResourceMetadata {
s.Version = &v
return s
}
// An object that represents a route returned by a describe operation.
type RouteData struct {
_ struct{} `type:"structure"`
// The name of the service mesh that the route resides in.
//
// MeshName is a required field
MeshName *string `locationName:"meshName" min:"1" type:"string" required:"true"`
// The associated metadata for the route.
//
// Metadata is a required field
Metadata *ResourceMetadata `locationName:"metadata" type:"structure" required:"true"`
// The name of the route.
//
// RouteName is a required field
RouteName *string `locationName:"routeName" min:"1" type:"string" required:"true"`
// The specifications of the route.
//
// Spec is a required field
Spec *RouteSpec `locationName:"spec" type:"structure" required:"true"`
// The status of the route.
//
// Status is a required field
Status *RouteStatus `locationName:"status" type:"structure" required:"true"`
// The virtual router that the route is associated with.
//
// VirtualRouterName is a required field
VirtualRouterName *string `locationName:"virtualRouterName" min:"1" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s RouteData) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s RouteData) GoString() string {
return s.String()
}
// SetMeshName sets the MeshName field's value.
func (s *RouteData) SetMeshName(v string) *RouteData {
s.MeshName = &v
return s
}
// SetMetadata sets the Metadata field's value.
func (s *RouteData) SetMetadata(v *ResourceMetadata) *RouteData {
s.Metadata = v
return s
}
// SetRouteName sets the RouteName field's value.
func (s *RouteData) SetRouteName(v string) *RouteData {
s.RouteName = &v
return s
}
// SetSpec sets the Spec field's value.
func (s *RouteData) SetSpec(v *RouteSpec) *RouteData {
s.Spec = v
return s
}
// SetStatus sets the Status field's value.
func (s *RouteData) SetStatus(v *RouteStatus) *RouteData {
s.Status = v
return s
}
// SetVirtualRouterName sets the VirtualRouterName field's value.
func (s *RouteData) SetVirtualRouterName(v string) *RouteData {
s.VirtualRouterName = &v
return s
}
// An object that represents a route returned by a list operation.
type RouteRef struct {
_ struct{} `type:"structure"`
// The full Amazon Resource Name (ARN) for the route.
//
// Arn is a required field
Arn *string `locationName:"arn" type:"string" required:"true"`
// The Unix epoch timestamp in seconds for when the resource was created.
//
// CreatedAt is a required field
CreatedAt *time.Time `locationName:"createdAt" type:"timestamp" required:"true"`
// The Unix epoch timestamp in seconds for when the resource was last updated.
//
// LastUpdatedAt is a required field
LastUpdatedAt *time.Time `locationName:"lastUpdatedAt" type:"timestamp" required:"true"`
// The name of the service mesh that the route resides in.
//
// MeshName is a required field
MeshName *string `locationName:"meshName" min:"1" type:"string" required:"true"`
// The AWS IAM account ID of the service mesh owner. If the account ID is not
// your own, then it's the ID of the account that shared the mesh with your
// account. For more information about mesh sharing, see Working with shared
// meshes (https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html).
//
// MeshOwner is a required field
MeshOwner *string `locationName:"meshOwner" min:"12" type:"string" required:"true"`
// The AWS IAM account ID of the resource owner. If the account ID is not your
// own, then it's the ID of the mesh owner or of another account that the mesh
// is shared with. For more information about mesh sharing, see Working with
// shared meshes (https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html).
//
// ResourceOwner is a required field
ResourceOwner *string `locationName:"resourceOwner" min:"12" type:"string" required:"true"`
// The name of the route.
//
// RouteName is a required field
RouteName *string `locationName:"routeName" min:"1" type:"string" required:"true"`
// The version of the resource. Resources are created at version 1, and this
// version is incremented each time that they're updated.
//
// Version is a required field
Version *int64 `locationName:"version" type:"long" required:"true"`
// The virtual router that the route is associated with.
//
// VirtualRouterName is a required field
VirtualRouterName *string `locationName:"virtualRouterName" min:"1" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s RouteRef) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s RouteRef) GoString() string {
return s.String()
}
// SetArn sets the Arn field's value.
func (s *RouteRef) SetArn(v string) *RouteRef {
s.Arn = &v
return s
}
// SetCreatedAt sets the CreatedAt field's value.
func (s *RouteRef) SetCreatedAt(v time.Time) *RouteRef {
s.CreatedAt = &v
return s
}
// SetLastUpdatedAt sets the LastUpdatedAt field's value.
func (s *RouteRef) SetLastUpdatedAt(v time.Time) *RouteRef {
s.LastUpdatedAt = &v
return s
}
// SetMeshName sets the MeshName field's value.
func (s *RouteRef) SetMeshName(v string) *RouteRef {
s.MeshName = &v
return s
}
// SetMeshOwner sets the MeshOwner field's value.
func (s *RouteRef) SetMeshOwner(v string) *RouteRef {
s.MeshOwner = &v
return s
}
// SetResourceOwner sets the ResourceOwner field's value.
func (s *RouteRef) SetResourceOwner(v string) *RouteRef {
s.ResourceOwner = &v
return s
}
// SetRouteName sets the RouteName field's value.
func (s *RouteRef) SetRouteName(v string) *RouteRef {
s.RouteName = &v
return s
}
// SetVersion sets the Version field's value.
func (s *RouteRef) SetVersion(v int64) *RouteRef {
s.Version = &v
return s
}
// SetVirtualRouterName sets the VirtualRouterName field's value.
func (s *RouteRef) SetVirtualRouterName(v string) *RouteRef {
s.VirtualRouterName = &v
return s
}
// An object that represents a route specification. Specify one route type.
type RouteSpec struct {
_ struct{} `type:"structure"`
// An object that represents the specification of a gRPC route.
GrpcRoute *GrpcRoute `locationName:"grpcRoute" type:"structure"`
// An object that represents the specification of an HTTP/2 route.
Http2Route *HttpRoute `locationName:"http2Route" type:"structure"`
// An object that represents the specification of an HTTP route.
HttpRoute *HttpRoute `locationName:"httpRoute" type:"structure"`
// The priority for the route. Routes are matched based on the specified value,
// where 0 is the highest priority.
Priority *int64 `locationName:"priority" type:"integer"`
// An object that represents the specification of a TCP route.
TcpRoute *TcpRoute `locationName:"tcpRoute" type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s RouteSpec) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s RouteSpec) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *RouteSpec) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "RouteSpec"}
if s.GrpcRoute != nil {
if err := s.GrpcRoute.Validate(); err != nil {
invalidParams.AddNested("GrpcRoute", err.(request.ErrInvalidParams))
}
}
if s.Http2Route != nil {
if err := s.Http2Route.Validate(); err != nil {
invalidParams.AddNested("Http2Route", err.(request.ErrInvalidParams))
}
}
if s.HttpRoute != nil {
if err := s.HttpRoute.Validate(); err != nil {
invalidParams.AddNested("HttpRoute", err.(request.ErrInvalidParams))
}
}
if s.TcpRoute != nil {
if err := s.TcpRoute.Validate(); err != nil {
invalidParams.AddNested("TcpRoute", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetGrpcRoute sets the GrpcRoute field's value.
func (s *RouteSpec) SetGrpcRoute(v *GrpcRoute) *RouteSpec {
s.GrpcRoute = v
return s
}
// SetHttp2Route sets the Http2Route field's value.
func (s *RouteSpec) SetHttp2Route(v *HttpRoute) *RouteSpec {
s.Http2Route = v
return s
}
// SetHttpRoute sets the HttpRoute field's value.
func (s *RouteSpec) SetHttpRoute(v *HttpRoute) *RouteSpec {
s.HttpRoute = v
return s
}
// SetPriority sets the Priority field's value.
func (s *RouteSpec) SetPriority(v int64) *RouteSpec {
s.Priority = &v
return s
}
// SetTcpRoute sets the TcpRoute field's value.
func (s *RouteSpec) SetTcpRoute(v *TcpRoute) *RouteSpec {
s.TcpRoute = v
return s
}
// An object that represents the current status of a route.
type RouteStatus struct {
_ struct{} `type:"structure"`
// The current status for the route.
//
// Status is a required field
Status *string `locationName:"status" type:"string" required:"true" enum:"RouteStatusCode"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s RouteStatus) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s RouteStatus) GoString() string {
return s.String()
}
// SetStatus sets the Status field's value.
func (s *RouteStatus) SetStatus(v string) *RouteStatus {
s.Status = &v
return s
}
// An object that represents the service discovery information for a virtual
// node.
type ServiceDiscovery struct {
_ struct{} `type:"structure"`
// Specifies any Cloud Map information for the virtual node.
AwsCloudMap *AwsCloudMapServiceDiscovery `locationName:"awsCloudMap" type:"structure"`
// Specifies the DNS information for the virtual node.
Dns *DnsServiceDiscovery `locationName:"dns" type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ServiceDiscovery) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ServiceDiscovery) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *ServiceDiscovery) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "ServiceDiscovery"}
if s.AwsCloudMap != nil {
if err := s.AwsCloudMap.Validate(); err != nil {
invalidParams.AddNested("AwsCloudMap", err.(request.ErrInvalidParams))
}
}
if s.Dns != nil {
if err := s.Dns.Validate(); err != nil {
invalidParams.AddNested("Dns", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetAwsCloudMap sets the AwsCloudMap field's value.
func (s *ServiceDiscovery) SetAwsCloudMap(v *AwsCloudMapServiceDiscovery) *ServiceDiscovery {
s.AwsCloudMap = v
return s
}
// SetDns sets the Dns field's value.
func (s *ServiceDiscovery) SetDns(v *DnsServiceDiscovery) *ServiceDiscovery {
s.Dns = v
return s
}
// The request has failed due to a temporary failure of the service.
type ServiceUnavailableException struct {
_ struct{} `type:"structure"`
RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"`
Message_ *string `locationName:"message" type:"string"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ServiceUnavailableException) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ServiceUnavailableException) GoString() string {
return s.String()
}
func newErrorServiceUnavailableException(v protocol.ResponseMetadata) error {
return &ServiceUnavailableException{
RespMetadata: v,
}
}
// Code returns the exception type name.
func (s *ServiceUnavailableException) Code() string {
return "ServiceUnavailableException"
}
// Message returns the exception's message.
func (s *ServiceUnavailableException) Message() string {
if s.Message_ != nil {
return *s.Message_
}
return ""
}
// OrigErr always returns nil, satisfies awserr.Error interface.
func (s *ServiceUnavailableException) OrigErr() error {
return nil
}
func (s *ServiceUnavailableException) Error() string {
return fmt.Sprintf("%s: %s", s.Code(), s.Message())
}
// Status code returns the HTTP status code for the request's response error.
func (s *ServiceUnavailableException) StatusCode() int {
return s.RespMetadata.StatusCode
}
// RequestID returns the service's response RequestID for request.
func (s *ServiceUnavailableException) RequestID() string {
return s.RespMetadata.RequestID
}
// An object that represents the methods by which a subject alternative name
// on a peer Transport Layer Security (TLS) certificate can be matched.
type SubjectAlternativeNameMatchers struct {
_ struct{} `type:"structure"`
// The values sent must match the specified values exactly.
//
// Exact is a required field
Exact []*string `locationName:"exact" type:"list" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s SubjectAlternativeNameMatchers) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s SubjectAlternativeNameMatchers) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *SubjectAlternativeNameMatchers) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "SubjectAlternativeNameMatchers"}
if s.Exact == nil {
invalidParams.Add(request.NewErrParamRequired("Exact"))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetExact sets the Exact field's value.
func (s *SubjectAlternativeNameMatchers) SetExact(v []*string) *SubjectAlternativeNameMatchers {
s.Exact = v
return s
}
// An object that represents the subject alternative names secured by the certificate.
type SubjectAlternativeNames struct {
_ struct{} `type:"structure"`
// An object that represents the criteria for determining a SANs match.
//
// Match is a required field
Match *SubjectAlternativeNameMatchers `locationName:"match" type:"structure" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s SubjectAlternativeNames) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s SubjectAlternativeNames) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *SubjectAlternativeNames) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "SubjectAlternativeNames"}
if s.Match == nil {
invalidParams.Add(request.NewErrParamRequired("Match"))
}
if s.Match != nil {
if err := s.Match.Validate(); err != nil {
invalidParams.AddNested("Match", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetMatch sets the Match field's value.
func (s *SubjectAlternativeNames) SetMatch(v *SubjectAlternativeNameMatchers) *SubjectAlternativeNames {
s.Match = v
return s
}
// Optional metadata that you apply to a resource to assist with categorization
// and organization. Each tag consists of a key and an optional value, both
// of which you define. Tag keys can have a maximum character length of 128
// characters, and tag values can have a maximum length of 256 characters.
type TagRef struct {
_ struct{} `type:"structure"`
// One part of a key-value pair that make up a tag. A key is a general label
// that acts like a category for more specific tag values.
//
// Key is a required field
Key *string `locationName:"key" min:"1" type:"string" required:"true"`
// The optional part of a key-value pair that make up a tag. A value acts as
// a descriptor within a tag category (key).
//
// Value is a required field
Value *string `locationName:"value" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s TagRef) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s TagRef) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *TagRef) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "TagRef"}
if s.Key == nil {
invalidParams.Add(request.NewErrParamRequired("Key"))
}
if s.Key != nil && len(*s.Key) < 1 {
invalidParams.Add(request.NewErrParamMinLen("Key", 1))
}
if s.Value == nil {
invalidParams.Add(request.NewErrParamRequired("Value"))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetKey sets the Key field's value.
func (s *TagRef) SetKey(v string) *TagRef {
s.Key = &v
return s
}
// SetValue sets the Value field's value.
func (s *TagRef) SetValue(v string) *TagRef {
s.Value = &v
return s
}
type TagResourceInput struct {
_ struct{} `type:"structure"`
// The Amazon Resource Name (ARN) of the resource to add tags to.
//
// ResourceArn is a required field
ResourceArn *string `location:"querystring" locationName:"resourceArn" type:"string" required:"true"`
// The tags to add to the resource. A tag is an array of key-value pairs. Tag
// keys can have a maximum character length of 128 characters, and tag values
// can have a maximum length of 256 characters.
//
// Tags is a required field
Tags []*TagRef `locationName:"tags" type:"list" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s TagResourceInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s TagResourceInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *TagResourceInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "TagResourceInput"}
if s.ResourceArn == nil {
invalidParams.Add(request.NewErrParamRequired("ResourceArn"))
}
if s.Tags == nil {
invalidParams.Add(request.NewErrParamRequired("Tags"))
}
if s.Tags != nil {
for i, v := range s.Tags {
if v == nil {
continue
}
if err := v.Validate(); err != nil {
invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams))
}
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetResourceArn sets the ResourceArn field's value.
func (s *TagResourceInput) SetResourceArn(v string) *TagResourceInput {
s.ResourceArn = &v
return s
}
// SetTags sets the Tags field's value.
func (s *TagResourceInput) SetTags(v []*TagRef) *TagResourceInput {
s.Tags = v
return s
}
type TagResourceOutput struct {
_ struct{} `type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s TagResourceOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s TagResourceOutput) GoString() string {
return s.String()
}
// An object that represents a TCP route type.
type TcpRoute struct {
_ struct{} `type:"structure"`
// The action to take if a match is determined.
//
// Action is a required field
Action *TcpRouteAction `locationName:"action" type:"structure" required:"true"`
// An object that represents types of timeouts.
Timeout *TcpTimeout `locationName:"timeout" type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s TcpRoute) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s TcpRoute) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *TcpRoute) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "TcpRoute"}
if s.Action == nil {
invalidParams.Add(request.NewErrParamRequired("Action"))
}
if s.Action != nil {
if err := s.Action.Validate(); err != nil {
invalidParams.AddNested("Action", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetAction sets the Action field's value.
func (s *TcpRoute) SetAction(v *TcpRouteAction) *TcpRoute {
s.Action = v
return s
}
// SetTimeout sets the Timeout field's value.
func (s *TcpRoute) SetTimeout(v *TcpTimeout) *TcpRoute {
s.Timeout = v
return s
}
// An object that represents the action to take if a match is determined.
type TcpRouteAction struct {
_ struct{} `type:"structure"`
// An object that represents the targets that traffic is routed to when a request
// matches the route.
//
// WeightedTargets is a required field
WeightedTargets []*WeightedTarget `locationName:"weightedTargets" min:"1" type:"list" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s TcpRouteAction) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s TcpRouteAction) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *TcpRouteAction) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "TcpRouteAction"}
if s.WeightedTargets == nil {
invalidParams.Add(request.NewErrParamRequired("WeightedTargets"))
}
if s.WeightedTargets != nil && len(s.WeightedTargets) < 1 {
invalidParams.Add(request.NewErrParamMinLen("WeightedTargets", 1))
}
if s.WeightedTargets != nil {
for i, v := range s.WeightedTargets {
if v == nil {
continue
}
if err := v.Validate(); err != nil {
invalidParams.AddNested(fmt.Sprintf("%s[%v]", "WeightedTargets", i), err.(request.ErrInvalidParams))
}
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetWeightedTargets sets the WeightedTargets field's value.
func (s *TcpRouteAction) SetWeightedTargets(v []*WeightedTarget) *TcpRouteAction {
s.WeightedTargets = v
return s
}
// An object that represents types of timeouts.
type TcpTimeout struct {
_ struct{} `type:"structure"`
// An object that represents an idle timeout. An idle timeout bounds the amount
// of time that a connection may be idle. The default value is none.
Idle *Duration `locationName:"idle" type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s TcpTimeout) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s TcpTimeout) GoString() string {
return s.String()
}
// SetIdle sets the Idle field's value.
func (s *TcpTimeout) SetIdle(v *Duration) *TcpTimeout {
s.Idle = v
return s
}
// An object that represents how the proxy will validate its peer during Transport
// Layer Security (TLS) negotiation.
type TlsValidationContext struct {
_ struct{} `type:"structure"`
// A reference to an object that represents the SANs for a Transport Layer Security
// (TLS) validation context.
SubjectAlternativeNames *SubjectAlternativeNames `locationName:"subjectAlternativeNames" type:"structure"`
// A reference to where to retrieve the trust chain when validating a peer’s
// Transport Layer Security (TLS) certificate.
//
// Trust is a required field
Trust *TlsValidationContextTrust `locationName:"trust" type:"structure" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s TlsValidationContext) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s TlsValidationContext) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *TlsValidationContext) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "TlsValidationContext"}
if s.Trust == nil {
invalidParams.Add(request.NewErrParamRequired("Trust"))
}
if s.SubjectAlternativeNames != nil {
if err := s.SubjectAlternativeNames.Validate(); err != nil {
invalidParams.AddNested("SubjectAlternativeNames", err.(request.ErrInvalidParams))
}
}
if s.Trust != nil {
if err := s.Trust.Validate(); err != nil {
invalidParams.AddNested("Trust", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetSubjectAlternativeNames sets the SubjectAlternativeNames field's value.
func (s *TlsValidationContext) SetSubjectAlternativeNames(v *SubjectAlternativeNames) *TlsValidationContext {
s.SubjectAlternativeNames = v
return s
}
// SetTrust sets the Trust field's value.
func (s *TlsValidationContext) SetTrust(v *TlsValidationContextTrust) *TlsValidationContext {
s.Trust = v
return s
}
// An object that represents a Transport Layer Security (TLS) validation context
// trust for an Certificate Manager certificate.
type TlsValidationContextAcmTrust struct {
_ struct{} `type:"structure"`
// One or more ACM Amazon Resource Name (ARN)s.
//
// CertificateAuthorityArns is a required field
CertificateAuthorityArns []*string `locationName:"certificateAuthorityArns" min:"1" type:"list" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s TlsValidationContextAcmTrust) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s TlsValidationContextAcmTrust) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *TlsValidationContextAcmTrust) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "TlsValidationContextAcmTrust"}
if s.CertificateAuthorityArns == nil {
invalidParams.Add(request.NewErrParamRequired("CertificateAuthorityArns"))
}
if s.CertificateAuthorityArns != nil && len(s.CertificateAuthorityArns) < 1 {
invalidParams.Add(request.NewErrParamMinLen("CertificateAuthorityArns", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetCertificateAuthorityArns sets the CertificateAuthorityArns field's value.
func (s *TlsValidationContextAcmTrust) SetCertificateAuthorityArns(v []*string) *TlsValidationContextAcmTrust {
s.CertificateAuthorityArns = v
return s
}
// An object that represents a Transport Layer Security (TLS) validation context
// trust for a local file.
type TlsValidationContextFileTrust struct {
_ struct{} `type:"structure"`
// The certificate trust chain for a certificate stored on the file system of
// the virtual node that the proxy is running on.
//
// CertificateChain is a required field
CertificateChain *string `locationName:"certificateChain" min:"1" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s TlsValidationContextFileTrust) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s TlsValidationContextFileTrust) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *TlsValidationContextFileTrust) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "TlsValidationContextFileTrust"}
if s.CertificateChain == nil {
invalidParams.Add(request.NewErrParamRequired("CertificateChain"))
}
if s.CertificateChain != nil && len(*s.CertificateChain) < 1 {
invalidParams.Add(request.NewErrParamMinLen("CertificateChain", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetCertificateChain sets the CertificateChain field's value.
func (s *TlsValidationContextFileTrust) SetCertificateChain(v string) *TlsValidationContextFileTrust {
s.CertificateChain = &v
return s
}
// An object that represents a Transport Layer Security (TLS) Secret Discovery
// Service validation context trust. The proxy must be configured with a local
// SDS provider via a Unix Domain Socket. See App Mesh TLS documentation (https://docs.aws.amazon.com/app-mesh/latest/userguide/tls.html)
// for more info.
type TlsValidationContextSdsTrust struct {
_ struct{} `type:"structure"`
// A reference to an object that represents the name of the secret for a Transport
// Layer Security (TLS) Secret Discovery Service validation context trust.
//
// SecretName is a required field
SecretName *string `locationName:"secretName" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s TlsValidationContextSdsTrust) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s TlsValidationContextSdsTrust) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *TlsValidationContextSdsTrust) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "TlsValidationContextSdsTrust"}
if s.SecretName == nil {
invalidParams.Add(request.NewErrParamRequired("SecretName"))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetSecretName sets the SecretName field's value.
func (s *TlsValidationContextSdsTrust) SetSecretName(v string) *TlsValidationContextSdsTrust {
s.SecretName = &v
return s
}
// An object that represents a Transport Layer Security (TLS) validation context
// trust.
type TlsValidationContextTrust struct {
_ struct{} `type:"structure"`
// A reference to an object that represents a Transport Layer Security (TLS)
// validation context trust for an Certificate Manager certificate.
Acm *TlsValidationContextAcmTrust `locationName:"acm" type:"structure"`
// An object that represents a Transport Layer Security (TLS) validation context
// trust for a local file.
File *TlsValidationContextFileTrust `locationName:"file" type:"structure"`
// A reference to an object that represents a Transport Layer Security (TLS)
// Secret Discovery Service validation context trust.
Sds *TlsValidationContextSdsTrust `locationName:"sds" type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s TlsValidationContextTrust) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s TlsValidationContextTrust) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *TlsValidationContextTrust) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "TlsValidationContextTrust"}
if s.Acm != nil {
if err := s.Acm.Validate(); err != nil {
invalidParams.AddNested("Acm", err.(request.ErrInvalidParams))
}
}
if s.File != nil {
if err := s.File.Validate(); err != nil {
invalidParams.AddNested("File", err.(request.ErrInvalidParams))
}
}
if s.Sds != nil {
if err := s.Sds.Validate(); err != nil {
invalidParams.AddNested("Sds", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetAcm sets the Acm field's value.
func (s *TlsValidationContextTrust) SetAcm(v *TlsValidationContextAcmTrust) *TlsValidationContextTrust {
s.Acm = v
return s
}
// SetFile sets the File field's value.
func (s *TlsValidationContextTrust) SetFile(v *TlsValidationContextFileTrust) *TlsValidationContextTrust {
s.File = v
return s
}
// SetSds sets the Sds field's value.
func (s *TlsValidationContextTrust) SetSds(v *TlsValidationContextSdsTrust) *TlsValidationContextTrust {
s.Sds = v
return s
}
// The maximum request rate permitted by the App Mesh APIs has been exceeded
// for your account. For best results, use an increasing or variable sleep interval
// between requests.
type TooManyRequestsException struct {
_ struct{} `type:"structure"`
RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"`
Message_ *string `locationName:"message" type:"string"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s TooManyRequestsException) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s TooManyRequestsException) GoString() string {
return s.String()
}
func newErrorTooManyRequestsException(v protocol.ResponseMetadata) error {
return &TooManyRequestsException{
RespMetadata: v,
}
}
// Code returns the exception type name.
func (s *TooManyRequestsException) Code() string {
return "TooManyRequestsException"
}
// Message returns the exception's message.
func (s *TooManyRequestsException) Message() string {
if s.Message_ != nil {
return *s.Message_
}
return ""
}
// OrigErr always returns nil, satisfies awserr.Error interface.
func (s *TooManyRequestsException) OrigErr() error {
return nil
}
func (s *TooManyRequestsException) Error() string {
return fmt.Sprintf("%s: %s", s.Code(), s.Message())
}
// Status code returns the HTTP status code for the request's response error.
func (s *TooManyRequestsException) StatusCode() int {
return s.RespMetadata.StatusCode
}
// RequestID returns the service's response RequestID for request.
func (s *TooManyRequestsException) RequestID() string {
return s.RespMetadata.RequestID
}
// The request exceeds the maximum allowed number of tags allowed per resource.
// The current limit is 50 user tags per resource. You must reduce the number
// of tags in the request. None of the tags in this request were applied.
type TooManyTagsException struct {
_ struct{} `type:"structure"`
RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"`
Message_ *string `locationName:"message" type:"string"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s TooManyTagsException) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s TooManyTagsException) GoString() string {
return s.String()
}
func newErrorTooManyTagsException(v protocol.ResponseMetadata) error {
return &TooManyTagsException{
RespMetadata: v,
}
}
// Code returns the exception type name.
func (s *TooManyTagsException) Code() string {
return "TooManyTagsException"
}
// Message returns the exception's message.
func (s *TooManyTagsException) Message() string {
if s.Message_ != nil {
return *s.Message_
}
return ""
}
// OrigErr always returns nil, satisfies awserr.Error interface.
func (s *TooManyTagsException) OrigErr() error {
return nil
}
func (s *TooManyTagsException) Error() string {
return fmt.Sprintf("%s: %s", s.Code(), s.Message())
}
// Status code returns the HTTP status code for the request's response error.
func (s *TooManyTagsException) StatusCode() int {
return s.RespMetadata.StatusCode
}
// RequestID returns the service's response RequestID for request.
func (s *TooManyTagsException) RequestID() string {
return s.RespMetadata.RequestID
}
type UntagResourceInput struct {
_ struct{} `type:"structure"`
// The Amazon Resource Name (ARN) of the resource to delete tags from.
//
// ResourceArn is a required field
ResourceArn *string `location:"querystring" locationName:"resourceArn" type:"string" required:"true"`
// The keys of the tags to be removed.
//
// TagKeys is a required field
TagKeys []*string `locationName:"tagKeys" type:"list" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s UntagResourceInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s UntagResourceInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *UntagResourceInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "UntagResourceInput"}
if s.ResourceArn == nil {
invalidParams.Add(request.NewErrParamRequired("ResourceArn"))
}
if s.TagKeys == nil {
invalidParams.Add(request.NewErrParamRequired("TagKeys"))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetResourceArn sets the ResourceArn field's value.
func (s *UntagResourceInput) SetResourceArn(v string) *UntagResourceInput {
s.ResourceArn = &v
return s
}
// SetTagKeys sets the TagKeys field's value.
func (s *UntagResourceInput) SetTagKeys(v []*string) *UntagResourceInput {
s.TagKeys = v
return s
}
type UntagResourceOutput struct {
_ struct{} `type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s UntagResourceOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s UntagResourceOutput) GoString() string {
return s.String()
}
type UpdateGatewayRouteInput struct {
_ struct{} `type:"structure"`
// Unique, case-sensitive identifier that you provide to ensure the idempotency
// of the request. Up to 36 letters, numbers, hyphens, and underscores are allowed.
ClientToken *string `locationName:"clientToken" type:"string" idempotencyToken:"true"`
// The name of the gateway route to update.
//
// GatewayRouteName is a required field
GatewayRouteName *string `location:"uri" locationName:"gatewayRouteName" min:"1" type:"string" required:"true"`
// The name of the service mesh that the gateway route resides in.
//
// MeshName is a required field
MeshName *string `location:"uri" locationName:"meshName" min:"1" type:"string" required:"true"`
// The AWS IAM account ID of the service mesh owner. If the account ID is not
// your own, then it's the ID of the account that shared the mesh with your
// account. For more information about mesh sharing, see Working with shared
// meshes (https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html).
MeshOwner *string `location:"querystring" locationName:"meshOwner" min:"12" type:"string"`
// The new gateway route specification to apply. This overwrites the existing
// data.
//
// Spec is a required field
Spec *GatewayRouteSpec `locationName:"spec" type:"structure" required:"true"`
// The name of the virtual gateway that the gateway route is associated with.
//
// VirtualGatewayName is a required field
VirtualGatewayName *string `location:"uri" locationName:"virtualGatewayName" min:"1" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s UpdateGatewayRouteInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s UpdateGatewayRouteInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *UpdateGatewayRouteInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "UpdateGatewayRouteInput"}
if s.GatewayRouteName == nil {
invalidParams.Add(request.NewErrParamRequired("GatewayRouteName"))
}
if s.GatewayRouteName != nil && len(*s.GatewayRouteName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("GatewayRouteName", 1))
}
if s.MeshName == nil {
invalidParams.Add(request.NewErrParamRequired("MeshName"))
}
if s.MeshName != nil && len(*s.MeshName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("MeshName", 1))
}
if s.MeshOwner != nil && len(*s.MeshOwner) < 12 {
invalidParams.Add(request.NewErrParamMinLen("MeshOwner", 12))
}
if s.Spec == nil {
invalidParams.Add(request.NewErrParamRequired("Spec"))
}
if s.VirtualGatewayName == nil {
invalidParams.Add(request.NewErrParamRequired("VirtualGatewayName"))
}
if s.VirtualGatewayName != nil && len(*s.VirtualGatewayName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("VirtualGatewayName", 1))
}
if s.Spec != nil {
if err := s.Spec.Validate(); err != nil {
invalidParams.AddNested("Spec", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetClientToken sets the ClientToken field's value.
func (s *UpdateGatewayRouteInput) SetClientToken(v string) *UpdateGatewayRouteInput {
s.ClientToken = &v
return s
}
// SetGatewayRouteName sets the GatewayRouteName field's value.
func (s *UpdateGatewayRouteInput) SetGatewayRouteName(v string) *UpdateGatewayRouteInput {
s.GatewayRouteName = &v
return s
}
// SetMeshName sets the MeshName field's value.
func (s *UpdateGatewayRouteInput) SetMeshName(v string) *UpdateGatewayRouteInput {
s.MeshName = &v
return s
}
// SetMeshOwner sets the MeshOwner field's value.
func (s *UpdateGatewayRouteInput) SetMeshOwner(v string) *UpdateGatewayRouteInput {
s.MeshOwner = &v
return s
}
// SetSpec sets the Spec field's value.
func (s *UpdateGatewayRouteInput) SetSpec(v *GatewayRouteSpec) *UpdateGatewayRouteInput {
s.Spec = v
return s
}
// SetVirtualGatewayName sets the VirtualGatewayName field's value.
func (s *UpdateGatewayRouteInput) SetVirtualGatewayName(v string) *UpdateGatewayRouteInput {
s.VirtualGatewayName = &v
return s
}
type UpdateGatewayRouteOutput struct {
_ struct{} `type:"structure" payload:"GatewayRoute"`
// A full description of the gateway route that was updated.
//
// GatewayRoute is a required field
GatewayRoute *GatewayRouteData `locationName:"gatewayRoute" type:"structure" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s UpdateGatewayRouteOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s UpdateGatewayRouteOutput) GoString() string {
return s.String()
}
// SetGatewayRoute sets the GatewayRoute field's value.
func (s *UpdateGatewayRouteOutput) SetGatewayRoute(v *GatewayRouteData) *UpdateGatewayRouteOutput {
s.GatewayRoute = v
return s
}
type UpdateMeshInput struct {
_ struct{} `type:"structure"`
// Unique, case-sensitive identifier that you provide to ensure the idempotency
// of the request. Up to 36 letters, numbers, hyphens, and underscores are allowed.
ClientToken *string `locationName:"clientToken" type:"string" idempotencyToken:"true"`
// The name of the service mesh to update.
//
// MeshName is a required field
MeshName *string `location:"uri" locationName:"meshName" min:"1" type:"string" required:"true"`
// The service mesh specification to apply.
Spec *MeshSpec `locationName:"spec" type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s UpdateMeshInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s UpdateMeshInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *UpdateMeshInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "UpdateMeshInput"}
if s.MeshName == nil {
invalidParams.Add(request.NewErrParamRequired("MeshName"))
}
if s.MeshName != nil && len(*s.MeshName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("MeshName", 1))
}
if s.Spec != nil {
if err := s.Spec.Validate(); err != nil {
invalidParams.AddNested("Spec", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetClientToken sets the ClientToken field's value.
func (s *UpdateMeshInput) SetClientToken(v string) *UpdateMeshInput {
s.ClientToken = &v
return s
}
// SetMeshName sets the MeshName field's value.
func (s *UpdateMeshInput) SetMeshName(v string) *UpdateMeshInput {
s.MeshName = &v
return s
}
// SetSpec sets the Spec field's value.
func (s *UpdateMeshInput) SetSpec(v *MeshSpec) *UpdateMeshInput {
s.Spec = v
return s
}
type UpdateMeshOutput struct {
_ struct{} `type:"structure" payload:"Mesh"`
// An object that represents a service mesh returned by a describe operation.
//
// Mesh is a required field
Mesh *MeshData `locationName:"mesh" type:"structure" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s UpdateMeshOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s UpdateMeshOutput) GoString() string {
return s.String()
}
// SetMesh sets the Mesh field's value.
func (s *UpdateMeshOutput) SetMesh(v *MeshData) *UpdateMeshOutput {
s.Mesh = v
return s
}
type UpdateRouteInput struct {
_ struct{} `type:"structure"`
// Unique, case-sensitive identifier that you provide to ensure the idempotency
// of the request. Up to 36 letters, numbers, hyphens, and underscores are allowed.
ClientToken *string `locationName:"clientToken" type:"string" idempotencyToken:"true"`
// The name of the service mesh that the route resides in.
//
// MeshName is a required field
MeshName *string `location:"uri" locationName:"meshName" min:"1" type:"string" required:"true"`
// The AWS IAM account ID of the service mesh owner. If the account ID is not
// your own, then it's the ID of the account that shared the mesh with your
// account. For more information about mesh sharing, see Working with shared
// meshes (https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html).
MeshOwner *string `location:"querystring" locationName:"meshOwner" min:"12" type:"string"`
// The name of the route to update.
//
// RouteName is a required field
RouteName *string `location:"uri" locationName:"routeName" min:"1" type:"string" required:"true"`
// The new route specification to apply. This overwrites the existing data.
//
// Spec is a required field
Spec *RouteSpec `locationName:"spec" type:"structure" required:"true"`
// The name of the virtual router that the route is associated with.
//
// VirtualRouterName is a required field
VirtualRouterName *string `location:"uri" locationName:"virtualRouterName" min:"1" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s UpdateRouteInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s UpdateRouteInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *UpdateRouteInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "UpdateRouteInput"}
if s.MeshName == nil {
invalidParams.Add(request.NewErrParamRequired("MeshName"))
}
if s.MeshName != nil && len(*s.MeshName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("MeshName", 1))
}
if s.MeshOwner != nil && len(*s.MeshOwner) < 12 {
invalidParams.Add(request.NewErrParamMinLen("MeshOwner", 12))
}
if s.RouteName == nil {
invalidParams.Add(request.NewErrParamRequired("RouteName"))
}
if s.RouteName != nil && len(*s.RouteName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("RouteName", 1))
}
if s.Spec == nil {
invalidParams.Add(request.NewErrParamRequired("Spec"))
}
if s.VirtualRouterName == nil {
invalidParams.Add(request.NewErrParamRequired("VirtualRouterName"))
}
if s.VirtualRouterName != nil && len(*s.VirtualRouterName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("VirtualRouterName", 1))
}
if s.Spec != nil {
if err := s.Spec.Validate(); err != nil {
invalidParams.AddNested("Spec", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetClientToken sets the ClientToken field's value.
func (s *UpdateRouteInput) SetClientToken(v string) *UpdateRouteInput {
s.ClientToken = &v
return s
}
// SetMeshName sets the MeshName field's value.
func (s *UpdateRouteInput) SetMeshName(v string) *UpdateRouteInput {
s.MeshName = &v
return s
}
// SetMeshOwner sets the MeshOwner field's value.
func (s *UpdateRouteInput) SetMeshOwner(v string) *UpdateRouteInput {
s.MeshOwner = &v
return s
}
// SetRouteName sets the RouteName field's value.
func (s *UpdateRouteInput) SetRouteName(v string) *UpdateRouteInput {
s.RouteName = &v
return s
}
// SetSpec sets the Spec field's value.
func (s *UpdateRouteInput) SetSpec(v *RouteSpec) *UpdateRouteInput {
s.Spec = v
return s
}
// SetVirtualRouterName sets the VirtualRouterName field's value.
func (s *UpdateRouteInput) SetVirtualRouterName(v string) *UpdateRouteInput {
s.VirtualRouterName = &v
return s
}
type UpdateRouteOutput struct {
_ struct{} `type:"structure" payload:"Route"`
// A full description of the route that was updated.
//
// Route is a required field
Route *RouteData `locationName:"route" type:"structure" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s UpdateRouteOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s UpdateRouteOutput) GoString() string {
return s.String()
}
// SetRoute sets the Route field's value.
func (s *UpdateRouteOutput) SetRoute(v *RouteData) *UpdateRouteOutput {
s.Route = v
return s
}
type UpdateVirtualGatewayInput struct {
_ struct{} `type:"structure"`
// Unique, case-sensitive identifier that you provide to ensure the idempotency
// of the request. Up to 36 letters, numbers, hyphens, and underscores are allowed.
ClientToken *string `locationName:"clientToken" type:"string" idempotencyToken:"true"`
// The name of the service mesh that the virtual gateway resides in.
//
// MeshName is a required field
MeshName *string `location:"uri" locationName:"meshName" min:"1" type:"string" required:"true"`
// The AWS IAM account ID of the service mesh owner. If the account ID is not
// your own, then it's the ID of the account that shared the mesh with your
// account. For more information about mesh sharing, see Working with shared
// meshes (https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html).
MeshOwner *string `location:"querystring" locationName:"meshOwner" min:"12" type:"string"`
// The new virtual gateway specification to apply. This overwrites the existing
// data.
//
// Spec is a required field
Spec *VirtualGatewaySpec `locationName:"spec" type:"structure" required:"true"`
// The name of the virtual gateway to update.
//
// VirtualGatewayName is a required field
VirtualGatewayName *string `location:"uri" locationName:"virtualGatewayName" min:"1" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s UpdateVirtualGatewayInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s UpdateVirtualGatewayInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *UpdateVirtualGatewayInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "UpdateVirtualGatewayInput"}
if s.MeshName == nil {
invalidParams.Add(request.NewErrParamRequired("MeshName"))
}
if s.MeshName != nil && len(*s.MeshName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("MeshName", 1))
}
if s.MeshOwner != nil && len(*s.MeshOwner) < 12 {
invalidParams.Add(request.NewErrParamMinLen("MeshOwner", 12))
}
if s.Spec == nil {
invalidParams.Add(request.NewErrParamRequired("Spec"))
}
if s.VirtualGatewayName == nil {
invalidParams.Add(request.NewErrParamRequired("VirtualGatewayName"))
}
if s.VirtualGatewayName != nil && len(*s.VirtualGatewayName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("VirtualGatewayName", 1))
}
if s.Spec != nil {
if err := s.Spec.Validate(); err != nil {
invalidParams.AddNested("Spec", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetClientToken sets the ClientToken field's value.
func (s *UpdateVirtualGatewayInput) SetClientToken(v string) *UpdateVirtualGatewayInput {
s.ClientToken = &v
return s
}
// SetMeshName sets the MeshName field's value.
func (s *UpdateVirtualGatewayInput) SetMeshName(v string) *UpdateVirtualGatewayInput {
s.MeshName = &v
return s
}
// SetMeshOwner sets the MeshOwner field's value.
func (s *UpdateVirtualGatewayInput) SetMeshOwner(v string) *UpdateVirtualGatewayInput {
s.MeshOwner = &v
return s
}
// SetSpec sets the Spec field's value.
func (s *UpdateVirtualGatewayInput) SetSpec(v *VirtualGatewaySpec) *UpdateVirtualGatewayInput {
s.Spec = v
return s
}
// SetVirtualGatewayName sets the VirtualGatewayName field's value.
func (s *UpdateVirtualGatewayInput) SetVirtualGatewayName(v string) *UpdateVirtualGatewayInput {
s.VirtualGatewayName = &v
return s
}
type UpdateVirtualGatewayOutput struct {
_ struct{} `type:"structure" payload:"VirtualGateway"`
// A full description of the virtual gateway that was updated.
//
// VirtualGateway is a required field
VirtualGateway *VirtualGatewayData `locationName:"virtualGateway" type:"structure" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s UpdateVirtualGatewayOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s UpdateVirtualGatewayOutput) GoString() string {
return s.String()
}
// SetVirtualGateway sets the VirtualGateway field's value.
func (s *UpdateVirtualGatewayOutput) SetVirtualGateway(v *VirtualGatewayData) *UpdateVirtualGatewayOutput {
s.VirtualGateway = v
return s
}
type UpdateVirtualNodeInput struct {
_ struct{} `type:"structure"`
// Unique, case-sensitive identifier that you provide to ensure the idempotency
// of the request. Up to 36 letters, numbers, hyphens, and underscores are allowed.
ClientToken *string `locationName:"clientToken" type:"string" idempotencyToken:"true"`
// The name of the service mesh that the virtual node resides in.
//
// MeshName is a required field
MeshName *string `location:"uri" locationName:"meshName" min:"1" type:"string" required:"true"`
// The AWS IAM account ID of the service mesh owner. If the account ID is not
// your own, then it's the ID of the account that shared the mesh with your
// account. For more information about mesh sharing, see Working with shared
// meshes (https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html).
MeshOwner *string `location:"querystring" locationName:"meshOwner" min:"12" type:"string"`
// The new virtual node specification to apply. This overwrites the existing
// data.
//
// Spec is a required field
Spec *VirtualNodeSpec `locationName:"spec" type:"structure" required:"true"`
// The name of the virtual node to update.
//
// VirtualNodeName is a required field
VirtualNodeName *string `location:"uri" locationName:"virtualNodeName" min:"1" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s UpdateVirtualNodeInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s UpdateVirtualNodeInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *UpdateVirtualNodeInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "UpdateVirtualNodeInput"}
if s.MeshName == nil {
invalidParams.Add(request.NewErrParamRequired("MeshName"))
}
if s.MeshName != nil && len(*s.MeshName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("MeshName", 1))
}
if s.MeshOwner != nil && len(*s.MeshOwner) < 12 {
invalidParams.Add(request.NewErrParamMinLen("MeshOwner", 12))
}
if s.Spec == nil {
invalidParams.Add(request.NewErrParamRequired("Spec"))
}
if s.VirtualNodeName == nil {
invalidParams.Add(request.NewErrParamRequired("VirtualNodeName"))
}
if s.VirtualNodeName != nil && len(*s.VirtualNodeName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("VirtualNodeName", 1))
}
if s.Spec != nil {
if err := s.Spec.Validate(); err != nil {
invalidParams.AddNested("Spec", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetClientToken sets the ClientToken field's value.
func (s *UpdateVirtualNodeInput) SetClientToken(v string) *UpdateVirtualNodeInput {
s.ClientToken = &v
return s
}
// SetMeshName sets the MeshName field's value.
func (s *UpdateVirtualNodeInput) SetMeshName(v string) *UpdateVirtualNodeInput {
s.MeshName = &v
return s
}
// SetMeshOwner sets the MeshOwner field's value.
func (s *UpdateVirtualNodeInput) SetMeshOwner(v string) *UpdateVirtualNodeInput {
s.MeshOwner = &v
return s
}
// SetSpec sets the Spec field's value.
func (s *UpdateVirtualNodeInput) SetSpec(v *VirtualNodeSpec) *UpdateVirtualNodeInput {
s.Spec = v
return s
}
// SetVirtualNodeName sets the VirtualNodeName field's value.
func (s *UpdateVirtualNodeInput) SetVirtualNodeName(v string) *UpdateVirtualNodeInput {
s.VirtualNodeName = &v
return s
}
type UpdateVirtualNodeOutput struct {
_ struct{} `type:"structure" payload:"VirtualNode"`
// A full description of the virtual node that was updated.
//
// VirtualNode is a required field
VirtualNode *VirtualNodeData `locationName:"virtualNode" type:"structure" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s UpdateVirtualNodeOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s UpdateVirtualNodeOutput) GoString() string {
return s.String()
}
// SetVirtualNode sets the VirtualNode field's value.
func (s *UpdateVirtualNodeOutput) SetVirtualNode(v *VirtualNodeData) *UpdateVirtualNodeOutput {
s.VirtualNode = v
return s
}
type UpdateVirtualRouterInput struct {
_ struct{} `type:"structure"`
// Unique, case-sensitive identifier that you provide to ensure the idempotency
// of the request. Up to 36 letters, numbers, hyphens, and underscores are allowed.
ClientToken *string `locationName:"clientToken" type:"string" idempotencyToken:"true"`
// The name of the service mesh that the virtual router resides in.
//
// MeshName is a required field
MeshName *string `location:"uri" locationName:"meshName" min:"1" type:"string" required:"true"`
// The AWS IAM account ID of the service mesh owner. If the account ID is not
// your own, then it's the ID of the account that shared the mesh with your
// account. For more information about mesh sharing, see Working with shared
// meshes (https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html).
MeshOwner *string `location:"querystring" locationName:"meshOwner" min:"12" type:"string"`
// The new virtual router specification to apply. This overwrites the existing
// data.
//
// Spec is a required field
Spec *VirtualRouterSpec `locationName:"spec" type:"structure" required:"true"`
// The name of the virtual router to update.
//
// VirtualRouterName is a required field
VirtualRouterName *string `location:"uri" locationName:"virtualRouterName" min:"1" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s UpdateVirtualRouterInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s UpdateVirtualRouterInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *UpdateVirtualRouterInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "UpdateVirtualRouterInput"}
if s.MeshName == nil {
invalidParams.Add(request.NewErrParamRequired("MeshName"))
}
if s.MeshName != nil && len(*s.MeshName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("MeshName", 1))
}
if s.MeshOwner != nil && len(*s.MeshOwner) < 12 {
invalidParams.Add(request.NewErrParamMinLen("MeshOwner", 12))
}
if s.Spec == nil {
invalidParams.Add(request.NewErrParamRequired("Spec"))
}
if s.VirtualRouterName == nil {
invalidParams.Add(request.NewErrParamRequired("VirtualRouterName"))
}
if s.VirtualRouterName != nil && len(*s.VirtualRouterName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("VirtualRouterName", 1))
}
if s.Spec != nil {
if err := s.Spec.Validate(); err != nil {
invalidParams.AddNested("Spec", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetClientToken sets the ClientToken field's value.
func (s *UpdateVirtualRouterInput) SetClientToken(v string) *UpdateVirtualRouterInput {
s.ClientToken = &v
return s
}
// SetMeshName sets the MeshName field's value.
func (s *UpdateVirtualRouterInput) SetMeshName(v string) *UpdateVirtualRouterInput {
s.MeshName = &v
return s
}
// SetMeshOwner sets the MeshOwner field's value.
func (s *UpdateVirtualRouterInput) SetMeshOwner(v string) *UpdateVirtualRouterInput {
s.MeshOwner = &v
return s
}
// SetSpec sets the Spec field's value.
func (s *UpdateVirtualRouterInput) SetSpec(v *VirtualRouterSpec) *UpdateVirtualRouterInput {
s.Spec = v
return s
}
// SetVirtualRouterName sets the VirtualRouterName field's value.
func (s *UpdateVirtualRouterInput) SetVirtualRouterName(v string) *UpdateVirtualRouterInput {
s.VirtualRouterName = &v
return s
}
type UpdateVirtualRouterOutput struct {
_ struct{} `type:"structure" payload:"VirtualRouter"`
// A full description of the virtual router that was updated.
//
// VirtualRouter is a required field
VirtualRouter *VirtualRouterData `locationName:"virtualRouter" type:"structure" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s UpdateVirtualRouterOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s UpdateVirtualRouterOutput) GoString() string {
return s.String()
}
// SetVirtualRouter sets the VirtualRouter field's value.
func (s *UpdateVirtualRouterOutput) SetVirtualRouter(v *VirtualRouterData) *UpdateVirtualRouterOutput {
s.VirtualRouter = v
return s
}
type UpdateVirtualServiceInput struct {
_ struct{} `type:"structure"`
// Unique, case-sensitive identifier that you provide to ensure the idempotency
// of the request. Up to 36 letters, numbers, hyphens, and underscores are allowed.
ClientToken *string `locationName:"clientToken" type:"string" idempotencyToken:"true"`
// The name of the service mesh that the virtual service resides in.
//
// MeshName is a required field
MeshName *string `location:"uri" locationName:"meshName" min:"1" type:"string" required:"true"`
// The AWS IAM account ID of the service mesh owner. If the account ID is not
// your own, then it's the ID of the account that shared the mesh with your
// account. For more information about mesh sharing, see Working with shared
// meshes (https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html).
MeshOwner *string `location:"querystring" locationName:"meshOwner" min:"12" type:"string"`
// The new virtual service specification to apply. This overwrites the existing
// data.
//
// Spec is a required field
Spec *VirtualServiceSpec `locationName:"spec" type:"structure" required:"true"`
// The name of the virtual service to update.
//
// VirtualServiceName is a required field
VirtualServiceName *string `location:"uri" locationName:"virtualServiceName" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s UpdateVirtualServiceInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s UpdateVirtualServiceInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *UpdateVirtualServiceInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "UpdateVirtualServiceInput"}
if s.MeshName == nil {
invalidParams.Add(request.NewErrParamRequired("MeshName"))
}
if s.MeshName != nil && len(*s.MeshName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("MeshName", 1))
}
if s.MeshOwner != nil && len(*s.MeshOwner) < 12 {
invalidParams.Add(request.NewErrParamMinLen("MeshOwner", 12))
}
if s.Spec == nil {
invalidParams.Add(request.NewErrParamRequired("Spec"))
}
if s.VirtualServiceName == nil {
invalidParams.Add(request.NewErrParamRequired("VirtualServiceName"))
}
if s.VirtualServiceName != nil && len(*s.VirtualServiceName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("VirtualServiceName", 1))
}
if s.Spec != nil {
if err := s.Spec.Validate(); err != nil {
invalidParams.AddNested("Spec", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetClientToken sets the ClientToken field's value.
func (s *UpdateVirtualServiceInput) SetClientToken(v string) *UpdateVirtualServiceInput {
s.ClientToken = &v
return s
}
// SetMeshName sets the MeshName field's value.
func (s *UpdateVirtualServiceInput) SetMeshName(v string) *UpdateVirtualServiceInput {
s.MeshName = &v
return s
}
// SetMeshOwner sets the MeshOwner field's value.
func (s *UpdateVirtualServiceInput) SetMeshOwner(v string) *UpdateVirtualServiceInput {
s.MeshOwner = &v
return s
}
// SetSpec sets the Spec field's value.
func (s *UpdateVirtualServiceInput) SetSpec(v *VirtualServiceSpec) *UpdateVirtualServiceInput {
s.Spec = v
return s
}
// SetVirtualServiceName sets the VirtualServiceName field's value.
func (s *UpdateVirtualServiceInput) SetVirtualServiceName(v string) *UpdateVirtualServiceInput {
s.VirtualServiceName = &v
return s
}
type UpdateVirtualServiceOutput struct {
_ struct{} `type:"structure" payload:"VirtualService"`
// A full description of the virtual service that was updated.
//
// VirtualService is a required field
VirtualService *VirtualServiceData `locationName:"virtualService" type:"structure" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s UpdateVirtualServiceOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s UpdateVirtualServiceOutput) GoString() string {
return s.String()
}
// SetVirtualService sets the VirtualService field's value.
func (s *UpdateVirtualServiceOutput) SetVirtualService(v *VirtualServiceData) *UpdateVirtualServiceOutput {
s.VirtualService = v
return s
}
// The access log configuration for a virtual gateway.
type VirtualGatewayAccessLog struct {
_ struct{} `type:"structure"`
// The file object to send virtual gateway access logs to.
File *VirtualGatewayFileAccessLog `locationName:"file" type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualGatewayAccessLog) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualGatewayAccessLog) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *VirtualGatewayAccessLog) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "VirtualGatewayAccessLog"}
if s.File != nil {
if err := s.File.Validate(); err != nil {
invalidParams.AddNested("File", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetFile sets the File field's value.
func (s *VirtualGatewayAccessLog) SetFile(v *VirtualGatewayFileAccessLog) *VirtualGatewayAccessLog {
s.File = v
return s
}
// An object that represents the default properties for a backend.
type VirtualGatewayBackendDefaults struct {
_ struct{} `type:"structure"`
// A reference to an object that represents a client policy.
ClientPolicy *VirtualGatewayClientPolicy `locationName:"clientPolicy" type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualGatewayBackendDefaults) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualGatewayBackendDefaults) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *VirtualGatewayBackendDefaults) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "VirtualGatewayBackendDefaults"}
if s.ClientPolicy != nil {
if err := s.ClientPolicy.Validate(); err != nil {
invalidParams.AddNested("ClientPolicy", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetClientPolicy sets the ClientPolicy field's value.
func (s *VirtualGatewayBackendDefaults) SetClientPolicy(v *VirtualGatewayClientPolicy) *VirtualGatewayBackendDefaults {
s.ClientPolicy = v
return s
}
// An object that represents a client policy.
type VirtualGatewayClientPolicy struct {
_ struct{} `type:"structure"`
// A reference to an object that represents a Transport Layer Security (TLS)
// client policy.
Tls *VirtualGatewayClientPolicyTls `locationName:"tls" type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualGatewayClientPolicy) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualGatewayClientPolicy) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *VirtualGatewayClientPolicy) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "VirtualGatewayClientPolicy"}
if s.Tls != nil {
if err := s.Tls.Validate(); err != nil {
invalidParams.AddNested("Tls", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetTls sets the Tls field's value.
func (s *VirtualGatewayClientPolicy) SetTls(v *VirtualGatewayClientPolicyTls) *VirtualGatewayClientPolicy {
s.Tls = v
return s
}
// An object that represents a Transport Layer Security (TLS) client policy.
type VirtualGatewayClientPolicyTls struct {
_ struct{} `type:"structure"`
// A reference to an object that represents a virtual gateway's client's Transport
// Layer Security (TLS) certificate.
Certificate *VirtualGatewayClientTlsCertificate `locationName:"certificate" type:"structure"`
// Whether the policy is enforced. The default is True, if a value isn't specified.
Enforce *bool `locationName:"enforce" type:"boolean"`
// One or more ports that the policy is enforced for.
Ports []*int64 `locationName:"ports" type:"list"`
// A reference to an object that represents a Transport Layer Security (TLS)
// validation context.
//
// Validation is a required field
Validation *VirtualGatewayTlsValidationContext `locationName:"validation" type:"structure" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualGatewayClientPolicyTls) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualGatewayClientPolicyTls) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *VirtualGatewayClientPolicyTls) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "VirtualGatewayClientPolicyTls"}
if s.Validation == nil {
invalidParams.Add(request.NewErrParamRequired("Validation"))
}
if s.Certificate != nil {
if err := s.Certificate.Validate(); err != nil {
invalidParams.AddNested("Certificate", err.(request.ErrInvalidParams))
}
}
if s.Validation != nil {
if err := s.Validation.Validate(); err != nil {
invalidParams.AddNested("Validation", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetCertificate sets the Certificate field's value.
func (s *VirtualGatewayClientPolicyTls) SetCertificate(v *VirtualGatewayClientTlsCertificate) *VirtualGatewayClientPolicyTls {
s.Certificate = v
return s
}
// SetEnforce sets the Enforce field's value.
func (s *VirtualGatewayClientPolicyTls) SetEnforce(v bool) *VirtualGatewayClientPolicyTls {
s.Enforce = &v
return s
}
// SetPorts sets the Ports field's value.
func (s *VirtualGatewayClientPolicyTls) SetPorts(v []*int64) *VirtualGatewayClientPolicyTls {
s.Ports = v
return s
}
// SetValidation sets the Validation field's value.
func (s *VirtualGatewayClientPolicyTls) SetValidation(v *VirtualGatewayTlsValidationContext) *VirtualGatewayClientPolicyTls {
s.Validation = v
return s
}
// An object that represents the virtual gateway's client's Transport Layer
// Security (TLS) certificate.
type VirtualGatewayClientTlsCertificate struct {
_ struct{} `type:"structure"`
// An object that represents a local file certificate. The certificate must
// meet specific requirements and you must have proxy authorization enabled.
// For more information, see Transport Layer Security (TLS) (https://docs.aws.amazon.com/app-mesh/latest/userguide/tls.html).
File *VirtualGatewayListenerTlsFileCertificate `locationName:"file" type:"structure"`
// A reference to an object that represents a virtual gateway's client's Secret
// Discovery Service certificate.
Sds *VirtualGatewayListenerTlsSdsCertificate `locationName:"sds" type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualGatewayClientTlsCertificate) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualGatewayClientTlsCertificate) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *VirtualGatewayClientTlsCertificate) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "VirtualGatewayClientTlsCertificate"}
if s.File != nil {
if err := s.File.Validate(); err != nil {
invalidParams.AddNested("File", err.(request.ErrInvalidParams))
}
}
if s.Sds != nil {
if err := s.Sds.Validate(); err != nil {
invalidParams.AddNested("Sds", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetFile sets the File field's value.
func (s *VirtualGatewayClientTlsCertificate) SetFile(v *VirtualGatewayListenerTlsFileCertificate) *VirtualGatewayClientTlsCertificate {
s.File = v
return s
}
// SetSds sets the Sds field's value.
func (s *VirtualGatewayClientTlsCertificate) SetSds(v *VirtualGatewayListenerTlsSdsCertificate) *VirtualGatewayClientTlsCertificate {
s.Sds = v
return s
}
// An object that represents the type of virtual gateway connection pool.
//
// Only one protocol is used at a time and should be the same protocol as the
// one chosen under port mapping.
//
// If not present the default value for maxPendingRequests is 2147483647.
type VirtualGatewayConnectionPool struct {
_ struct{} `type:"structure"`
// An object that represents a type of connection pool.
Grpc *VirtualGatewayGrpcConnectionPool `locationName:"grpc" type:"structure"`
// An object that represents a type of connection pool.
Http *VirtualGatewayHttpConnectionPool `locationName:"http" type:"structure"`
// An object that represents a type of connection pool.
Http2 *VirtualGatewayHttp2ConnectionPool `locationName:"http2" type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualGatewayConnectionPool) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualGatewayConnectionPool) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *VirtualGatewayConnectionPool) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "VirtualGatewayConnectionPool"}
if s.Grpc != nil {
if err := s.Grpc.Validate(); err != nil {
invalidParams.AddNested("Grpc", err.(request.ErrInvalidParams))
}
}
if s.Http != nil {
if err := s.Http.Validate(); err != nil {
invalidParams.AddNested("Http", err.(request.ErrInvalidParams))
}
}
if s.Http2 != nil {
if err := s.Http2.Validate(); err != nil {
invalidParams.AddNested("Http2", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetGrpc sets the Grpc field's value.
func (s *VirtualGatewayConnectionPool) SetGrpc(v *VirtualGatewayGrpcConnectionPool) *VirtualGatewayConnectionPool {
s.Grpc = v
return s
}
// SetHttp sets the Http field's value.
func (s *VirtualGatewayConnectionPool) SetHttp(v *VirtualGatewayHttpConnectionPool) *VirtualGatewayConnectionPool {
s.Http = v
return s
}
// SetHttp2 sets the Http2 field's value.
func (s *VirtualGatewayConnectionPool) SetHttp2(v *VirtualGatewayHttp2ConnectionPool) *VirtualGatewayConnectionPool {
s.Http2 = v
return s
}
// An object that represents a virtual gateway returned by a describe operation.
type VirtualGatewayData struct {
_ struct{} `type:"structure"`
// The name of the service mesh that the virtual gateway resides in.
//
// MeshName is a required field
MeshName *string `locationName:"meshName" min:"1" type:"string" required:"true"`
// An object that represents metadata for a resource.
//
// Metadata is a required field
Metadata *ResourceMetadata `locationName:"metadata" type:"structure" required:"true"`
// The specifications of the virtual gateway.
//
// Spec is a required field
Spec *VirtualGatewaySpec `locationName:"spec" type:"structure" required:"true"`
// The current status of the virtual gateway.
//
// Status is a required field
Status *VirtualGatewayStatus `locationName:"status" type:"structure" required:"true"`
// The name of the virtual gateway.
//
// VirtualGatewayName is a required field
VirtualGatewayName *string `locationName:"virtualGatewayName" min:"1" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualGatewayData) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualGatewayData) GoString() string {
return s.String()
}
// SetMeshName sets the MeshName field's value.
func (s *VirtualGatewayData) SetMeshName(v string) *VirtualGatewayData {
s.MeshName = &v
return s
}
// SetMetadata sets the Metadata field's value.
func (s *VirtualGatewayData) SetMetadata(v *ResourceMetadata) *VirtualGatewayData {
s.Metadata = v
return s
}
// SetSpec sets the Spec field's value.
func (s *VirtualGatewayData) SetSpec(v *VirtualGatewaySpec) *VirtualGatewayData {
s.Spec = v
return s
}
// SetStatus sets the Status field's value.
func (s *VirtualGatewayData) SetStatus(v *VirtualGatewayStatus) *VirtualGatewayData {
s.Status = v
return s
}
// SetVirtualGatewayName sets the VirtualGatewayName field's value.
func (s *VirtualGatewayData) SetVirtualGatewayName(v string) *VirtualGatewayData {
s.VirtualGatewayName = &v
return s
}
// An object that represents an access log file.
type VirtualGatewayFileAccessLog struct {
_ struct{} `type:"structure"`
// The file path to write access logs to. You can use /dev/stdout to send access
// logs to standard out and configure your Envoy container to use a log driver,
// such as awslogs, to export the access logs to a log storage service such
// as Amazon CloudWatch Logs. You can also specify a path in the Envoy container's
// file system to write the files to disk.
//
// Path is a required field
Path *string `locationName:"path" min:"1" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualGatewayFileAccessLog) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualGatewayFileAccessLog) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *VirtualGatewayFileAccessLog) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "VirtualGatewayFileAccessLog"}
if s.Path == nil {
invalidParams.Add(request.NewErrParamRequired("Path"))
}
if s.Path != nil && len(*s.Path) < 1 {
invalidParams.Add(request.NewErrParamMinLen("Path", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetPath sets the Path field's value.
func (s *VirtualGatewayFileAccessLog) SetPath(v string) *VirtualGatewayFileAccessLog {
s.Path = &v
return s
}
// An object that represents a type of connection pool.
type VirtualGatewayGrpcConnectionPool struct {
_ struct{} `type:"structure"`
// Maximum number of inflight requests Envoy can concurrently support across
// hosts in upstream cluster.
//
// MaxRequests is a required field
MaxRequests *int64 `locationName:"maxRequests" min:"1" type:"integer" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualGatewayGrpcConnectionPool) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualGatewayGrpcConnectionPool) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *VirtualGatewayGrpcConnectionPool) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "VirtualGatewayGrpcConnectionPool"}
if s.MaxRequests == nil {
invalidParams.Add(request.NewErrParamRequired("MaxRequests"))
}
if s.MaxRequests != nil && *s.MaxRequests < 1 {
invalidParams.Add(request.NewErrParamMinValue("MaxRequests", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetMaxRequests sets the MaxRequests field's value.
func (s *VirtualGatewayGrpcConnectionPool) SetMaxRequests(v int64) *VirtualGatewayGrpcConnectionPool {
s.MaxRequests = &v
return s
}
// An object that represents the health check policy for a virtual gateway's
// listener.
type VirtualGatewayHealthCheckPolicy struct {
_ struct{} `type:"structure"`
// The number of consecutive successful health checks that must occur before
// declaring the listener healthy.
//
// HealthyThreshold is a required field
HealthyThreshold *int64 `locationName:"healthyThreshold" min:"2" type:"integer" required:"true"`
// The time period in milliseconds between each health check execution.
//
// IntervalMillis is a required field
IntervalMillis *int64 `locationName:"intervalMillis" min:"5000" type:"long" required:"true"`
// The destination path for the health check request. This value is only used
// if the specified protocol is HTTP or HTTP/2. For any other protocol, this
// value is ignored.
Path *string `locationName:"path" type:"string"`
// The destination port for the health check request. This port must match the
// port defined in the PortMapping for the listener.
Port *int64 `locationName:"port" min:"1" type:"integer"`
// The protocol for the health check request. If you specify grpc, then your
// service must conform to the GRPC Health Checking Protocol (https://github.com/grpc/grpc/blob/master/doc/health-checking.md).
//
// Protocol is a required field
Protocol *string `locationName:"protocol" type:"string" required:"true" enum:"VirtualGatewayPortProtocol"`
// The amount of time to wait when receiving a response from the health check,
// in milliseconds.
//
// TimeoutMillis is a required field
TimeoutMillis *int64 `locationName:"timeoutMillis" min:"2000" type:"long" required:"true"`
// The number of consecutive failed health checks that must occur before declaring
// a virtual gateway unhealthy.
//
// UnhealthyThreshold is a required field
UnhealthyThreshold *int64 `locationName:"unhealthyThreshold" min:"2" type:"integer" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualGatewayHealthCheckPolicy) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualGatewayHealthCheckPolicy) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *VirtualGatewayHealthCheckPolicy) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "VirtualGatewayHealthCheckPolicy"}
if s.HealthyThreshold == nil {
invalidParams.Add(request.NewErrParamRequired("HealthyThreshold"))
}
if s.HealthyThreshold != nil && *s.HealthyThreshold < 2 {
invalidParams.Add(request.NewErrParamMinValue("HealthyThreshold", 2))
}
if s.IntervalMillis == nil {
invalidParams.Add(request.NewErrParamRequired("IntervalMillis"))
}
if s.IntervalMillis != nil && *s.IntervalMillis < 5000 {
invalidParams.Add(request.NewErrParamMinValue("IntervalMillis", 5000))
}
if s.Port != nil && *s.Port < 1 {
invalidParams.Add(request.NewErrParamMinValue("Port", 1))
}
if s.Protocol == nil {
invalidParams.Add(request.NewErrParamRequired("Protocol"))
}
if s.TimeoutMillis == nil {
invalidParams.Add(request.NewErrParamRequired("TimeoutMillis"))
}
if s.TimeoutMillis != nil && *s.TimeoutMillis < 2000 {
invalidParams.Add(request.NewErrParamMinValue("TimeoutMillis", 2000))
}
if s.UnhealthyThreshold == nil {
invalidParams.Add(request.NewErrParamRequired("UnhealthyThreshold"))
}
if s.UnhealthyThreshold != nil && *s.UnhealthyThreshold < 2 {
invalidParams.Add(request.NewErrParamMinValue("UnhealthyThreshold", 2))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetHealthyThreshold sets the HealthyThreshold field's value.
func (s *VirtualGatewayHealthCheckPolicy) SetHealthyThreshold(v int64) *VirtualGatewayHealthCheckPolicy {
s.HealthyThreshold = &v
return s
}
// SetIntervalMillis sets the IntervalMillis field's value.
func (s *VirtualGatewayHealthCheckPolicy) SetIntervalMillis(v int64) *VirtualGatewayHealthCheckPolicy {
s.IntervalMillis = &v
return s
}
// SetPath sets the Path field's value.
func (s *VirtualGatewayHealthCheckPolicy) SetPath(v string) *VirtualGatewayHealthCheckPolicy {
s.Path = &v
return s
}
// SetPort sets the Port field's value.
func (s *VirtualGatewayHealthCheckPolicy) SetPort(v int64) *VirtualGatewayHealthCheckPolicy {
s.Port = &v
return s
}
// SetProtocol sets the Protocol field's value.
func (s *VirtualGatewayHealthCheckPolicy) SetProtocol(v string) *VirtualGatewayHealthCheckPolicy {
s.Protocol = &v
return s
}
// SetTimeoutMillis sets the TimeoutMillis field's value.
func (s *VirtualGatewayHealthCheckPolicy) SetTimeoutMillis(v int64) *VirtualGatewayHealthCheckPolicy {
s.TimeoutMillis = &v
return s
}
// SetUnhealthyThreshold sets the UnhealthyThreshold field's value.
func (s *VirtualGatewayHealthCheckPolicy) SetUnhealthyThreshold(v int64) *VirtualGatewayHealthCheckPolicy {
s.UnhealthyThreshold = &v
return s
}
// An object that represents a type of connection pool.
type VirtualGatewayHttp2ConnectionPool struct {
_ struct{} `type:"structure"`
// Maximum number of inflight requests Envoy can concurrently support across
// hosts in upstream cluster.
//
// MaxRequests is a required field
MaxRequests *int64 `locationName:"maxRequests" min:"1" type:"integer" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualGatewayHttp2ConnectionPool) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualGatewayHttp2ConnectionPool) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *VirtualGatewayHttp2ConnectionPool) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "VirtualGatewayHttp2ConnectionPool"}
if s.MaxRequests == nil {
invalidParams.Add(request.NewErrParamRequired("MaxRequests"))
}
if s.MaxRequests != nil && *s.MaxRequests < 1 {
invalidParams.Add(request.NewErrParamMinValue("MaxRequests", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetMaxRequests sets the MaxRequests field's value.
func (s *VirtualGatewayHttp2ConnectionPool) SetMaxRequests(v int64) *VirtualGatewayHttp2ConnectionPool {
s.MaxRequests = &v
return s
}
// An object that represents a type of connection pool.
type VirtualGatewayHttpConnectionPool struct {
_ struct{} `type:"structure"`
// Maximum number of outbound TCP connections Envoy can establish concurrently
// with all hosts in upstream cluster.
//
// MaxConnections is a required field
MaxConnections *int64 `locationName:"maxConnections" min:"1" type:"integer" required:"true"`
// Number of overflowing requests after max_connections Envoy will queue to
// upstream cluster.
MaxPendingRequests *int64 `locationName:"maxPendingRequests" min:"1" type:"integer"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualGatewayHttpConnectionPool) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualGatewayHttpConnectionPool) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *VirtualGatewayHttpConnectionPool) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "VirtualGatewayHttpConnectionPool"}
if s.MaxConnections == nil {
invalidParams.Add(request.NewErrParamRequired("MaxConnections"))
}
if s.MaxConnections != nil && *s.MaxConnections < 1 {
invalidParams.Add(request.NewErrParamMinValue("MaxConnections", 1))
}
if s.MaxPendingRequests != nil && *s.MaxPendingRequests < 1 {
invalidParams.Add(request.NewErrParamMinValue("MaxPendingRequests", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetMaxConnections sets the MaxConnections field's value.
func (s *VirtualGatewayHttpConnectionPool) SetMaxConnections(v int64) *VirtualGatewayHttpConnectionPool {
s.MaxConnections = &v
return s
}
// SetMaxPendingRequests sets the MaxPendingRequests field's value.
func (s *VirtualGatewayHttpConnectionPool) SetMaxPendingRequests(v int64) *VirtualGatewayHttpConnectionPool {
s.MaxPendingRequests = &v
return s
}
// An object that represents a listener for a virtual gateway.
type VirtualGatewayListener struct {
_ struct{} `type:"structure"`
// The connection pool information for the virtual gateway listener.
ConnectionPool *VirtualGatewayConnectionPool `locationName:"connectionPool" type:"structure"`
// The health check information for the listener.
HealthCheck *VirtualGatewayHealthCheckPolicy `locationName:"healthCheck" type:"structure"`
// The port mapping information for the listener.
//
// PortMapping is a required field
PortMapping *VirtualGatewayPortMapping `locationName:"portMapping" type:"structure" required:"true"`
// A reference to an object that represents the Transport Layer Security (TLS)
// properties for the listener.
Tls *VirtualGatewayListenerTls `locationName:"tls" type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualGatewayListener) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualGatewayListener) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *VirtualGatewayListener) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "VirtualGatewayListener"}
if s.PortMapping == nil {
invalidParams.Add(request.NewErrParamRequired("PortMapping"))
}
if s.ConnectionPool != nil {
if err := s.ConnectionPool.Validate(); err != nil {
invalidParams.AddNested("ConnectionPool", err.(request.ErrInvalidParams))
}
}
if s.HealthCheck != nil {
if err := s.HealthCheck.Validate(); err != nil {
invalidParams.AddNested("HealthCheck", err.(request.ErrInvalidParams))
}
}
if s.PortMapping != nil {
if err := s.PortMapping.Validate(); err != nil {
invalidParams.AddNested("PortMapping", err.(request.ErrInvalidParams))
}
}
if s.Tls != nil {
if err := s.Tls.Validate(); err != nil {
invalidParams.AddNested("Tls", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetConnectionPool sets the ConnectionPool field's value.
func (s *VirtualGatewayListener) SetConnectionPool(v *VirtualGatewayConnectionPool) *VirtualGatewayListener {
s.ConnectionPool = v
return s
}
// SetHealthCheck sets the HealthCheck field's value.
func (s *VirtualGatewayListener) SetHealthCheck(v *VirtualGatewayHealthCheckPolicy) *VirtualGatewayListener {
s.HealthCheck = v
return s
}
// SetPortMapping sets the PortMapping field's value.
func (s *VirtualGatewayListener) SetPortMapping(v *VirtualGatewayPortMapping) *VirtualGatewayListener {
s.PortMapping = v
return s
}
// SetTls sets the Tls field's value.
func (s *VirtualGatewayListener) SetTls(v *VirtualGatewayListenerTls) *VirtualGatewayListener {
s.Tls = v
return s
}
// An object that represents the Transport Layer Security (TLS) properties for
// a listener.
type VirtualGatewayListenerTls struct {
_ struct{} `type:"structure"`
// An object that represents a Transport Layer Security (TLS) certificate.
//
// Certificate is a required field
Certificate *VirtualGatewayListenerTlsCertificate `locationName:"certificate" type:"structure" required:"true"`
// Specify one of the following modes.
//
// * STRICT – Listener only accepts connections with TLS enabled.
//
// * PERMISSIVE – Listener accepts connections with or without TLS enabled.
//
// * DISABLED – Listener only accepts connections without TLS.
//
// Mode is a required field
Mode *string `locationName:"mode" type:"string" required:"true" enum:"VirtualGatewayListenerTlsMode"`
// A reference to an object that represents a virtual gateway's listener's Transport
// Layer Security (TLS) validation context.
Validation *VirtualGatewayListenerTlsValidationContext `locationName:"validation" type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualGatewayListenerTls) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualGatewayListenerTls) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *VirtualGatewayListenerTls) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "VirtualGatewayListenerTls"}
if s.Certificate == nil {
invalidParams.Add(request.NewErrParamRequired("Certificate"))
}
if s.Mode == nil {
invalidParams.Add(request.NewErrParamRequired("Mode"))
}
if s.Certificate != nil {
if err := s.Certificate.Validate(); err != nil {
invalidParams.AddNested("Certificate", err.(request.ErrInvalidParams))
}
}
if s.Validation != nil {
if err := s.Validation.Validate(); err != nil {
invalidParams.AddNested("Validation", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetCertificate sets the Certificate field's value.
func (s *VirtualGatewayListenerTls) SetCertificate(v *VirtualGatewayListenerTlsCertificate) *VirtualGatewayListenerTls {
s.Certificate = v
return s
}
// SetMode sets the Mode field's value.
func (s *VirtualGatewayListenerTls) SetMode(v string) *VirtualGatewayListenerTls {
s.Mode = &v
return s
}
// SetValidation sets the Validation field's value.
func (s *VirtualGatewayListenerTls) SetValidation(v *VirtualGatewayListenerTlsValidationContext) *VirtualGatewayListenerTls {
s.Validation = v
return s
}
// An object that represents an Certificate Manager certificate.
type VirtualGatewayListenerTlsAcmCertificate struct {
_ struct{} `type:"structure"`
// The Amazon Resource Name (ARN) for the certificate. The certificate must
// meet specific requirements and you must have proxy authorization enabled.
// For more information, see Transport Layer Security (TLS) (https://docs.aws.amazon.com/app-mesh/latest/userguide/tls.html#virtual-node-tls-prerequisites).
//
// CertificateArn is a required field
CertificateArn *string `locationName:"certificateArn" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualGatewayListenerTlsAcmCertificate) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualGatewayListenerTlsAcmCertificate) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *VirtualGatewayListenerTlsAcmCertificate) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "VirtualGatewayListenerTlsAcmCertificate"}
if s.CertificateArn == nil {
invalidParams.Add(request.NewErrParamRequired("CertificateArn"))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetCertificateArn sets the CertificateArn field's value.
func (s *VirtualGatewayListenerTlsAcmCertificate) SetCertificateArn(v string) *VirtualGatewayListenerTlsAcmCertificate {
s.CertificateArn = &v
return s
}
// An object that represents a listener's Transport Layer Security (TLS) certificate.
type VirtualGatewayListenerTlsCertificate struct {
_ struct{} `type:"structure"`
// A reference to an object that represents an Certificate Manager certificate.
Acm *VirtualGatewayListenerTlsAcmCertificate `locationName:"acm" type:"structure"`
// A reference to an object that represents a local file certificate.
File *VirtualGatewayListenerTlsFileCertificate `locationName:"file" type:"structure"`
// A reference to an object that represents a virtual gateway's listener's Secret
// Discovery Service certificate.
Sds *VirtualGatewayListenerTlsSdsCertificate `locationName:"sds" type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualGatewayListenerTlsCertificate) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualGatewayListenerTlsCertificate) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *VirtualGatewayListenerTlsCertificate) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "VirtualGatewayListenerTlsCertificate"}
if s.Acm != nil {
if err := s.Acm.Validate(); err != nil {
invalidParams.AddNested("Acm", err.(request.ErrInvalidParams))
}
}
if s.File != nil {
if err := s.File.Validate(); err != nil {
invalidParams.AddNested("File", err.(request.ErrInvalidParams))
}
}
if s.Sds != nil {
if err := s.Sds.Validate(); err != nil {
invalidParams.AddNested("Sds", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetAcm sets the Acm field's value.
func (s *VirtualGatewayListenerTlsCertificate) SetAcm(v *VirtualGatewayListenerTlsAcmCertificate) *VirtualGatewayListenerTlsCertificate {
s.Acm = v
return s
}
// SetFile sets the File field's value.
func (s *VirtualGatewayListenerTlsCertificate) SetFile(v *VirtualGatewayListenerTlsFileCertificate) *VirtualGatewayListenerTlsCertificate {
s.File = v
return s
}
// SetSds sets the Sds field's value.
func (s *VirtualGatewayListenerTlsCertificate) SetSds(v *VirtualGatewayListenerTlsSdsCertificate) *VirtualGatewayListenerTlsCertificate {
s.Sds = v
return s
}
// An object that represents a local file certificate. The certificate must
// meet specific requirements and you must have proxy authorization enabled.
// For more information, see Transport Layer Security (TLS) (https://docs.aws.amazon.com/app-mesh/latest/userguide/tls.html#virtual-node-tls-prerequisites).
type VirtualGatewayListenerTlsFileCertificate struct {
_ struct{} `type:"structure"`
// The certificate chain for the certificate.
//
// CertificateChain is a required field
CertificateChain *string `locationName:"certificateChain" min:"1" type:"string" required:"true"`
// The private key for a certificate stored on the file system of the mesh endpoint
// that the proxy is running on.
//
// PrivateKey is a required field
PrivateKey *string `locationName:"privateKey" min:"1" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualGatewayListenerTlsFileCertificate) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualGatewayListenerTlsFileCertificate) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *VirtualGatewayListenerTlsFileCertificate) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "VirtualGatewayListenerTlsFileCertificate"}
if s.CertificateChain == nil {
invalidParams.Add(request.NewErrParamRequired("CertificateChain"))
}
if s.CertificateChain != nil && len(*s.CertificateChain) < 1 {
invalidParams.Add(request.NewErrParamMinLen("CertificateChain", 1))
}
if s.PrivateKey == nil {
invalidParams.Add(request.NewErrParamRequired("PrivateKey"))
}
if s.PrivateKey != nil && len(*s.PrivateKey) < 1 {
invalidParams.Add(request.NewErrParamMinLen("PrivateKey", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetCertificateChain sets the CertificateChain field's value.
func (s *VirtualGatewayListenerTlsFileCertificate) SetCertificateChain(v string) *VirtualGatewayListenerTlsFileCertificate {
s.CertificateChain = &v
return s
}
// SetPrivateKey sets the PrivateKey field's value.
func (s *VirtualGatewayListenerTlsFileCertificate) SetPrivateKey(v string) *VirtualGatewayListenerTlsFileCertificate {
s.PrivateKey = &v
return s
}
// An object that represents the virtual gateway's listener's Secret Discovery
// Service certificate.The proxy must be configured with a local SDS provider
// via a Unix Domain Socket. See App MeshTLS documentation (https://docs.aws.amazon.com/app-mesh/latest/userguide/tls.html)
// for more info.
type VirtualGatewayListenerTlsSdsCertificate struct {
_ struct{} `type:"structure"`
// A reference to an object that represents the name of the secret secret requested
// from the Secret Discovery Service provider representing Transport Layer Security
// (TLS) materials like a certificate or certificate chain.
//
// SecretName is a required field
SecretName *string `locationName:"secretName" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualGatewayListenerTlsSdsCertificate) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualGatewayListenerTlsSdsCertificate) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *VirtualGatewayListenerTlsSdsCertificate) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "VirtualGatewayListenerTlsSdsCertificate"}
if s.SecretName == nil {
invalidParams.Add(request.NewErrParamRequired("SecretName"))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetSecretName sets the SecretName field's value.
func (s *VirtualGatewayListenerTlsSdsCertificate) SetSecretName(v string) *VirtualGatewayListenerTlsSdsCertificate {
s.SecretName = &v
return s
}
// An object that represents a virtual gateway's listener's Transport Layer
// Security (TLS) validation context.
type VirtualGatewayListenerTlsValidationContext struct {
_ struct{} `type:"structure"`
// A reference to an object that represents the SANs for a virtual gateway listener's
// Transport Layer Security (TLS) validation context.
SubjectAlternativeNames *SubjectAlternativeNames `locationName:"subjectAlternativeNames" type:"structure"`
// A reference to where to retrieve the trust chain when validating a peer’s
// Transport Layer Security (TLS) certificate.
//
// Trust is a required field
Trust *VirtualGatewayListenerTlsValidationContextTrust `locationName:"trust" type:"structure" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualGatewayListenerTlsValidationContext) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualGatewayListenerTlsValidationContext) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *VirtualGatewayListenerTlsValidationContext) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "VirtualGatewayListenerTlsValidationContext"}
if s.Trust == nil {
invalidParams.Add(request.NewErrParamRequired("Trust"))
}
if s.SubjectAlternativeNames != nil {
if err := s.SubjectAlternativeNames.Validate(); err != nil {
invalidParams.AddNested("SubjectAlternativeNames", err.(request.ErrInvalidParams))
}
}
if s.Trust != nil {
if err := s.Trust.Validate(); err != nil {
invalidParams.AddNested("Trust", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetSubjectAlternativeNames sets the SubjectAlternativeNames field's value.
func (s *VirtualGatewayListenerTlsValidationContext) SetSubjectAlternativeNames(v *SubjectAlternativeNames) *VirtualGatewayListenerTlsValidationContext {
s.SubjectAlternativeNames = v
return s
}
// SetTrust sets the Trust field's value.
func (s *VirtualGatewayListenerTlsValidationContext) SetTrust(v *VirtualGatewayListenerTlsValidationContextTrust) *VirtualGatewayListenerTlsValidationContext {
s.Trust = v
return s
}
// An object that represents a virtual gateway's listener's Transport Layer
// Security (TLS) validation context trust.
type VirtualGatewayListenerTlsValidationContextTrust struct {
_ struct{} `type:"structure"`
// An object that represents a Transport Layer Security (TLS) validation context
// trust for a local file.
File *VirtualGatewayTlsValidationContextFileTrust `locationName:"file" type:"structure"`
// A reference to an object that represents a virtual gateway's listener's Transport
// Layer Security (TLS) Secret Discovery Service validation context trust.
Sds *VirtualGatewayTlsValidationContextSdsTrust `locationName:"sds" type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualGatewayListenerTlsValidationContextTrust) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualGatewayListenerTlsValidationContextTrust) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *VirtualGatewayListenerTlsValidationContextTrust) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "VirtualGatewayListenerTlsValidationContextTrust"}
if s.File != nil {
if err := s.File.Validate(); err != nil {
invalidParams.AddNested("File", err.(request.ErrInvalidParams))
}
}
if s.Sds != nil {
if err := s.Sds.Validate(); err != nil {
invalidParams.AddNested("Sds", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetFile sets the File field's value.
func (s *VirtualGatewayListenerTlsValidationContextTrust) SetFile(v *VirtualGatewayTlsValidationContextFileTrust) *VirtualGatewayListenerTlsValidationContextTrust {
s.File = v
return s
}
// SetSds sets the Sds field's value.
func (s *VirtualGatewayListenerTlsValidationContextTrust) SetSds(v *VirtualGatewayTlsValidationContextSdsTrust) *VirtualGatewayListenerTlsValidationContextTrust {
s.Sds = v
return s
}
// An object that represents logging information.
type VirtualGatewayLogging struct {
_ struct{} `type:"structure"`
// The access log configuration.
AccessLog *VirtualGatewayAccessLog `locationName:"accessLog" type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualGatewayLogging) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualGatewayLogging) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *VirtualGatewayLogging) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "VirtualGatewayLogging"}
if s.AccessLog != nil {
if err := s.AccessLog.Validate(); err != nil {
invalidParams.AddNested("AccessLog", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetAccessLog sets the AccessLog field's value.
func (s *VirtualGatewayLogging) SetAccessLog(v *VirtualGatewayAccessLog) *VirtualGatewayLogging {
s.AccessLog = v
return s
}
// An object that represents a port mapping.
type VirtualGatewayPortMapping struct {
_ struct{} `type:"structure"`
// The port used for the port mapping. Specify one protocol.
//
// Port is a required field
Port *int64 `locationName:"port" min:"1" type:"integer" required:"true"`
// The protocol used for the port mapping.
//
// Protocol is a required field
Protocol *string `locationName:"protocol" type:"string" required:"true" enum:"VirtualGatewayPortProtocol"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualGatewayPortMapping) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualGatewayPortMapping) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *VirtualGatewayPortMapping) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "VirtualGatewayPortMapping"}
if s.Port == nil {
invalidParams.Add(request.NewErrParamRequired("Port"))
}
if s.Port != nil && *s.Port < 1 {
invalidParams.Add(request.NewErrParamMinValue("Port", 1))
}
if s.Protocol == nil {
invalidParams.Add(request.NewErrParamRequired("Protocol"))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetPort sets the Port field's value.
func (s *VirtualGatewayPortMapping) SetPort(v int64) *VirtualGatewayPortMapping {
s.Port = &v
return s
}
// SetProtocol sets the Protocol field's value.
func (s *VirtualGatewayPortMapping) SetProtocol(v string) *VirtualGatewayPortMapping {
s.Protocol = &v
return s
}
// An object that represents a virtual gateway returned by a list operation.
type VirtualGatewayRef struct {
_ struct{} `type:"structure"`
// The full Amazon Resource Name (ARN) for the resource.
//
// Arn is a required field
Arn *string `locationName:"arn" type:"string" required:"true"`
// The Unix epoch timestamp in seconds for when the resource was created.
//
// CreatedAt is a required field
CreatedAt *time.Time `locationName:"createdAt" type:"timestamp" required:"true"`
// The Unix epoch timestamp in seconds for when the resource was last updated.
//
// LastUpdatedAt is a required field
LastUpdatedAt *time.Time `locationName:"lastUpdatedAt" type:"timestamp" required:"true"`
// The name of the service mesh that the resource resides in.
//
// MeshName is a required field
MeshName *string `locationName:"meshName" min:"1" type:"string" required:"true"`
// The AWS IAM account ID of the service mesh owner. If the account ID is not
// your own, then it's the ID of the account that shared the mesh with your
// account. For more information about mesh sharing, see Working with shared
// meshes (https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html).
//
// MeshOwner is a required field
MeshOwner *string `locationName:"meshOwner" min:"12" type:"string" required:"true"`
// The AWS IAM account ID of the resource owner. If the account ID is not your
// own, then it's the ID of the mesh owner or of another account that the mesh
// is shared with. For more information about mesh sharing, see Working with
// shared meshes (https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html).
//
// ResourceOwner is a required field
ResourceOwner *string `locationName:"resourceOwner" min:"12" type:"string" required:"true"`
// The version of the resource. Resources are created at version 1, and this
// version is incremented each time that they're updated.
//
// Version is a required field
Version *int64 `locationName:"version" type:"long" required:"true"`
// The name of the resource.
//
// VirtualGatewayName is a required field
VirtualGatewayName *string `locationName:"virtualGatewayName" min:"1" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualGatewayRef) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualGatewayRef) GoString() string {
return s.String()
}
// SetArn sets the Arn field's value.
func (s *VirtualGatewayRef) SetArn(v string) *VirtualGatewayRef {
s.Arn = &v
return s
}
// SetCreatedAt sets the CreatedAt field's value.
func (s *VirtualGatewayRef) SetCreatedAt(v time.Time) *VirtualGatewayRef {
s.CreatedAt = &v
return s
}
// SetLastUpdatedAt sets the LastUpdatedAt field's value.
func (s *VirtualGatewayRef) SetLastUpdatedAt(v time.Time) *VirtualGatewayRef {
s.LastUpdatedAt = &v
return s
}
// SetMeshName sets the MeshName field's value.
func (s *VirtualGatewayRef) SetMeshName(v string) *VirtualGatewayRef {
s.MeshName = &v
return s
}
// SetMeshOwner sets the MeshOwner field's value.
func (s *VirtualGatewayRef) SetMeshOwner(v string) *VirtualGatewayRef {
s.MeshOwner = &v
return s
}
// SetResourceOwner sets the ResourceOwner field's value.
func (s *VirtualGatewayRef) SetResourceOwner(v string) *VirtualGatewayRef {
s.ResourceOwner = &v
return s
}
// SetVersion sets the Version field's value.
func (s *VirtualGatewayRef) SetVersion(v int64) *VirtualGatewayRef {
s.Version = &v
return s
}
// SetVirtualGatewayName sets the VirtualGatewayName field's value.
func (s *VirtualGatewayRef) SetVirtualGatewayName(v string) *VirtualGatewayRef {
s.VirtualGatewayName = &v
return s
}
// An object that represents the specification of a service mesh resource.
type VirtualGatewaySpec struct {
_ struct{} `type:"structure"`
// A reference to an object that represents the defaults for backends.
BackendDefaults *VirtualGatewayBackendDefaults `locationName:"backendDefaults" type:"structure"`
// The listeners that the mesh endpoint is expected to receive inbound traffic
// from. You can specify one listener.
//
// Listeners is a required field
Listeners []*VirtualGatewayListener `locationName:"listeners" type:"list" required:"true"`
// An object that represents logging information.
Logging *VirtualGatewayLogging `locationName:"logging" type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualGatewaySpec) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualGatewaySpec) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *VirtualGatewaySpec) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "VirtualGatewaySpec"}
if s.Listeners == nil {
invalidParams.Add(request.NewErrParamRequired("Listeners"))
}
if s.BackendDefaults != nil {
if err := s.BackendDefaults.Validate(); err != nil {
invalidParams.AddNested("BackendDefaults", err.(request.ErrInvalidParams))
}
}
if s.Listeners != nil {
for i, v := range s.Listeners {
if v == nil {
continue
}
if err := v.Validate(); err != nil {
invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Listeners", i), err.(request.ErrInvalidParams))
}
}
}
if s.Logging != nil {
if err := s.Logging.Validate(); err != nil {
invalidParams.AddNested("Logging", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetBackendDefaults sets the BackendDefaults field's value.
func (s *VirtualGatewaySpec) SetBackendDefaults(v *VirtualGatewayBackendDefaults) *VirtualGatewaySpec {
s.BackendDefaults = v
return s
}
// SetListeners sets the Listeners field's value.
func (s *VirtualGatewaySpec) SetListeners(v []*VirtualGatewayListener) *VirtualGatewaySpec {
s.Listeners = v
return s
}
// SetLogging sets the Logging field's value.
func (s *VirtualGatewaySpec) SetLogging(v *VirtualGatewayLogging) *VirtualGatewaySpec {
s.Logging = v
return s
}
// An object that represents the status of the mesh resource.
type VirtualGatewayStatus struct {
_ struct{} `type:"structure"`
// The current status.
//
// Status is a required field
Status *string `locationName:"status" type:"string" required:"true" enum:"VirtualGatewayStatusCode"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualGatewayStatus) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualGatewayStatus) GoString() string {
return s.String()
}
// SetStatus sets the Status field's value.
func (s *VirtualGatewayStatus) SetStatus(v string) *VirtualGatewayStatus {
s.Status = &v
return s
}
// An object that represents a Transport Layer Security (TLS) validation context.
type VirtualGatewayTlsValidationContext struct {
_ struct{} `type:"structure"`
// A reference to an object that represents the SANs for a virtual gateway's
// listener's Transport Layer Security (TLS) validation context.
SubjectAlternativeNames *SubjectAlternativeNames `locationName:"subjectAlternativeNames" type:"structure"`
// A reference to where to retrieve the trust chain when validating a peer’s
// Transport Layer Security (TLS) certificate.
//
// Trust is a required field
Trust *VirtualGatewayTlsValidationContextTrust `locationName:"trust" type:"structure" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualGatewayTlsValidationContext) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualGatewayTlsValidationContext) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *VirtualGatewayTlsValidationContext) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "VirtualGatewayTlsValidationContext"}
if s.Trust == nil {
invalidParams.Add(request.NewErrParamRequired("Trust"))
}
if s.SubjectAlternativeNames != nil {
if err := s.SubjectAlternativeNames.Validate(); err != nil {
invalidParams.AddNested("SubjectAlternativeNames", err.(request.ErrInvalidParams))
}
}
if s.Trust != nil {
if err := s.Trust.Validate(); err != nil {
invalidParams.AddNested("Trust", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetSubjectAlternativeNames sets the SubjectAlternativeNames field's value.
func (s *VirtualGatewayTlsValidationContext) SetSubjectAlternativeNames(v *SubjectAlternativeNames) *VirtualGatewayTlsValidationContext {
s.SubjectAlternativeNames = v
return s
}
// SetTrust sets the Trust field's value.
func (s *VirtualGatewayTlsValidationContext) SetTrust(v *VirtualGatewayTlsValidationContextTrust) *VirtualGatewayTlsValidationContext {
s.Trust = v
return s
}
// An object that represents a Transport Layer Security (TLS) validation context
// trust for an Certificate Manager certificate.
type VirtualGatewayTlsValidationContextAcmTrust struct {
_ struct{} `type:"structure"`
// One or more ACM Amazon Resource Name (ARN)s.
//
// CertificateAuthorityArns is a required field
CertificateAuthorityArns []*string `locationName:"certificateAuthorityArns" min:"1" type:"list" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualGatewayTlsValidationContextAcmTrust) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualGatewayTlsValidationContextAcmTrust) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *VirtualGatewayTlsValidationContextAcmTrust) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "VirtualGatewayTlsValidationContextAcmTrust"}
if s.CertificateAuthorityArns == nil {
invalidParams.Add(request.NewErrParamRequired("CertificateAuthorityArns"))
}
if s.CertificateAuthorityArns != nil && len(s.CertificateAuthorityArns) < 1 {
invalidParams.Add(request.NewErrParamMinLen("CertificateAuthorityArns", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetCertificateAuthorityArns sets the CertificateAuthorityArns field's value.
func (s *VirtualGatewayTlsValidationContextAcmTrust) SetCertificateAuthorityArns(v []*string) *VirtualGatewayTlsValidationContextAcmTrust {
s.CertificateAuthorityArns = v
return s
}
// An object that represents a Transport Layer Security (TLS) validation context
// trust for a local file.
type VirtualGatewayTlsValidationContextFileTrust struct {
_ struct{} `type:"structure"`
// The certificate trust chain for a certificate stored on the file system of
// the virtual node that the proxy is running on.
//
// CertificateChain is a required field
CertificateChain *string `locationName:"certificateChain" min:"1" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualGatewayTlsValidationContextFileTrust) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualGatewayTlsValidationContextFileTrust) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *VirtualGatewayTlsValidationContextFileTrust) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "VirtualGatewayTlsValidationContextFileTrust"}
if s.CertificateChain == nil {
invalidParams.Add(request.NewErrParamRequired("CertificateChain"))
}
if s.CertificateChain != nil && len(*s.CertificateChain) < 1 {
invalidParams.Add(request.NewErrParamMinLen("CertificateChain", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetCertificateChain sets the CertificateChain field's value.
func (s *VirtualGatewayTlsValidationContextFileTrust) SetCertificateChain(v string) *VirtualGatewayTlsValidationContextFileTrust {
s.CertificateChain = &v
return s
}
// An object that represents a virtual gateway's listener's Transport Layer
// Security (TLS) Secret Discovery Service validation context trust. The proxy
// must be configured with a local SDS provider via a Unix Domain Socket. See
// App Mesh TLS documentation (https://docs.aws.amazon.com/app-mesh/latest/userguide/tls.html)
// for more info.
type VirtualGatewayTlsValidationContextSdsTrust struct {
_ struct{} `type:"structure"`
// A reference to an object that represents the name of the secret for a virtual
// gateway's Transport Layer Security (TLS) Secret Discovery Service validation
// context trust.
//
// SecretName is a required field
SecretName *string `locationName:"secretName" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualGatewayTlsValidationContextSdsTrust) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualGatewayTlsValidationContextSdsTrust) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *VirtualGatewayTlsValidationContextSdsTrust) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "VirtualGatewayTlsValidationContextSdsTrust"}
if s.SecretName == nil {
invalidParams.Add(request.NewErrParamRequired("SecretName"))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetSecretName sets the SecretName field's value.
func (s *VirtualGatewayTlsValidationContextSdsTrust) SetSecretName(v string) *VirtualGatewayTlsValidationContextSdsTrust {
s.SecretName = &v
return s
}
// An object that represents a Transport Layer Security (TLS) validation context
// trust.
type VirtualGatewayTlsValidationContextTrust struct {
_ struct{} `type:"structure"`
// A reference to an object that represents a Transport Layer Security (TLS)
// validation context trust for an Certificate Manager certificate.
Acm *VirtualGatewayTlsValidationContextAcmTrust `locationName:"acm" type:"structure"`
// An object that represents a Transport Layer Security (TLS) validation context
// trust for a local file.
File *VirtualGatewayTlsValidationContextFileTrust `locationName:"file" type:"structure"`
// A reference to an object that represents a virtual gateway's Transport Layer
// Security (TLS) Secret Discovery Service validation context trust.
Sds *VirtualGatewayTlsValidationContextSdsTrust `locationName:"sds" type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualGatewayTlsValidationContextTrust) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualGatewayTlsValidationContextTrust) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *VirtualGatewayTlsValidationContextTrust) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "VirtualGatewayTlsValidationContextTrust"}
if s.Acm != nil {
if err := s.Acm.Validate(); err != nil {
invalidParams.AddNested("Acm", err.(request.ErrInvalidParams))
}
}
if s.File != nil {
if err := s.File.Validate(); err != nil {
invalidParams.AddNested("File", err.(request.ErrInvalidParams))
}
}
if s.Sds != nil {
if err := s.Sds.Validate(); err != nil {
invalidParams.AddNested("Sds", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetAcm sets the Acm field's value.
func (s *VirtualGatewayTlsValidationContextTrust) SetAcm(v *VirtualGatewayTlsValidationContextAcmTrust) *VirtualGatewayTlsValidationContextTrust {
s.Acm = v
return s
}
// SetFile sets the File field's value.
func (s *VirtualGatewayTlsValidationContextTrust) SetFile(v *VirtualGatewayTlsValidationContextFileTrust) *VirtualGatewayTlsValidationContextTrust {
s.File = v
return s
}
// SetSds sets the Sds field's value.
func (s *VirtualGatewayTlsValidationContextTrust) SetSds(v *VirtualGatewayTlsValidationContextSdsTrust) *VirtualGatewayTlsValidationContextTrust {
s.Sds = v
return s
}
// An object that represents the type of virtual node connection pool.
//
// Only one protocol is used at a time and should be the same protocol as the
// one chosen under port mapping.
//
// If not present the default value for maxPendingRequests is 2147483647.
type VirtualNodeConnectionPool struct {
_ struct{} `type:"structure"`
// An object that represents a type of connection pool.
Grpc *VirtualNodeGrpcConnectionPool `locationName:"grpc" type:"structure"`
// An object that represents a type of connection pool.
Http *VirtualNodeHttpConnectionPool `locationName:"http" type:"structure"`
// An object that represents a type of connection pool.
Http2 *VirtualNodeHttp2ConnectionPool `locationName:"http2" type:"structure"`
// An object that represents a type of connection pool.
Tcp *VirtualNodeTcpConnectionPool `locationName:"tcp" type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualNodeConnectionPool) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualNodeConnectionPool) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *VirtualNodeConnectionPool) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "VirtualNodeConnectionPool"}
if s.Grpc != nil {
if err := s.Grpc.Validate(); err != nil {
invalidParams.AddNested("Grpc", err.(request.ErrInvalidParams))
}
}
if s.Http != nil {
if err := s.Http.Validate(); err != nil {
invalidParams.AddNested("Http", err.(request.ErrInvalidParams))
}
}
if s.Http2 != nil {
if err := s.Http2.Validate(); err != nil {
invalidParams.AddNested("Http2", err.(request.ErrInvalidParams))
}
}
if s.Tcp != nil {
if err := s.Tcp.Validate(); err != nil {
invalidParams.AddNested("Tcp", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetGrpc sets the Grpc field's value.
func (s *VirtualNodeConnectionPool) SetGrpc(v *VirtualNodeGrpcConnectionPool) *VirtualNodeConnectionPool {
s.Grpc = v
return s
}
// SetHttp sets the Http field's value.
func (s *VirtualNodeConnectionPool) SetHttp(v *VirtualNodeHttpConnectionPool) *VirtualNodeConnectionPool {
s.Http = v
return s
}
// SetHttp2 sets the Http2 field's value.
func (s *VirtualNodeConnectionPool) SetHttp2(v *VirtualNodeHttp2ConnectionPool) *VirtualNodeConnectionPool {
s.Http2 = v
return s
}
// SetTcp sets the Tcp field's value.
func (s *VirtualNodeConnectionPool) SetTcp(v *VirtualNodeTcpConnectionPool) *VirtualNodeConnectionPool {
s.Tcp = v
return s
}
// An object that represents a virtual node returned by a describe operation.
type VirtualNodeData struct {
_ struct{} `type:"structure"`
// The name of the service mesh that the virtual node resides in.
//
// MeshName is a required field
MeshName *string `locationName:"meshName" min:"1" type:"string" required:"true"`
// The associated metadata for the virtual node.
//
// Metadata is a required field
Metadata *ResourceMetadata `locationName:"metadata" type:"structure" required:"true"`
// The specifications of the virtual node.
//
// Spec is a required field
Spec *VirtualNodeSpec `locationName:"spec" type:"structure" required:"true"`
// The current status for the virtual node.
//
// Status is a required field
Status *VirtualNodeStatus `locationName:"status" type:"structure" required:"true"`
// The name of the virtual node.
//
// VirtualNodeName is a required field
VirtualNodeName *string `locationName:"virtualNodeName" min:"1" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualNodeData) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualNodeData) GoString() string {
return s.String()
}
// SetMeshName sets the MeshName field's value.
func (s *VirtualNodeData) SetMeshName(v string) *VirtualNodeData {
s.MeshName = &v
return s
}
// SetMetadata sets the Metadata field's value.
func (s *VirtualNodeData) SetMetadata(v *ResourceMetadata) *VirtualNodeData {
s.Metadata = v
return s
}
// SetSpec sets the Spec field's value.
func (s *VirtualNodeData) SetSpec(v *VirtualNodeSpec) *VirtualNodeData {
s.Spec = v
return s
}
// SetStatus sets the Status field's value.
func (s *VirtualNodeData) SetStatus(v *VirtualNodeStatus) *VirtualNodeData {
s.Status = v
return s
}
// SetVirtualNodeName sets the VirtualNodeName field's value.
func (s *VirtualNodeData) SetVirtualNodeName(v string) *VirtualNodeData {
s.VirtualNodeName = &v
return s
}
// An object that represents a type of connection pool.
type VirtualNodeGrpcConnectionPool struct {
_ struct{} `type:"structure"`
// Maximum number of inflight requests Envoy can concurrently support across
// hosts in upstream cluster.
//
// MaxRequests is a required field
MaxRequests *int64 `locationName:"maxRequests" min:"1" type:"integer" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualNodeGrpcConnectionPool) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualNodeGrpcConnectionPool) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *VirtualNodeGrpcConnectionPool) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "VirtualNodeGrpcConnectionPool"}
if s.MaxRequests == nil {
invalidParams.Add(request.NewErrParamRequired("MaxRequests"))
}
if s.MaxRequests != nil && *s.MaxRequests < 1 {
invalidParams.Add(request.NewErrParamMinValue("MaxRequests", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetMaxRequests sets the MaxRequests field's value.
func (s *VirtualNodeGrpcConnectionPool) SetMaxRequests(v int64) *VirtualNodeGrpcConnectionPool {
s.MaxRequests = &v
return s
}
// An object that represents a type of connection pool.
type VirtualNodeHttp2ConnectionPool struct {
_ struct{} `type:"structure"`
// Maximum number of inflight requests Envoy can concurrently support across
// hosts in upstream cluster.
//
// MaxRequests is a required field
MaxRequests *int64 `locationName:"maxRequests" min:"1" type:"integer" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualNodeHttp2ConnectionPool) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualNodeHttp2ConnectionPool) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *VirtualNodeHttp2ConnectionPool) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "VirtualNodeHttp2ConnectionPool"}
if s.MaxRequests == nil {
invalidParams.Add(request.NewErrParamRequired("MaxRequests"))
}
if s.MaxRequests != nil && *s.MaxRequests < 1 {
invalidParams.Add(request.NewErrParamMinValue("MaxRequests", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetMaxRequests sets the MaxRequests field's value.
func (s *VirtualNodeHttp2ConnectionPool) SetMaxRequests(v int64) *VirtualNodeHttp2ConnectionPool {
s.MaxRequests = &v
return s
}
// An object that represents a type of connection pool.
type VirtualNodeHttpConnectionPool struct {
_ struct{} `type:"structure"`
// Maximum number of outbound TCP connections Envoy can establish concurrently
// with all hosts in upstream cluster.
//
// MaxConnections is a required field
MaxConnections *int64 `locationName:"maxConnections" min:"1" type:"integer" required:"true"`
// Number of overflowing requests after max_connections Envoy will queue to
// upstream cluster.
MaxPendingRequests *int64 `locationName:"maxPendingRequests" min:"1" type:"integer"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualNodeHttpConnectionPool) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualNodeHttpConnectionPool) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *VirtualNodeHttpConnectionPool) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "VirtualNodeHttpConnectionPool"}
if s.MaxConnections == nil {
invalidParams.Add(request.NewErrParamRequired("MaxConnections"))
}
if s.MaxConnections != nil && *s.MaxConnections < 1 {
invalidParams.Add(request.NewErrParamMinValue("MaxConnections", 1))
}
if s.MaxPendingRequests != nil && *s.MaxPendingRequests < 1 {
invalidParams.Add(request.NewErrParamMinValue("MaxPendingRequests", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetMaxConnections sets the MaxConnections field's value.
func (s *VirtualNodeHttpConnectionPool) SetMaxConnections(v int64) *VirtualNodeHttpConnectionPool {
s.MaxConnections = &v
return s
}
// SetMaxPendingRequests sets the MaxPendingRequests field's value.
func (s *VirtualNodeHttpConnectionPool) SetMaxPendingRequests(v int64) *VirtualNodeHttpConnectionPool {
s.MaxPendingRequests = &v
return s
}
// An object that represents a virtual node returned by a list operation.
type VirtualNodeRef struct {
_ struct{} `type:"structure"`
// The full Amazon Resource Name (ARN) for the virtual node.
//
// Arn is a required field
Arn *string `locationName:"arn" type:"string" required:"true"`
// The Unix epoch timestamp in seconds for when the resource was created.
//
// CreatedAt is a required field
CreatedAt *time.Time `locationName:"createdAt" type:"timestamp" required:"true"`
// The Unix epoch timestamp in seconds for when the resource was last updated.
//
// LastUpdatedAt is a required field
LastUpdatedAt *time.Time `locationName:"lastUpdatedAt" type:"timestamp" required:"true"`
// The name of the service mesh that the virtual node resides in.
//
// MeshName is a required field
MeshName *string `locationName:"meshName" min:"1" type:"string" required:"true"`
// The AWS IAM account ID of the service mesh owner. If the account ID is not
// your own, then it's the ID of the account that shared the mesh with your
// account. For more information about mesh sharing, see Working with shared
// meshes (https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html).
//
// MeshOwner is a required field
MeshOwner *string `locationName:"meshOwner" min:"12" type:"string" required:"true"`
// The AWS IAM account ID of the resource owner. If the account ID is not your
// own, then it's the ID of the mesh owner or of another account that the mesh
// is shared with. For more information about mesh sharing, see Working with
// shared meshes (https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html).
//
// ResourceOwner is a required field
ResourceOwner *string `locationName:"resourceOwner" min:"12" type:"string" required:"true"`
// The version of the resource. Resources are created at version 1, and this
// version is incremented each time that they're updated.
//
// Version is a required field
Version *int64 `locationName:"version" type:"long" required:"true"`
// The name of the virtual node.
//
// VirtualNodeName is a required field
VirtualNodeName *string `locationName:"virtualNodeName" min:"1" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualNodeRef) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualNodeRef) GoString() string {
return s.String()
}
// SetArn sets the Arn field's value.
func (s *VirtualNodeRef) SetArn(v string) *VirtualNodeRef {
s.Arn = &v
return s
}
// SetCreatedAt sets the CreatedAt field's value.
func (s *VirtualNodeRef) SetCreatedAt(v time.Time) *VirtualNodeRef {
s.CreatedAt = &v
return s
}
// SetLastUpdatedAt sets the LastUpdatedAt field's value.
func (s *VirtualNodeRef) SetLastUpdatedAt(v time.Time) *VirtualNodeRef {
s.LastUpdatedAt = &v
return s
}
// SetMeshName sets the MeshName field's value.
func (s *VirtualNodeRef) SetMeshName(v string) *VirtualNodeRef {
s.MeshName = &v
return s
}
// SetMeshOwner sets the MeshOwner field's value.
func (s *VirtualNodeRef) SetMeshOwner(v string) *VirtualNodeRef {
s.MeshOwner = &v
return s
}
// SetResourceOwner sets the ResourceOwner field's value.
func (s *VirtualNodeRef) SetResourceOwner(v string) *VirtualNodeRef {
s.ResourceOwner = &v
return s
}
// SetVersion sets the Version field's value.
func (s *VirtualNodeRef) SetVersion(v int64) *VirtualNodeRef {
s.Version = &v
return s
}
// SetVirtualNodeName sets the VirtualNodeName field's value.
func (s *VirtualNodeRef) SetVirtualNodeName(v string) *VirtualNodeRef {
s.VirtualNodeName = &v
return s
}
// An object that represents a virtual node service provider.
type VirtualNodeServiceProvider struct {
_ struct{} `type:"structure"`
// The name of the virtual node that is acting as a service provider.
//
// VirtualNodeName is a required field
VirtualNodeName *string `locationName:"virtualNodeName" min:"1" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualNodeServiceProvider) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualNodeServiceProvider) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *VirtualNodeServiceProvider) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "VirtualNodeServiceProvider"}
if s.VirtualNodeName == nil {
invalidParams.Add(request.NewErrParamRequired("VirtualNodeName"))
}
if s.VirtualNodeName != nil && len(*s.VirtualNodeName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("VirtualNodeName", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetVirtualNodeName sets the VirtualNodeName field's value.
func (s *VirtualNodeServiceProvider) SetVirtualNodeName(v string) *VirtualNodeServiceProvider {
s.VirtualNodeName = &v
return s
}
// An object that represents the specification of a virtual node.
type VirtualNodeSpec struct {
_ struct{} `type:"structure"`
// A reference to an object that represents the defaults for backends.
BackendDefaults *BackendDefaults `locationName:"backendDefaults" type:"structure"`
// The backends that the virtual node is expected to send outbound traffic to.
Backends []*Backend `locationName:"backends" type:"list"`
// The listener that the virtual node is expected to receive inbound traffic
// from. You can specify one listener.
Listeners []*Listener `locationName:"listeners" type:"list"`
// The inbound and outbound access logging information for the virtual node.
Logging *Logging `locationName:"logging" type:"structure"`
// The service discovery information for the virtual node. If your virtual node
// does not expect ingress traffic, you can omit this parameter. If you specify
// a listener, then you must specify service discovery information.
ServiceDiscovery *ServiceDiscovery `locationName:"serviceDiscovery" type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualNodeSpec) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualNodeSpec) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *VirtualNodeSpec) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "VirtualNodeSpec"}
if s.BackendDefaults != nil {
if err := s.BackendDefaults.Validate(); err != nil {
invalidParams.AddNested("BackendDefaults", err.(request.ErrInvalidParams))
}
}
if s.Backends != nil {
for i, v := range s.Backends {
if v == nil {
continue
}
if err := v.Validate(); err != nil {
invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Backends", i), err.(request.ErrInvalidParams))
}
}
}
if s.Listeners != nil {
for i, v := range s.Listeners {
if v == nil {
continue
}
if err := v.Validate(); err != nil {
invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Listeners", i), err.(request.ErrInvalidParams))
}
}
}
if s.Logging != nil {
if err := s.Logging.Validate(); err != nil {
invalidParams.AddNested("Logging", err.(request.ErrInvalidParams))
}
}
if s.ServiceDiscovery != nil {
if err := s.ServiceDiscovery.Validate(); err != nil {
invalidParams.AddNested("ServiceDiscovery", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetBackendDefaults sets the BackendDefaults field's value.
func (s *VirtualNodeSpec) SetBackendDefaults(v *BackendDefaults) *VirtualNodeSpec {
s.BackendDefaults = v
return s
}
// SetBackends sets the Backends field's value.
func (s *VirtualNodeSpec) SetBackends(v []*Backend) *VirtualNodeSpec {
s.Backends = v
return s
}
// SetListeners sets the Listeners field's value.
func (s *VirtualNodeSpec) SetListeners(v []*Listener) *VirtualNodeSpec {
s.Listeners = v
return s
}
// SetLogging sets the Logging field's value.
func (s *VirtualNodeSpec) SetLogging(v *Logging) *VirtualNodeSpec {
s.Logging = v
return s
}
// SetServiceDiscovery sets the ServiceDiscovery field's value.
func (s *VirtualNodeSpec) SetServiceDiscovery(v *ServiceDiscovery) *VirtualNodeSpec {
s.ServiceDiscovery = v
return s
}
// An object that represents the current status of the virtual node.
type VirtualNodeStatus struct {
_ struct{} `type:"structure"`
// The current status of the virtual node.
//
// Status is a required field
Status *string `locationName:"status" type:"string" required:"true" enum:"VirtualNodeStatusCode"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualNodeStatus) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualNodeStatus) GoString() string {
return s.String()
}
// SetStatus sets the Status field's value.
func (s *VirtualNodeStatus) SetStatus(v string) *VirtualNodeStatus {
s.Status = &v
return s
}
// An object that represents a type of connection pool.
type VirtualNodeTcpConnectionPool struct {
_ struct{} `type:"structure"`
// Maximum number of outbound TCP connections Envoy can establish concurrently
// with all hosts in upstream cluster.
//
// MaxConnections is a required field
MaxConnections *int64 `locationName:"maxConnections" min:"1" type:"integer" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualNodeTcpConnectionPool) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualNodeTcpConnectionPool) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *VirtualNodeTcpConnectionPool) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "VirtualNodeTcpConnectionPool"}
if s.MaxConnections == nil {
invalidParams.Add(request.NewErrParamRequired("MaxConnections"))
}
if s.MaxConnections != nil && *s.MaxConnections < 1 {
invalidParams.Add(request.NewErrParamMinValue("MaxConnections", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetMaxConnections sets the MaxConnections field's value.
func (s *VirtualNodeTcpConnectionPool) SetMaxConnections(v int64) *VirtualNodeTcpConnectionPool {
s.MaxConnections = &v
return s
}
// An object that represents a virtual router returned by a describe operation.
type VirtualRouterData struct {
_ struct{} `type:"structure"`
// The name of the service mesh that the virtual router resides in.
//
// MeshName is a required field
MeshName *string `locationName:"meshName" min:"1" type:"string" required:"true"`
// The associated metadata for the virtual router.
//
// Metadata is a required field
Metadata *ResourceMetadata `locationName:"metadata" type:"structure" required:"true"`
// The specifications of the virtual router.
//
// Spec is a required field
Spec *VirtualRouterSpec `locationName:"spec" type:"structure" required:"true"`
// The current status of the virtual router.
//
// Status is a required field
Status *VirtualRouterStatus `locationName:"status" type:"structure" required:"true"`
// The name of the virtual router.
//
// VirtualRouterName is a required field
VirtualRouterName *string `locationName:"virtualRouterName" min:"1" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualRouterData) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualRouterData) GoString() string {
return s.String()
}
// SetMeshName sets the MeshName field's value.
func (s *VirtualRouterData) SetMeshName(v string) *VirtualRouterData {
s.MeshName = &v
return s
}
// SetMetadata sets the Metadata field's value.
func (s *VirtualRouterData) SetMetadata(v *ResourceMetadata) *VirtualRouterData {
s.Metadata = v
return s
}
// SetSpec sets the Spec field's value.
func (s *VirtualRouterData) SetSpec(v *VirtualRouterSpec) *VirtualRouterData {
s.Spec = v
return s
}
// SetStatus sets the Status field's value.
func (s *VirtualRouterData) SetStatus(v *VirtualRouterStatus) *VirtualRouterData {
s.Status = v
return s
}
// SetVirtualRouterName sets the VirtualRouterName field's value.
func (s *VirtualRouterData) SetVirtualRouterName(v string) *VirtualRouterData {
s.VirtualRouterName = &v
return s
}
// An object that represents a virtual router listener.
type VirtualRouterListener struct {
_ struct{} `type:"structure"`
// An object that represents a port mapping.
//
// PortMapping is a required field
PortMapping *PortMapping `locationName:"portMapping" type:"structure" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualRouterListener) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualRouterListener) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *VirtualRouterListener) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "VirtualRouterListener"}
if s.PortMapping == nil {
invalidParams.Add(request.NewErrParamRequired("PortMapping"))
}
if s.PortMapping != nil {
if err := s.PortMapping.Validate(); err != nil {
invalidParams.AddNested("PortMapping", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetPortMapping sets the PortMapping field's value.
func (s *VirtualRouterListener) SetPortMapping(v *PortMapping) *VirtualRouterListener {
s.PortMapping = v
return s
}
// An object that represents a virtual router returned by a list operation.
type VirtualRouterRef struct {
_ struct{} `type:"structure"`
// The full Amazon Resource Name (ARN) for the virtual router.
//
// Arn is a required field
Arn *string `locationName:"arn" type:"string" required:"true"`
// The Unix epoch timestamp in seconds for when the resource was created.
//
// CreatedAt is a required field
CreatedAt *time.Time `locationName:"createdAt" type:"timestamp" required:"true"`
// The Unix epoch timestamp in seconds for when the resource was last updated.
//
// LastUpdatedAt is a required field
LastUpdatedAt *time.Time `locationName:"lastUpdatedAt" type:"timestamp" required:"true"`
// The name of the service mesh that the virtual router resides in.
//
// MeshName is a required field
MeshName *string `locationName:"meshName" min:"1" type:"string" required:"true"`
// The AWS IAM account ID of the service mesh owner. If the account ID is not
// your own, then it's the ID of the account that shared the mesh with your
// account. For more information about mesh sharing, see Working with shared
// meshes (https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html).
//
// MeshOwner is a required field
MeshOwner *string `locationName:"meshOwner" min:"12" type:"string" required:"true"`
// The AWS IAM account ID of the resource owner. If the account ID is not your
// own, then it's the ID of the mesh owner or of another account that the mesh
// is shared with. For more information about mesh sharing, see Working with
// shared meshes (https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html).
//
// ResourceOwner is a required field
ResourceOwner *string `locationName:"resourceOwner" min:"12" type:"string" required:"true"`
// The version of the resource. Resources are created at version 1, and this
// version is incremented each time that they're updated.
//
// Version is a required field
Version *int64 `locationName:"version" type:"long" required:"true"`
// The name of the virtual router.
//
// VirtualRouterName is a required field
VirtualRouterName *string `locationName:"virtualRouterName" min:"1" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualRouterRef) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualRouterRef) GoString() string {
return s.String()
}
// SetArn sets the Arn field's value.
func (s *VirtualRouterRef) SetArn(v string) *VirtualRouterRef {
s.Arn = &v
return s
}
// SetCreatedAt sets the CreatedAt field's value.
func (s *VirtualRouterRef) SetCreatedAt(v time.Time) *VirtualRouterRef {
s.CreatedAt = &v
return s
}
// SetLastUpdatedAt sets the LastUpdatedAt field's value.
func (s *VirtualRouterRef) SetLastUpdatedAt(v time.Time) *VirtualRouterRef {
s.LastUpdatedAt = &v
return s
}
// SetMeshName sets the MeshName field's value.
func (s *VirtualRouterRef) SetMeshName(v string) *VirtualRouterRef {
s.MeshName = &v
return s
}
// SetMeshOwner sets the MeshOwner field's value.
func (s *VirtualRouterRef) SetMeshOwner(v string) *VirtualRouterRef {
s.MeshOwner = &v
return s
}
// SetResourceOwner sets the ResourceOwner field's value.
func (s *VirtualRouterRef) SetResourceOwner(v string) *VirtualRouterRef {
s.ResourceOwner = &v
return s
}
// SetVersion sets the Version field's value.
func (s *VirtualRouterRef) SetVersion(v int64) *VirtualRouterRef {
s.Version = &v
return s
}
// SetVirtualRouterName sets the VirtualRouterName field's value.
func (s *VirtualRouterRef) SetVirtualRouterName(v string) *VirtualRouterRef {
s.VirtualRouterName = &v
return s
}
// An object that represents a virtual node service provider.
type VirtualRouterServiceProvider struct {
_ struct{} `type:"structure"`
// The name of the virtual router that is acting as a service provider.
//
// VirtualRouterName is a required field
VirtualRouterName *string `locationName:"virtualRouterName" min:"1" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualRouterServiceProvider) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualRouterServiceProvider) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *VirtualRouterServiceProvider) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "VirtualRouterServiceProvider"}
if s.VirtualRouterName == nil {
invalidParams.Add(request.NewErrParamRequired("VirtualRouterName"))
}
if s.VirtualRouterName != nil && len(*s.VirtualRouterName) < 1 {
invalidParams.Add(request.NewErrParamMinLen("VirtualRouterName", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetVirtualRouterName sets the VirtualRouterName field's value.
func (s *VirtualRouterServiceProvider) SetVirtualRouterName(v string) *VirtualRouterServiceProvider {
s.VirtualRouterName = &v
return s
}
// An object that represents the specification of a virtual router.
type VirtualRouterSpec struct {
_ struct{} `type:"structure"`
// The listeners that the virtual router is expected to receive inbound traffic
// from. You can specify one listener.
Listeners []*VirtualRouterListener `locationName:"listeners" min:"1" type:"list"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualRouterSpec) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualRouterSpec) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *VirtualRouterSpec) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "VirtualRouterSpec"}
if s.Listeners != nil && len(s.Listeners) < 1 {
invalidParams.Add(request.NewErrParamMinLen("Listeners", 1))
}
if s.Listeners != nil {
for i, v := range s.Listeners {
if v == nil {
continue
}
if err := v.Validate(); err != nil {
invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Listeners", i), err.(request.ErrInvalidParams))
}
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetListeners sets the Listeners field's value.
func (s *VirtualRouterSpec) SetListeners(v []*VirtualRouterListener) *VirtualRouterSpec {
s.Listeners = v
return s
}
// An object that represents the status of a virtual router.
type VirtualRouterStatus struct {
_ struct{} `type:"structure"`
// The current status of the virtual router.
//
// Status is a required field
Status *string `locationName:"status" type:"string" required:"true" enum:"VirtualRouterStatusCode"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualRouterStatus) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualRouterStatus) GoString() string {
return s.String()
}
// SetStatus sets the Status field's value.
func (s *VirtualRouterStatus) SetStatus(v string) *VirtualRouterStatus {
s.Status = &v
return s
}
// An object that represents a virtual service backend for a virtual node.
type VirtualServiceBackend struct {
_ struct{} `type:"structure"`
// A reference to an object that represents the client policy for a backend.
ClientPolicy *ClientPolicy `locationName:"clientPolicy" type:"structure"`
// The name of the virtual service that is acting as a virtual node backend.
//
// VirtualServiceName is a required field
VirtualServiceName *string `locationName:"virtualServiceName" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualServiceBackend) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualServiceBackend) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *VirtualServiceBackend) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "VirtualServiceBackend"}
if s.VirtualServiceName == nil {
invalidParams.Add(request.NewErrParamRequired("VirtualServiceName"))
}
if s.ClientPolicy != nil {
if err := s.ClientPolicy.Validate(); err != nil {
invalidParams.AddNested("ClientPolicy", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetClientPolicy sets the ClientPolicy field's value.
func (s *VirtualServiceBackend) SetClientPolicy(v *ClientPolicy) *VirtualServiceBackend {
s.ClientPolicy = v
return s
}
// SetVirtualServiceName sets the VirtualServiceName field's value.
func (s *VirtualServiceBackend) SetVirtualServiceName(v string) *VirtualServiceBackend {
s.VirtualServiceName = &v
return s
}
// An object that represents a virtual service returned by a describe operation.
type VirtualServiceData struct {
_ struct{} `type:"structure"`
// The name of the service mesh that the virtual service resides in.
//
// MeshName is a required field
MeshName *string `locationName:"meshName" min:"1" type:"string" required:"true"`
// An object that represents metadata for a resource.
//
// Metadata is a required field
Metadata *ResourceMetadata `locationName:"metadata" type:"structure" required:"true"`
// The specifications of the virtual service.
//
// Spec is a required field
Spec *VirtualServiceSpec `locationName:"spec" type:"structure" required:"true"`
// The current status of the virtual service.
//
// Status is a required field
Status *VirtualServiceStatus `locationName:"status" type:"structure" required:"true"`
// The name of the virtual service.
//
// VirtualServiceName is a required field
VirtualServiceName *string `locationName:"virtualServiceName" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualServiceData) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualServiceData) GoString() string {
return s.String()
}
// SetMeshName sets the MeshName field's value.
func (s *VirtualServiceData) SetMeshName(v string) *VirtualServiceData {
s.MeshName = &v
return s
}
// SetMetadata sets the Metadata field's value.
func (s *VirtualServiceData) SetMetadata(v *ResourceMetadata) *VirtualServiceData {
s.Metadata = v
return s
}
// SetSpec sets the Spec field's value.
func (s *VirtualServiceData) SetSpec(v *VirtualServiceSpec) *VirtualServiceData {
s.Spec = v
return s
}
// SetStatus sets the Status field's value.
func (s *VirtualServiceData) SetStatus(v *VirtualServiceStatus) *VirtualServiceData {
s.Status = v
return s
}
// SetVirtualServiceName sets the VirtualServiceName field's value.
func (s *VirtualServiceData) SetVirtualServiceName(v string) *VirtualServiceData {
s.VirtualServiceName = &v
return s
}
// An object that represents the provider for a virtual service.
type VirtualServiceProvider struct {
_ struct{} `type:"structure"`
// The virtual node associated with a virtual service.
VirtualNode *VirtualNodeServiceProvider `locationName:"virtualNode" type:"structure"`
// The virtual router associated with a virtual service.
VirtualRouter *VirtualRouterServiceProvider `locationName:"virtualRouter" type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualServiceProvider) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualServiceProvider) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *VirtualServiceProvider) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "VirtualServiceProvider"}
if s.VirtualNode != nil {
if err := s.VirtualNode.Validate(); err != nil {
invalidParams.AddNested("VirtualNode", err.(request.ErrInvalidParams))
}
}
if s.VirtualRouter != nil {
if err := s.VirtualRouter.Validate(); err != nil {
invalidParams.AddNested("VirtualRouter", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetVirtualNode sets the VirtualNode field's value.
func (s *VirtualServiceProvider) SetVirtualNode(v *VirtualNodeServiceProvider) *VirtualServiceProvider {
s.VirtualNode = v
return s
}
// SetVirtualRouter sets the VirtualRouter field's value.
func (s *VirtualServiceProvider) SetVirtualRouter(v *VirtualRouterServiceProvider) *VirtualServiceProvider {
s.VirtualRouter = v
return s
}
// An object that represents a virtual service returned by a list operation.
type VirtualServiceRef struct {
_ struct{} `type:"structure"`
// The full Amazon Resource Name (ARN) for the virtual service.
//
// Arn is a required field
Arn *string `locationName:"arn" type:"string" required:"true"`
// The Unix epoch timestamp in seconds for when the resource was created.
//
// CreatedAt is a required field
CreatedAt *time.Time `locationName:"createdAt" type:"timestamp" required:"true"`
// The Unix epoch timestamp in seconds for when the resource was last updated.
//
// LastUpdatedAt is a required field
LastUpdatedAt *time.Time `locationName:"lastUpdatedAt" type:"timestamp" required:"true"`
// The name of the service mesh that the virtual service resides in.
//
// MeshName is a required field
MeshName *string `locationName:"meshName" min:"1" type:"string" required:"true"`
// The AWS IAM account ID of the service mesh owner. If the account ID is not
// your own, then it's the ID of the account that shared the mesh with your
// account. For more information about mesh sharing, see Working with shared
// meshes (https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html).
//
// MeshOwner is a required field
MeshOwner *string `locationName:"meshOwner" min:"12" type:"string" required:"true"`
// The AWS IAM account ID of the resource owner. If the account ID is not your
// own, then it's the ID of the mesh owner or of another account that the mesh
// is shared with. For more information about mesh sharing, see Working with
// shared meshes (https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html).
//
// ResourceOwner is a required field
ResourceOwner *string `locationName:"resourceOwner" min:"12" type:"string" required:"true"`
// The version of the resource. Resources are created at version 1, and this
// version is incremented each time that they're updated.
//
// Version is a required field
Version *int64 `locationName:"version" type:"long" required:"true"`
// The name of the virtual service.
//
// VirtualServiceName is a required field
VirtualServiceName *string `locationName:"virtualServiceName" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualServiceRef) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualServiceRef) GoString() string {
return s.String()
}
// SetArn sets the Arn field's value.
func (s *VirtualServiceRef) SetArn(v string) *VirtualServiceRef {
s.Arn = &v
return s
}
// SetCreatedAt sets the CreatedAt field's value.
func (s *VirtualServiceRef) SetCreatedAt(v time.Time) *VirtualServiceRef {
s.CreatedAt = &v
return s
}
// SetLastUpdatedAt sets the LastUpdatedAt field's value.
func (s *VirtualServiceRef) SetLastUpdatedAt(v time.Time) *VirtualServiceRef {
s.LastUpdatedAt = &v
return s
}
// SetMeshName sets the MeshName field's value.
func (s *VirtualServiceRef) SetMeshName(v string) *VirtualServiceRef {
s.MeshName = &v
return s
}
// SetMeshOwner sets the MeshOwner field's value.
func (s *VirtualServiceRef) SetMeshOwner(v string) *VirtualServiceRef {
s.MeshOwner = &v
return s
}
// SetResourceOwner sets the ResourceOwner field's value.
func (s *VirtualServiceRef) SetResourceOwner(v string) *VirtualServiceRef {
s.ResourceOwner = &v
return s
}
// SetVersion sets the Version field's value.
func (s *VirtualServiceRef) SetVersion(v int64) *VirtualServiceRef {
s.Version = &v
return s
}
// SetVirtualServiceName sets the VirtualServiceName field's value.
func (s *VirtualServiceRef) SetVirtualServiceName(v string) *VirtualServiceRef {
s.VirtualServiceName = &v
return s
}
// An object that represents the specification of a virtual service.
type VirtualServiceSpec struct {
_ struct{} `type:"structure"`
// The App Mesh object that is acting as the provider for a virtual service.
// You can specify a single virtual node or virtual router.
Provider *VirtualServiceProvider `locationName:"provider" type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualServiceSpec) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualServiceSpec) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *VirtualServiceSpec) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "VirtualServiceSpec"}
if s.Provider != nil {
if err := s.Provider.Validate(); err != nil {
invalidParams.AddNested("Provider", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetProvider sets the Provider field's value.
func (s *VirtualServiceSpec) SetProvider(v *VirtualServiceProvider) *VirtualServiceSpec {
s.Provider = v
return s
}
// An object that represents the status of a virtual service.
type VirtualServiceStatus struct {
_ struct{} `type:"structure"`
// The current status of the virtual service.
//
// Status is a required field
Status *string `locationName:"status" type:"string" required:"true" enum:"VirtualServiceStatusCode"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualServiceStatus) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VirtualServiceStatus) GoString() string {
return s.String()
}
// SetStatus sets the Status field's value.
func (s *VirtualServiceStatus) SetStatus(v string) *VirtualServiceStatus {
s.Status = &v
return s
}
// An object that represents a target and its relative weight. Traffic is distributed
// across targets according to their relative weight. For example, a weighted
// target with a relative weight of 50 receives five times as much traffic as
// one with a relative weight of 10. The total weight for all targets combined
// must be less than or equal to 100.
type WeightedTarget struct {
_ struct{} `type:"structure"`
// The virtual node to associate with the weighted target.
//
// VirtualNode is a required field
VirtualNode *string `locationName:"virtualNode" min:"1" type:"string" required:"true"`
// The relative weight of the weighted target.
//
// Weight is a required field
Weight *int64 `locationName:"weight" type:"integer" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s WeightedTarget) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s WeightedTarget) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *WeightedTarget) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "WeightedTarget"}
if s.VirtualNode == nil {
invalidParams.Add(request.NewErrParamRequired("VirtualNode"))
}
if s.VirtualNode != nil && len(*s.VirtualNode) < 1 {
invalidParams.Add(request.NewErrParamMinLen("VirtualNode", 1))
}
if s.Weight == nil {
invalidParams.Add(request.NewErrParamRequired("Weight"))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetVirtualNode sets the VirtualNode field's value.
func (s *WeightedTarget) SetVirtualNode(v string) *WeightedTarget {
s.VirtualNode = &v
return s
}
// SetWeight sets the Weight field's value.
func (s *WeightedTarget) SetWeight(v int64) *WeightedTarget {
s.Weight = &v
return s
}
const (
// DefaultGatewayRouteRewriteEnabled is a DefaultGatewayRouteRewrite enum value
DefaultGatewayRouteRewriteEnabled = "ENABLED"
// DefaultGatewayRouteRewriteDisabled is a DefaultGatewayRouteRewrite enum value
DefaultGatewayRouteRewriteDisabled = "DISABLED"
)
// DefaultGatewayRouteRewrite_Values returns all elements of the DefaultGatewayRouteRewrite enum
func DefaultGatewayRouteRewrite_Values() []string {
return []string{
DefaultGatewayRouteRewriteEnabled,
DefaultGatewayRouteRewriteDisabled,
}
}
const (
// DnsResponseTypeLoadbalancer is a DnsResponseType enum value
DnsResponseTypeLoadbalancer = "LOADBALANCER"
// DnsResponseTypeEndpoints is a DnsResponseType enum value
DnsResponseTypeEndpoints = "ENDPOINTS"
)
// DnsResponseType_Values returns all elements of the DnsResponseType enum
func DnsResponseType_Values() []string {
return []string{
DnsResponseTypeLoadbalancer,
DnsResponseTypeEndpoints,
}
}
const (
// DurationUnitS is a DurationUnit enum value
DurationUnitS = "s"
// DurationUnitMs is a DurationUnit enum value
DurationUnitMs = "ms"
)
// DurationUnit_Values returns all elements of the DurationUnit enum
func DurationUnit_Values() []string {
return []string{
DurationUnitS,
DurationUnitMs,
}
}
const (
// EgressFilterTypeAllowAll is a EgressFilterType enum value
EgressFilterTypeAllowAll = "ALLOW_ALL"
// EgressFilterTypeDropAll is a EgressFilterType enum value
EgressFilterTypeDropAll = "DROP_ALL"
)
// EgressFilterType_Values returns all elements of the EgressFilterType enum
func EgressFilterType_Values() []string {
return []string{
EgressFilterTypeAllowAll,
EgressFilterTypeDropAll,
}
}
const (
// GatewayRouteStatusCodeActive is a GatewayRouteStatusCode enum value
GatewayRouteStatusCodeActive = "ACTIVE"
// GatewayRouteStatusCodeInactive is a GatewayRouteStatusCode enum value
GatewayRouteStatusCodeInactive = "INACTIVE"
// GatewayRouteStatusCodeDeleted is a GatewayRouteStatusCode enum value
GatewayRouteStatusCodeDeleted = "DELETED"
)
// GatewayRouteStatusCode_Values returns all elements of the GatewayRouteStatusCode enum
func GatewayRouteStatusCode_Values() []string {
return []string{
GatewayRouteStatusCodeActive,
GatewayRouteStatusCodeInactive,
GatewayRouteStatusCodeDeleted,
}
}
const (
// GrpcRetryPolicyEventCancelled is a GrpcRetryPolicyEvent enum value
GrpcRetryPolicyEventCancelled = "cancelled"
// GrpcRetryPolicyEventDeadlineExceeded is a GrpcRetryPolicyEvent enum value
GrpcRetryPolicyEventDeadlineExceeded = "deadline-exceeded"
// GrpcRetryPolicyEventInternal is a GrpcRetryPolicyEvent enum value
GrpcRetryPolicyEventInternal = "internal"
// GrpcRetryPolicyEventResourceExhausted is a GrpcRetryPolicyEvent enum value
GrpcRetryPolicyEventResourceExhausted = "resource-exhausted"
// GrpcRetryPolicyEventUnavailable is a GrpcRetryPolicyEvent enum value
GrpcRetryPolicyEventUnavailable = "unavailable"
)
// GrpcRetryPolicyEvent_Values returns all elements of the GrpcRetryPolicyEvent enum
func GrpcRetryPolicyEvent_Values() []string {
return []string{
GrpcRetryPolicyEventCancelled,
GrpcRetryPolicyEventDeadlineExceeded,
GrpcRetryPolicyEventInternal,
GrpcRetryPolicyEventResourceExhausted,
GrpcRetryPolicyEventUnavailable,
}
}
const (
// HttpMethodGet is a HttpMethod enum value
HttpMethodGet = "GET"
// HttpMethodHead is a HttpMethod enum value
HttpMethodHead = "HEAD"
// HttpMethodPost is a HttpMethod enum value
HttpMethodPost = "POST"
// HttpMethodPut is a HttpMethod enum value
HttpMethodPut = "PUT"
// HttpMethodDelete is a HttpMethod enum value
HttpMethodDelete = "DELETE"
// HttpMethodConnect is a HttpMethod enum value
HttpMethodConnect = "CONNECT"
// HttpMethodOptions is a HttpMethod enum value
HttpMethodOptions = "OPTIONS"
// HttpMethodTrace is a HttpMethod enum value
HttpMethodTrace = "TRACE"
// HttpMethodPatch is a HttpMethod enum value
HttpMethodPatch = "PATCH"
)
// HttpMethod_Values returns all elements of the HttpMethod enum
func HttpMethod_Values() []string {
return []string{
HttpMethodGet,
HttpMethodHead,
HttpMethodPost,
HttpMethodPut,
HttpMethodDelete,
HttpMethodConnect,
HttpMethodOptions,
HttpMethodTrace,
HttpMethodPatch,
}
}
const (
// HttpSchemeHttp is a HttpScheme enum value
HttpSchemeHttp = "http"
// HttpSchemeHttps is a HttpScheme enum value
HttpSchemeHttps = "https"
)
// HttpScheme_Values returns all elements of the HttpScheme enum
func HttpScheme_Values() []string {
return []string{
HttpSchemeHttp,
HttpSchemeHttps,
}
}
const (
// ListenerTlsModeStrict is a ListenerTlsMode enum value
ListenerTlsModeStrict = "STRICT"
// ListenerTlsModePermissive is a ListenerTlsMode enum value
ListenerTlsModePermissive = "PERMISSIVE"
// ListenerTlsModeDisabled is a ListenerTlsMode enum value
ListenerTlsModeDisabled = "DISABLED"
)
// ListenerTlsMode_Values returns all elements of the ListenerTlsMode enum
func ListenerTlsMode_Values() []string {
return []string{
ListenerTlsModeStrict,
ListenerTlsModePermissive,
ListenerTlsModeDisabled,
}
}
const (
// MeshStatusCodeActive is a MeshStatusCode enum value
MeshStatusCodeActive = "ACTIVE"
// MeshStatusCodeInactive is a MeshStatusCode enum value
MeshStatusCodeInactive = "INACTIVE"
// MeshStatusCodeDeleted is a MeshStatusCode enum value
MeshStatusCodeDeleted = "DELETED"
)
// MeshStatusCode_Values returns all elements of the MeshStatusCode enum
func MeshStatusCode_Values() []string {
return []string{
MeshStatusCodeActive,
MeshStatusCodeInactive,
MeshStatusCodeDeleted,
}
}
const (
// PortProtocolHttp is a PortProtocol enum value
PortProtocolHttp = "http"
// PortProtocolTcp is a PortProtocol enum value
PortProtocolTcp = "tcp"
// PortProtocolHttp2 is a PortProtocol enum value
PortProtocolHttp2 = "http2"
// PortProtocolGrpc is a PortProtocol enum value
PortProtocolGrpc = "grpc"
)
// PortProtocol_Values returns all elements of the PortProtocol enum
func PortProtocol_Values() []string {
return []string{
PortProtocolHttp,
PortProtocolTcp,
PortProtocolHttp2,
PortProtocolGrpc,
}
}
const (
// RouteStatusCodeActive is a RouteStatusCode enum value
RouteStatusCodeActive = "ACTIVE"
// RouteStatusCodeInactive is a RouteStatusCode enum value
RouteStatusCodeInactive = "INACTIVE"
// RouteStatusCodeDeleted is a RouteStatusCode enum value
RouteStatusCodeDeleted = "DELETED"
)
// RouteStatusCode_Values returns all elements of the RouteStatusCode enum
func RouteStatusCode_Values() []string {
return []string{
RouteStatusCodeActive,
RouteStatusCodeInactive,
RouteStatusCodeDeleted,
}
}
const (
// TcpRetryPolicyEventConnectionError is a TcpRetryPolicyEvent enum value
TcpRetryPolicyEventConnectionError = "connection-error"
)
// TcpRetryPolicyEvent_Values returns all elements of the TcpRetryPolicyEvent enum
func TcpRetryPolicyEvent_Values() []string {
return []string{
TcpRetryPolicyEventConnectionError,
}
}
const (
// VirtualGatewayListenerTlsModeStrict is a VirtualGatewayListenerTlsMode enum value
VirtualGatewayListenerTlsModeStrict = "STRICT"
// VirtualGatewayListenerTlsModePermissive is a VirtualGatewayListenerTlsMode enum value
VirtualGatewayListenerTlsModePermissive = "PERMISSIVE"
// VirtualGatewayListenerTlsModeDisabled is a VirtualGatewayListenerTlsMode enum value
VirtualGatewayListenerTlsModeDisabled = "DISABLED"
)
// VirtualGatewayListenerTlsMode_Values returns all elements of the VirtualGatewayListenerTlsMode enum
func VirtualGatewayListenerTlsMode_Values() []string {
return []string{
VirtualGatewayListenerTlsModeStrict,
VirtualGatewayListenerTlsModePermissive,
VirtualGatewayListenerTlsModeDisabled,
}
}
const (
// VirtualGatewayPortProtocolHttp is a VirtualGatewayPortProtocol enum value
VirtualGatewayPortProtocolHttp = "http"
// VirtualGatewayPortProtocolHttp2 is a VirtualGatewayPortProtocol enum value
VirtualGatewayPortProtocolHttp2 = "http2"
// VirtualGatewayPortProtocolGrpc is a VirtualGatewayPortProtocol enum value
VirtualGatewayPortProtocolGrpc = "grpc"
)
// VirtualGatewayPortProtocol_Values returns all elements of the VirtualGatewayPortProtocol enum
func VirtualGatewayPortProtocol_Values() []string {
return []string{
VirtualGatewayPortProtocolHttp,
VirtualGatewayPortProtocolHttp2,
VirtualGatewayPortProtocolGrpc,
}
}
const (
// VirtualGatewayStatusCodeActive is a VirtualGatewayStatusCode enum value
VirtualGatewayStatusCodeActive = "ACTIVE"
// VirtualGatewayStatusCodeInactive is a VirtualGatewayStatusCode enum value
VirtualGatewayStatusCodeInactive = "INACTIVE"
// VirtualGatewayStatusCodeDeleted is a VirtualGatewayStatusCode enum value
VirtualGatewayStatusCodeDeleted = "DELETED"
)
// VirtualGatewayStatusCode_Values returns all elements of the VirtualGatewayStatusCode enum
func VirtualGatewayStatusCode_Values() []string {
return []string{
VirtualGatewayStatusCodeActive,
VirtualGatewayStatusCodeInactive,
VirtualGatewayStatusCodeDeleted,
}
}
const (
// VirtualNodeStatusCodeActive is a VirtualNodeStatusCode enum value
VirtualNodeStatusCodeActive = "ACTIVE"
// VirtualNodeStatusCodeInactive is a VirtualNodeStatusCode enum value
VirtualNodeStatusCodeInactive = "INACTIVE"
// VirtualNodeStatusCodeDeleted is a VirtualNodeStatusCode enum value
VirtualNodeStatusCodeDeleted = "DELETED"
)
// VirtualNodeStatusCode_Values returns all elements of the VirtualNodeStatusCode enum
func VirtualNodeStatusCode_Values() []string {
return []string{
VirtualNodeStatusCodeActive,
VirtualNodeStatusCodeInactive,
VirtualNodeStatusCodeDeleted,
}
}
const (
// VirtualRouterStatusCodeActive is a VirtualRouterStatusCode enum value
VirtualRouterStatusCodeActive = "ACTIVE"
// VirtualRouterStatusCodeInactive is a VirtualRouterStatusCode enum value
VirtualRouterStatusCodeInactive = "INACTIVE"
// VirtualRouterStatusCodeDeleted is a VirtualRouterStatusCode enum value
VirtualRouterStatusCodeDeleted = "DELETED"
)
// VirtualRouterStatusCode_Values returns all elements of the VirtualRouterStatusCode enum
func VirtualRouterStatusCode_Values() []string {
return []string{
VirtualRouterStatusCodeActive,
VirtualRouterStatusCodeInactive,
VirtualRouterStatusCodeDeleted,
}
}
const (
// VirtualServiceStatusCodeActive is a VirtualServiceStatusCode enum value
VirtualServiceStatusCodeActive = "ACTIVE"
// VirtualServiceStatusCodeInactive is a VirtualServiceStatusCode enum value
VirtualServiceStatusCodeInactive = "INACTIVE"
// VirtualServiceStatusCodeDeleted is a VirtualServiceStatusCode enum value
VirtualServiceStatusCodeDeleted = "DELETED"
)
// VirtualServiceStatusCode_Values returns all elements of the VirtualServiceStatusCode enum
func VirtualServiceStatusCode_Values() []string {
return []string{
VirtualServiceStatusCodeActive,
VirtualServiceStatusCodeInactive,
VirtualServiceStatusCodeDeleted,
}
}
| [] | [] | [] | [] | [] | go | null | null | null |
rcnn/modeling/cascade_rcnn/inference.py | import torch
import torch.nn.functional as F
from torch import nn
from utils.data.structures.bounding_box import BoxList
from utils.data.structures.boxlist_ops import boxlist_nms, boxlist_soft_nms, boxlist_box_voting
from utils.data.structures.boxlist_ops import cat_boxlist
from rcnn.utils.box_coder import BoxCoder
from rcnn.core.config import cfg
import numpy as np
class PostProcessor(nn.Module):
"""
From a set of classification scores, box regression and proposals,
computes the post-processed boxes, and applies NMS to obtain the
final results
"""
def __init__(self, score_thresh=0.05, nms=0.5, detections_per_img=100, box_coder=None, cls_agnostic_bbox_reg=False,
is_repeat=False):
"""
Arguments:
score_thresh (float)
nms (float)
detections_per_img (int)
box_coder (BoxCoder)
"""
super(PostProcessor, self).__init__()
self.score_thresh = score_thresh
self.nms = nms
self.detections_per_img = detections_per_img
if box_coder is None:
box_coder = BoxCoder(weights=(10., 10., 5., 5.))
self.box_coder = box_coder
self.cls_agnostic_bbox_reg = cls_agnostic_bbox_reg
self.is_repeat = is_repeat
def forward(self, x, boxes, targets=None):
"""
Arguments:
x (tuple[tensor, tensor]): x contains the class logits
and the box_regression from the model.
boxes (list[BoxList]): bounding boxes that are used as
reference, one for ech image
targets (list[BoxList])
Returns:
results (list[BoxList]): one BoxList for each image, containing
the extra fields labels and scores
"""
assert self.cls_agnostic_bbox_reg, 'Use a class agnostic bounding box regressor in Cascade R-CNN'
class_logits, box_regression = x
class_prob = F.softmax(class_logits, -1)
# TODO think about a representation of batch of boxes
image_shapes = [box.size for box in boxes]
boxes_per_image = [len(box) for box in boxes]
concat_boxes = torch.cat([a.bbox for a in boxes], dim=0)
box_regression = box_regression[:, -4:]
proposals = self.box_coder.decode(box_regression.view(sum(boxes_per_image), -1), concat_boxes)
proposals[proposals < 0] = 0
if self.is_repeat:
proposals = proposals.repeat(1, class_prob.shape[1])
else:
proposals = proposals.split(boxes_per_image, dim=0)
refine_proposals = self.refine(boxes, targets, proposals)
return refine_proposals
num_classes = class_prob.shape[1]
proposals = proposals.split(boxes_per_image, dim=0)
class_prob = class_prob.split(boxes_per_image, dim=0)
results = []
for prob, boxes_per_img, image_shape in zip(class_prob, proposals, image_shapes):
boxlist = self.prepare_boxlist(boxes_per_img, prob, image_shape)
boxlist = boxlist.clip_to_image(remove_empty=False)
# boxlist = self.filter_results(boxlist, num_classes)
results.append(boxlist)
return results
def refine(self, boxes, targets, proposals):
"""Refine every stage box prediction and return the result"""
refine_proposals = []
if targets is not None:
for box, targets_per_image, proposals_per_image in zip(boxes, targets, proposals):
# remove mal-boxes with non-positive width or height and ground
# truth boxes during training
keep = self._filter_boxes(proposals_per_image, box, targets_per_image)
for field, value in box.extra_fields.items():
box.add_field(field, value[keep])
box.bbox = proposals_per_image[keep]
refine_proposals.append(box)
refine_proposals = self.add_gt_proposals(refine_proposals, targets)
else:
for box, proposals_per_image in zip(boxes, proposals):
box.bbox = proposals_per_image
refine_proposals.append(box)
return refine_proposals
def _filter_boxes(self, bbox, last, gt):
"""Only keep boxes with positive height and width, and not-gt.
"""
last_bbox = last.bbox
gt_bbox = gt.bbox
ws = bbox[:, 2] - bbox[:, 0] + 1
hs = bbox[:, 3] - bbox[:, 1] + 1
for i in range(gt_bbox.shape[0]):
last_bbox = torch.where(last_bbox == gt_bbox[i], torch.full_like(last_bbox, -1), last_bbox)
s = sum([last_bbox[:, 0], last_bbox[:, 1], last_bbox[:, 2], last_bbox[:, 3]])
keep = np.where((ws.cpu() > 0) & (hs.cpu() > 0) & (s.cpu() > 0))[0]
return keep
def add_gt_proposals(self, proposals, targets):
"""
Arguments:
proposals: list[BoxList]
targets: list[BoxList]
"""
# Get the device we're operating on
device = proposals[0].bbox.device
gt_boxes = [target.copy_with_fields(['labels']) for target in targets]
# later cat of bbox requires all fields to be present for all bbox
# so we need to add a dummy for objectness that's missing
# print(proposals[0].get_field("regression_targets").shape, len(gt_boxes[0]))
for gt_box in gt_boxes:
gt_box.add_field("objectness", torch.ones(len(gt_box), device=device))
gt_box.add_field("regression_targets", torch.zeros((len(gt_box), 4), device=device))
proposals = [
cat_boxlist((proposal, gt_box)) for proposal, gt_box in zip(proposals, gt_boxes)
]
return proposals
def prepare_boxlist(self, boxes, scores, image_shape):
"""
Returns BoxList from `boxes` and adds probability scores information
as an extra field
`boxes` has shape (#detections, 4 * #classes), where each row represents
a list of predicted bounding boxes for each of the object classes in the
dataset (including the background class). The detections in each row
originate from the same object proposal.
`scores` has shape (#detection, #classes), where each row represents a list
of object detection confidence scores for each of the object classes in the
dataset (including the background class). `scores[i, j]`` corresponds to the
box at `boxes[i, j * 4:(j + 1) * 4]`.
"""
boxes = boxes.reshape(-1, 4)
scores = scores.reshape(-1)
boxlist = BoxList(boxes, image_shape, mode="xyxy")
boxlist.add_field("scores", scores)
return boxlist
def box_post_processor(idx, is_train=True):
bbox_reg_weights = cfg.CASCADE_RCNN.BBOX_REG_WEIGHTS[idx]
box_coder = BoxCoder(weights=bbox_reg_weights)
score_thresh = cfg.FAST_RCNN.SCORE_THRESH
nms_thresh = cfg.FAST_RCNN.NMS
detections_per_img = cfg.FAST_RCNN.DETECTIONS_PER_IMG
cls_agnostic_bbox_reg = cfg.FAST_RCNN.CLS_AGNOSTIC_BBOX_REG
final_test_stage = (idx == cfg.CASCADE_RCNN.TEST_STAGE - 1)
final_train_stage = (idx == cfg.CASCADE_RCNN.NUM_STAGE - 1)
is_repeat = (is_train and final_train_stage) or (not is_train and final_test_stage)
postprocessor = PostProcessor(
score_thresh,
nms_thresh,
detections_per_img,
box_coder,
cls_agnostic_bbox_reg,
is_repeat,
)
return postprocessor
| [] | [] | [] | [] | [] | python | null | null | null |
src/pcgr/vcf2tsv.py | #!/usr/bin/env python
import argparse
from cyvcf2 import VCF, Writer
import numpy as np
import re
import math
import subprocess
version = '0.3.5'
def __main__():
parser = argparse.ArgumentParser(description='Convert a VCF file with genomic variants to a file with tab-separated values (TSV). One entry (TSV line) per sample genotype', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('query_vcf', help='Bgzipped input VCF file with query variants (SNVs/InDels)')
parser.add_argument('out_tsv', help='Output TSV file with one line pr non-rejected sample genotype (Variant, genotype and annotation data as tab-separated values)')
parser.add_argument("--skip_info_data",action = "store_true", help="Skip printing of data in INFO column")
parser.add_argument("--skip_genotype_data", action="store_true", help="Skip printing of genotype_data (FORMAT columns)")
parser.add_argument("--keep_rejected_calls", action="store_true", help="Print data for rejected calls")
parser.add_argument("--print_data_type_header", action="store_true", help="Print a header line with data types of VCF annotations")
parser.add_argument("--compress", action="store_true", help="Compress TSV file with gzip")
parser.add_argument('--version', action='version', version='%(prog)s ' + str(version))
args = parser.parse_args()
vcf2tsv(args.query_vcf, args.out_tsv, args.skip_info_data, args.skip_genotype_data, args.keep_rejected_calls, args.compress, args.print_data_type_header)
def check_subprocess(command):
try:
output = subprocess.check_output(str(command), stderr=subprocess.STDOUT, shell=True)
if len(output) > 0:
print (str(output.decode()).rstrip())
except subprocess.CalledProcessError as e:
print (e.output)
exit(0)
def vcf2tsv(query_vcf, out_tsv, skip_info_data, skip_genotype_data, keep_rejected_calls, compress, print_data_type_header):
vcf = VCF(query_vcf, gts012 = True)
out = open(out_tsv,'w')
fixed_columns_header = ['CHROM','POS','ID','REF','ALT','QUAL','FILTER']
fixed_columns_header_type = ['String','Integer','String','String','String','Float','String']
samples = vcf.samples
info_columns_header = []
format_columns_header = []
sample_columns_header = []
column_types = {}
gt_present_header = 0
if len(samples) > 0:
sample_columns_header.append('VCF_SAMPLE_ID')
for e in vcf.header_iter():
header_element = e.info()
if 'ID' in header_element.keys() and 'HeaderType' in header_element.keys():
if header_element['HeaderType'] == 'INFO' or header_element['HeaderType'] == 'FORMAT':
column_types[header_element['ID']] = header_element['Type']
if header_element['HeaderType'] == 'INFO':
if skip_info_data is False:
info_columns_header.append(header_element['ID'])
if header_element['HeaderType'] == 'FORMAT':
if len(sample_columns_header) > 0 and skip_genotype_data is False:
if header_element['ID'] != 'GT':
format_columns_header.append(header_element['ID'])
else:
gt_present_header = 1
#header_line = '\t'.join(fixed_columns_header)
header_tags = fixed_columns_header
if skip_info_data is False:
#header_line = '\t'.join(fixed_columns_header) + '\t' + '\t'.join(sorted(info_columns_header))
header_tags = fixed_columns_header + sorted(info_columns_header)
if len(sample_columns_header) > 0:
if skip_genotype_data is False:
#header_line = '\t'.join(fixed_columns_header) + '\t' + '\t'.join(sorted(info_columns_header)) + '\t' + '\t'.join(sample_columns_header) + '\t' + '\t'.join(sorted(format_columns_header)) + '\tGT'
header_tags = fixed_columns_header + sorted(info_columns_header) + sample_columns_header + sorted(format_columns_header) + ['GT']
else:
#header_line = '\t'.join(fixed_columns_header) + '\t' + '\t'.join(sorted(info_columns_header))
header_tags = fixed_columns_header + sorted(info_columns_header)
else:
if len(sample_columns_header) > 0:
if skip_genotype_data is False:
#header_line = '\t'.join(fixed_columns_header) + '\t' + '\t'.join(sample_columns_header) + '\t' + '\t'.join(sorted(format_columns_header)) + '\tGT'
header_tags = fixed_columns_header + sample_columns_header + sorted(format_columns_header) + ['GT']
else:
#header_line = '\t'.join(fixed_columns_header)
header_tags = fixed_columns_header
header_line = '\t'.join(header_tags)
out.write('#https://github.com/sigven/vcf2tsv version=' + str(version) + '\n')
if print_data_type_header is True:
#header_tags = header_line.rstrip().split('\t')
header_types = []
for h in header_tags:
if h in column_types:
header_types.append(str(column_types[h]))
#header_line_type = '\t'.join(fixed_columns_header_type) + '\t' + '\t'.join(header_types)
header_line_type = '\t'.join(fixed_columns_header_type + header_types)
out.write('#' + str(header_line_type) + '\n')
out.write(str(header_line) + '\n')
else:
out.write(str(header_line) + '\n')
for rec in vcf:
rec_id = '.'
rec_qual = '.'
rec_filter = '.'
alt = ",".join(str(n) for n in rec.ALT)
if not rec.ID is None:
rec_id = str(rec.ID)
if not rec.QUAL is None:
rec_qual = str("{0:.2f}".format(rec.QUAL))
rec_filter = str(rec.FILTER)
if rec.FILTER is None:
rec_filter = 'PASS'
pos = int(rec.start) + 1
fixed_fields_string = str(rec.CHROM) + '\t' + str(pos) + '\t' + str(rec_id) + '\t' + str(rec.REF) + '\t' + str(alt) + '\t' + str(rec_qual) + '\t' + str(rec_filter)
if not 'PASS' in rec_filter and not keep_rejected_calls:
continue
variant_info = rec.INFO
vcf_info_data = []
if skip_info_data is False:
for info_field in sorted(info_columns_header):
if column_types[info_field] == 'Flag':
if variant_info.get(info_field) is None:
vcf_info_data.append('False')
else:
vcf_info_data.append('True')
elif column_types[info_field] == 'Float' or column_types[info_field] == 'Integer' or column_types[info_field] == 'String' or column_types[info_field] == 'Character':
if type(variant_info.get(info_field)) is list or type(variant_info.get(info_field)) is tuple:
vcf_info_data.append(",".join(str(n) for n in variant_info.get(info_field)))
else:
if variant_info.get(info_field) is None:
vcf_info_data.append('.')
else:
if column_types[info_field] == 'Float':
if not isinstance(variant_info.get(info_field),float):
print('vcf2tsv.py WARNING:\tINFO tag ' + str(info_field) + ' is defined in the VCF header as type \'Float\', yet parsed as other type:' + str(type(variant_info.get(info_field))))
if not ',' in str(alt):
print('Warning: Multiple values in INFO tag for single ALT allele (VCF multiallelic sites not decomposed properly?):' + str(fixed_fields_string) + '\t' + str(info_field) + '=' + str(variant_info.get(info_field)))
vcf_info_data.append('.')
else:
val = str("{0:.7f}".format(variant_info.get(info_field)))
vcf_info_data.append(val)
else:
if column_types[info_field] == 'String' or column_types[info_field] == 'Character':
if isinstance(variant_info.get(info_field),str):
#print(str(info_field) + '\t' + variant_info.get(info_field).encode('ascii','ignore').rstrip().decode('ascii'))
vcf_info_data.append(variant_info.get(info_field).encode('ascii','ignore').decode('ascii'))
else:
vcf_info_data.append('.')
if column_types[info_field] == 'String':
print('vcf2tsv.py WARNING:\tINFO tag ' + str(info_field) + ' is defined in the VCF header as type \'String\', yet parsed as other type:' + str(type(variant_info.get(info_field))))
if column_types[info_field] == 'Character':
print('vcf2tsv.py WARNING:\tINFO tag ' + str(info_field) + ' is defined in the VCF header as type \'Character\', yet parsed as other type:' + str(type(variant_info.get(info_field))))
else:
if isinstance(variant_info.get(info_field),int):
vcf_info_data.append(str(variant_info.get(info_field)))
else:
print('vcf2tsv.py WARNING:\tINFO tag ' + str(info_field) + ' is defined in the VCF header as type \'Integer\', yet parsed as other type:' + str(type(variant_info.get(info_field))))
vcf_info_data.append(re.sub(r'\(|\)', '', variant_info.get(info_field).encode('ascii','ignore').decode('ascii')))
#print(str(vcf_info_data))
#dictionary, with sample names as keys, values being genotype data (dictionary with format tags as keys)
vcf_sample_genotype_data = {}
if len(samples) > 0 and skip_genotype_data is False:
gt_cyvcf = rec.gt_types
i = 0
while i < len(samples):
vcf_sample_genotype_data[samples[i]] = {}
gt = './.'
if gt_present_header == 1:
if gt_cyvcf[i] == 0:
gt = '0/0'
if gt_cyvcf[i] == 1:
gt = '0/1'
if gt_cyvcf[i] == 2:
gt = '1/1'
vcf_sample_genotype_data[samples[i]]['GT'] = gt
i = i + 1
for format_tag in sorted(format_columns_header):
if len(samples) > 0 and skip_genotype_data is False:
sample_dat = rec.format(format_tag)
if sample_dat is None:
k = 0
while k < len(samples):
if samples[k] in vcf_sample_genotype_data:
vcf_sample_genotype_data[samples[k]][format_tag] = '.'
k = k + 1
continue
dim = sample_dat.shape
j = 0
## sample-wise
while j < dim[0]:
if sample_dat[j].size > 1:
d = ','.join(str(e) for e in np.ndarray.tolist(sample_dat[j]))
if samples[j] in vcf_sample_genotype_data:
vcf_sample_genotype_data[samples[j]][format_tag] = d
else:
d = '.'
if column_types[format_tag] == 'Float':
if not math.isnan(sample_dat[j]):
d = str(sample_dat[j][0])
if column_types[format_tag] == 'String':
d = str(sample_dat[j])
if column_types[format_tag] == 'Integer':
d = str(sample_dat[j][0])
if samples[j] in vcf_sample_genotype_data:
vcf_sample_genotype_data[samples[j]][format_tag] = d
j = j + 1
#print(str(vcf_sample_genotype_data))
tsv_elements = []
tsv_elements.append(fixed_fields_string)
if skip_info_data is False:
if skip_genotype_data is False:
if len(sample_columns_header) > 0:
tsv_elements.append("\t".join(str(n) for n in vcf_info_data))
## one line per sample variant
for s in sorted(vcf_sample_genotype_data.keys()):
sample = s
line_elements = []
line_elements.extend(tsv_elements)
line_elements.append(sample)
gt_tag = '.'
for tag in sorted(vcf_sample_genotype_data[sample].keys()):
if tag != 'GT':
line_elements.append(vcf_sample_genotype_data[sample][tag].encode('ascii','ignore').decode('ascii'))
else:
gt_tag = vcf_sample_genotype_data[sample][tag].encode('ascii','ignore').decode('ascii')
line_elements.append(gt_tag)
if gt_tag == './.' or gt_tag == '.':
if keep_rejected_calls:
out.write('\t'.join(line_elements) + '\n')
else:
out.write("\t".join(str(n) for n in line_elements) + '\n')
else:
tsv_elements.append("\t".join(str(n) for n in vcf_info_data))
line_elements = []
line_elements.extend(tsv_elements)
out.write('\t'.join(line_elements) + '\n')
else:
tsv_elements.append("\t".join(str(n) for n in vcf_info_data))
line_elements = []
line_elements.extend(tsv_elements)
out.write('\t'.join(line_elements) + '\n')
else:
if skip_genotype_data is False:
if len(sample_columns_header) > 0:
## one line per sample variant
for s in sorted(vcf_sample_genotype_data.keys()):
sample = s
line_elements = []
line_elements.extend(tsv_elements)
line_elements.append(sample)
gt_tag = '.'
for tag in sorted(vcf_sample_genotype_data[sample].keys()):
if tag != 'GT':
line_elements.append(vcf_sample_genotype_data[sample][tag])
else:
gt_tag = vcf_sample_genotype_data[sample][tag]
line_elements.append(gt_tag)
if gt_tag == './.' or gt_tag == '.':
if keep_rejected_calls:
out.write('\t'.join(line_elements) + '\n')
else:
out.write('\t'.join(line_elements) + '\n')
else:
line_elements = []
line_elements.extend(tsv_elements)
line_elements = tsv_elements
out.write('\t'.join(line_elements) + '\n')
out.close()
if compress is True:
command = 'gzip -f ' + str(out_tsv)
check_subprocess(command)
if __name__=="__main__": __main__()
| [] | [] | [] | [] | [] | python | null | null | null |
tripleo_common/image/image_uploader.py | # Copyright 2015 Red Hat, Inc.
#
# 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.
#
import base64
from concurrent import futures
import hashlib
import json
import netifaces
import os
import random
import re
import requests
from requests import auth as requests_auth
from requests.adapters import HTTPAdapter
import shutil
import six
from six.moves.urllib import parse
import subprocess
import tempfile
import tenacity
import yaml
from oslo_concurrency import processutils
from oslo_log import log as logging
from tripleo_common.actions import ansible
from tripleo_common.image.base import BaseImageManager
from tripleo_common.image.exception import ImageNotFoundException
from tripleo_common.image.exception import ImageUploaderException
from tripleo_common.image.exception import ImageUploaderThreadException
from tripleo_common.image import image_export
from tripleo_common.utils import common as common_utils
from tripleo_common.utils.locks import threadinglock
LOG = logging.getLogger(__name__)
SECURE_REGISTRIES = (
'trunk.registry.rdoproject.org',
'docker.io',
'registry-1.docker.io',
)
NO_VERIFY_REGISTRIES = ()
CLEANUP = (
CLEANUP_FULL, CLEANUP_PARTIAL, CLEANUP_NONE
) = (
'full', 'partial', 'none'
)
CALL_TYPES = (
CALL_PING,
CALL_MANIFEST,
CALL_BLOB,
CALL_UPLOAD,
CALL_TAGS,
CALL_CATALOG
) = (
'/',
'%(image)s/manifests/%(tag)s',
'%(image)s/blobs/%(digest)s',
'%(image)s/blobs/uploads/',
'%(image)s/tags/list',
'/_catalog',
)
MEDIA_TYPES = (
MEDIA_MANIFEST_V1,
MEDIA_MANIFEST_V1_SIGNED,
MEDIA_MANIFEST_V2,
MEDIA_MANIFEST_V2_LIST,
MEDIA_CONFIG,
MEDIA_BLOB,
MEDIA_BLOB_COMPRESSED
) = (
'application/vnd.docker.distribution.manifest.v1+json',
'application/vnd.docker.distribution.manifest.v1+prettyjws',
'application/vnd.docker.distribution.manifest.v2+json',
'application/vnd.docker.distribution.manifest.list.v2+json',
'application/vnd.docker.container.image.v1+json',
'application/vnd.docker.image.rootfs.diff.tar',
'application/vnd.docker.image.rootfs.diff.tar.gzip'
)
DEFAULT_UPLOADER = 'python'
def get_undercloud_registry():
addr = 'localhost'
if 'br-ctlplane' in netifaces.interfaces():
addrs = netifaces.ifaddresses('br-ctlplane')
if netifaces.AF_INET in addrs and addrs[netifaces.AF_INET]:
addr = addrs[netifaces.AF_INET][0].get('addr', 'localhost')
elif netifaces.AF_INET6 in addrs and addrs[netifaces.AF_INET6]:
addr = addrs[netifaces.AF_INET6][0].get('addr', 'localhost')
return '%s:%s' % (common_utils.bracket_ipv6(addr), '8787')
class MakeSession(object):
"""Class method to uniformly create sessions.
Sessions created by this class will retry on errors with an exponential
backoff before raising an exception. Because our primary interaction is
with the container registries the adapter will also retry on 401 and
404. This is being done because registries commonly return 401 when an
image is not found, which is commonly a cache miss. See the adapter
definitions for more on retry details.
"""
def __init__(self, verify=True):
self.session = requests.Session()
self.session.verify = verify
adapter = HTTPAdapter(
max_retries=8,
pool_connections=24,
pool_maxsize=24,
pool_block=False
)
self.session.mount('http://', adapter)
self.session.mount('https://', adapter)
def create(self):
return self.__enter__()
def __enter__(self):
return self.session
def __exit__(self, *args, **kwargs):
self.session.close()
class ImageUploadManager(BaseImageManager):
"""Manage the uploading of image files
Manage the uploading of images from a config file specified in YAML
syntax. Multiple config files can be specified. They will be merged.
"""
def __init__(self, config_files=None,
dry_run=False, cleanup=CLEANUP_FULL,
mirrors=None, registry_credentials=None,
multi_arch=False, lock=None):
if config_files is None:
config_files = []
super(ImageUploadManager, self).__init__(config_files)
self.uploaders = {
'skopeo': SkopeoImageUploader(),
'python': PythonImageUploader(lock)
}
self.dry_run = dry_run
self.cleanup = cleanup
if mirrors:
for uploader in self.uploaders.values():
if hasattr(uploader, 'mirrors'):
uploader.mirrors.update(mirrors)
if registry_credentials:
self.validate_registry_credentials(registry_credentials)
for uploader in self.uploaders.values():
uploader.registry_credentials = registry_credentials
self.multi_arch = multi_arch
self.lock = lock
@staticmethod
def validate_registry_credentials(creds_data):
if not isinstance(creds_data, dict):
raise TypeError('Credentials data must be a dict')
for registry, cred_entry in creds_data.items():
if not isinstance(cred_entry, dict) or len(cred_entry) != 1:
raise TypeError('Credentials entry must be '
'a dict with a single item')
if not isinstance(registry, six.string_types):
raise TypeError('Key must be a registry host string: %s' %
registry)
username, password = next(iter(cred_entry.items()))
if not (isinstance(username, six.string_types) and
isinstance(password, six.string_types)):
raise TypeError('Username and password must be strings: %s' %
username)
def discover_image_tag(self, image, tag_from_label=None,
username=None, password=None):
uploader = self.uploader(DEFAULT_UPLOADER)
return uploader.discover_image_tag(
image, tag_from_label=tag_from_label,
username=username, password=password)
def uploader(self, uploader):
if uploader not in self.uploaders:
raise ImageUploaderException('Unknown image uploader type')
return self.uploaders[uploader]
def get_uploader(self, uploader):
return self.uploader(uploader)
@staticmethod
def get_push_destination(item):
push_destination = item.get('push_destination')
if not push_destination:
return get_undercloud_registry()
# If set to True, use discovered undercloud registry
if isinstance(push_destination, bool):
return get_undercloud_registry()
return push_destination
def upload(self):
"""Start the upload process"""
LOG.info('Using config files: %s' % self.config_files)
uploads = self.load_config_files(self.UPLOADS) or []
container_images = self.load_config_files(self.CONTAINER_IMAGES) or []
upload_images = uploads + container_images
tasks = []
for item in upload_images:
image_name = item.get('imagename')
uploader = item.get('uploader', DEFAULT_UPLOADER)
pull_source = item.get('pull_source')
push_destination = self.get_push_destination(item)
# This updates the parsed upload_images dict with real values
item['push_destination'] = push_destination
append_tag = item.get('modify_append_tag')
modify_role = item.get('modify_role')
modify_vars = item.get('modify_vars')
multi_arch = item.get('multi_arch', self.multi_arch)
uploader = self.uploader(uploader)
tasks.append(UploadTask(
image_name, pull_source, push_destination,
append_tag, modify_role, modify_vars, self.dry_run,
self.cleanup, multi_arch, self.lock))
# NOTE(mwhahaha): We want to randomize the upload process because of
# the shared nature of container layers. Because we multiprocess the
# handling of containers, if performed in an alphabetical order (the
# default) we end up duplicating fetching of container layers. Things
# Like cinder-volume and cinder-backup share almost all of the same
# layers so when they are fetched at the same time, we will duplicate
# the processing. By randomizing the list we will reduce the amount
# of duplicating that occurs. In my testing I went from ~30mins to
# ~20mins to run. In the future this could be improved if we added
# some locking to the container fetching based on layer hashes but
# will require a significant rewrite.
random.shuffle(tasks)
for task in tasks:
uploader.add_upload_task(task)
for uploader in self.uploaders.values():
uploader.run_tasks()
return upload_images # simply to make test validation easier
class BaseImageUploader(object):
mirrors = {}
insecure_registries = set()
no_verify_registries = set(NO_VERIFY_REGISTRIES)
secure_registries = set(SECURE_REGISTRIES)
export_registries = set()
push_registries = set()
def __init__(self, lock=None):
self.upload_tasks = []
# A mapping of layer hashs to the image which first copied that
# layer to the target
self.image_layers = {}
self.registry_credentials = {}
self.lock = lock
@classmethod
def init_registries_cache(cls):
cls.insecure_registries.clear()
cls.no_verify_registries.clear()
cls.no_verify_registries.update(NO_VERIFY_REGISTRIES)
cls.secure_registries.clear()
cls.secure_registries.update(SECURE_REGISTRIES)
cls.mirrors.clear()
cls.export_registries.clear()
cls.push_registries.clear()
def cleanup(self):
pass
def run_tasks(self):
pass
def credentials_for_registry(self, registry):
creds = self.registry_credentials.get(registry)
if not creds:
return None, None
username, password = next(iter(creds.items()))
return username, password
@classmethod
def run_modify_playbook(cls, modify_role, modify_vars,
source_image, target_image, append_tag,
container_build_tool='buildah'):
run_vars = {}
if modify_vars:
run_vars.update(modify_vars)
run_vars['source_image'] = source_image
run_vars['target_image'] = target_image
run_vars['modified_append_tag'] = append_tag
run_vars['container_build_tool'] = container_build_tool
LOG.info('Playbook variables: \n%s' % yaml.safe_dump(
run_vars, default_flow_style=False))
playbook = [{
'hosts': 'localhost',
'gather_facts': 'no',
'tasks': [{
'name': 'Import role %s' % modify_role,
'import_role': {
'name': modify_role
},
'vars': run_vars
}]
}]
LOG.info('Playbook: \n%s' % yaml.safe_dump(
playbook, default_flow_style=False))
work_dir = tempfile.mkdtemp(prefix='tripleo-modify-image-playbook-')
try:
action = ansible.AnsiblePlaybookAction(
playbook=playbook,
work_dir=work_dir,
verbosity=1,
extra_env_variables=dict(os.environ),
override_ansible_cfg=(
"[defaults]\n"
"stdout_callback=yaml\n"
)
)
result = action.run(None)
log_path = result.get('log_path')
if log_path and os.path.isfile(log_path):
with open(log_path) as f:
for line in f:
LOG.info(line.rstrip())
shutil.rmtree(work_dir)
except processutils.ProcessExecutionError as e:
LOG.error('%s\nError running playbook in directory: %s'
% (e.stdout, work_dir))
raise ImageUploaderException(
'Modifying image %s failed' % target_image)
@classmethod
def _images_match(cls, image1, image2, session1=None):
try:
image1_digest = cls._image_digest(image1, session=session1)
except Exception:
return False
try:
image2_digest = cls._image_digest(image2)
except Exception:
return False
# missing digest, no way to know if they match
if not image1_digest or not image2_digest:
return False
return image1_digest == image2_digest
@classmethod
def _image_digest(cls, image, session=None):
image_url = cls._image_to_url(image)
i = cls._inspect(image_url, session)
return i.get('Digest')
@classmethod
def _image_labels(cls, image_url, session=None):
i = cls._inspect(image_url, session)
return i.get('Labels', {}) or {}
@classmethod
def _image_exists(cls, image, session=None):
try:
cls._image_digest(
image, session=session)
except ImageNotFoundException:
return False
else:
return True
@tenacity.retry( # Retry up to 5 times with jittered exponential backoff
reraise=True,
retry=tenacity.retry_if_exception_type(
requests.exceptions.RequestException
),
wait=tenacity.wait_random_exponential(multiplier=1, max=10),
stop=tenacity.stop_after_attempt(5)
)
def authenticate(self, image_url, username=None, password=None,
session=None):
netloc = image_url.netloc
image, tag = self._image_tag_from_url(image_url)
self.is_insecure_registry(registry_host=netloc)
url = self._build_url(image_url, path='/')
verify = (netloc not in self.no_verify_registries)
if not session:
session = MakeSession(verify=verify).create()
else:
session.headers.pop('Authorization', None)
session.verify = verify
r = session.get(url, timeout=30)
LOG.debug('%s status code %s' % (url, r.status_code))
if r.status_code == 200:
return session
if r.status_code != 401:
r.raise_for_status()
if 'www-authenticate' not in r.headers:
raise ImageUploaderException(
'Unknown authentication method for headers: %s' % r.headers)
www_auth = r.headers['www-authenticate']
if not www_auth.startswith('Bearer '):
raise ImageUploaderException(
'Unknown www-authenticate value: %s' % www_auth)
token_param = {}
realm = re.search('realm="(.*?)"', www_auth).group(1)
if 'service=' in www_auth:
token_param['service'] = re.search(
'service="(.*?)"', www_auth).group(1)
token_param['scope'] = 'repository:%s:pull' % image[1:]
auth = None
if username:
auth = requests_auth.HTTPBasicAuth(username, password)
LOG.debug('Token parameters: params {}'.format(token_param))
rauth = session.get(realm, params=token_param, auth=auth, timeout=30)
rauth.raise_for_status()
session.headers['Authorization'] = 'Bearer %s' % rauth.json()['token']
hash_request_id = hashlib.sha1(str(rauth.url).encode())
LOG.debug(
'Session authenticated: id {}'.format(
hash_request_id.hexdigest()
)
)
setattr(session, 'reauthenticate', self.authenticate)
setattr(
session,
'auth_args',
dict(
image_url=image_url,
username=username,
password=password,
session=session
)
)
return session
@staticmethod
def _get_response_text(response, encoding='utf-8', force_encoding=False):
"""Return request response text
We need to set the encoding for the response other wise it
will attempt to detect the encoding which is very time consuming.
See https://github.com/psf/requests/issues/4235 for additional
context.
:param: response: requests Respoinse object
:param: encoding: encoding to set if not currently set
:param: force_encoding: set response encoding always
"""
if force_encoding or not response.encoding:
response.encoding = encoding
return response.text
@staticmethod
def check_status(session, request, allow_reauth=True):
hash_request_id = hashlib.sha1(str(request.url).encode())
request_id = hash_request_id.hexdigest()
text = getattr(request, 'text', 'unknown')
reason = getattr(request, 'reason', 'unknown')
status_code = getattr(request, 'status_code', None)
headers = getattr(request, 'headers', {})
session_headers = getattr(session, 'headers', {})
if status_code >= 300:
LOG.info(
'Non-2xx: id {}, status {}, reason {}, text {}'.format(
request_id,
status_code,
reason,
text
)
)
if status_code == 401:
LOG.warning(
'Failure: id {}, status {}, reason {} text {}'.format(
request_id,
status_code,
reason,
text
)
)
LOG.debug(
'Request headers after 401: id {}, headers {}'.format(
request_id,
headers
)
)
LOG.debug(
'Session headers after 401: id {}, headers {}'.format(
request_id,
session_headers
)
)
www_auth = headers.get(
'www-authenticate',
headers.get(
'Www-Authenticate'
)
)
if www_auth:
error = None
if 'error=' in www_auth:
error = re.search('error="(.*?)"', www_auth).group(1)
LOG.warning(
'Error detected in auth headers: error {}'.format(
error
)
)
if error == 'invalid_token' and allow_reauth:
if hasattr(session, 'reauthenticate'):
reauth = int(session.headers.get('_TripleOReAuth', 0))
reauth += 1
session.headers['_TripleOReAuth'] = str(reauth)
LOG.warning(
'Re-authenticating: id {}, count {}'.format(
request_id,
reauth
)
)
session.reauthenticate(**session.auth_args)
request.raise_for_status()
@classmethod
def _build_url(cls, url, path):
netloc = url.netloc
if netloc in cls.mirrors:
mirror = cls.mirrors[netloc]
return '%sv2%s' % (mirror, path)
else:
if not cls.is_insecure_registry(registry_host=netloc):
scheme = 'https'
else:
scheme = 'http'
if netloc == 'docker.io':
netloc = 'registry-1.docker.io'
return '%s://%s/v2%s' % (scheme, netloc, path)
@classmethod
def _image_tag_from_url(cls, image_url):
if '@' in image_url.path:
parts = image_url.path.split('@')
else:
parts = image_url.path.split(':')
tag = parts[-1]
image = ':'.join(parts[:-1])
return image, tag
@classmethod
@tenacity.retry( # Retry up to 5 times with jittered exponential backoff
reraise=True,
retry=tenacity.retry_if_exception_type(
requests.exceptions.RequestException
),
wait=tenacity.wait_random_exponential(multiplier=1, max=10),
stop=tenacity.stop_after_attempt(5)
)
def _inspect(cls, image_url, session=None):
image, tag = cls._image_tag_from_url(image_url)
parts = {
'image': image,
'tag': tag
}
manifest_url = cls._build_url(
image_url, CALL_MANIFEST % parts
)
tags_url = cls._build_url(
image_url, CALL_TAGS % parts
)
manifest_headers = {'Accept': MEDIA_MANIFEST_V2}
manifest_r = session.get(manifest_url, headers=manifest_headers,
timeout=30)
if manifest_r.status_code in (403, 404):
raise ImageNotFoundException('Not found image: %s' %
image_url.geturl())
cls.check_status(session=session, request=manifest_r)
tags_r = session.get(tags_url, timeout=30)
cls.check_status(session=session, request=tags_r)
manifest_str = cls._get_response_text(manifest_r)
if 'Docker-Content-Digest' in manifest_r.headers:
digest = manifest_r.headers['Docker-Content-Digest']
else:
# The registry didn't supply the manifest digest, so calculate it
calc_digest = hashlib.sha256()
calc_digest.update(manifest_str.encode('utf-8'))
digest = 'sha256:%s' % calc_digest.hexdigest()
manifest = json.loads(manifest_str)
if manifest.get('schemaVersion', 2) == 1:
config = json.loads(manifest['history'][0]['v1Compatibility'])
layers = list(reversed([l['blobSum']
for l in manifest['fsLayers']]))
else:
layers = [l['digest'] for l in manifest['layers']]
parts['digest'] = manifest['config']['digest']
config_headers = {
'Accept': manifest['config']['mediaType']
}
config_url = cls._build_url(
image_url, CALL_BLOB % parts)
config_r = session.get(config_url, headers=config_headers,
timeout=30)
cls.check_status(session=session, request=config_r)
config = config_r.json()
tags = tags_r.json()['tags']
image, tag = cls._image_tag_from_url(image_url)
name = '%s%s' % (image_url.netloc, image)
created = config['created']
docker_version = config.get('docker_version', '')
labels = config['config']['Labels']
architecture = config['architecture']
image_os = config['os']
return {
'Name': name,
'Tag': tag,
'Digest': digest,
'RepoTags': tags,
'Created': created,
'DockerVersion': docker_version,
'Labels': labels,
'Architecture': architecture,
'Os': image_os,
'Layers': layers,
}
def list(self, registry, session=None):
self.is_insecure_registry(registry_host=registry)
url = self._image_to_url(registry)
catalog_url = self._build_url(
url, CALL_CATALOG
)
catalog_resp = session.get(catalog_url, timeout=30)
if catalog_resp.status_code in [200]:
catalog = catalog_resp.json()
elif catalog_resp.status_code in [404]:
# just return since the catalog returned a 404
LOG.debug('catalog_url return 404')
return []
else:
raise ImageUploaderException(
'Image registry made invalid response: %s' %
catalog_resp.status_code
)
tags_get_args = []
for repo in catalog.get('repositories', []):
image = '%s/%s' % (registry, repo)
tags_get_args.append((self, image, session))
images = []
with futures.ThreadPoolExecutor(max_workers=16) as p:
for image, tags in p.map(tags_for_image, tags_get_args):
if not tags:
continue
for tag in tags:
images.append('%s:%s' % (image, tag))
return images
def inspect(self, image, session=None):
image_url = self._image_to_url(image)
return self._inspect(image_url, session)
def delete(self, image, session=None):
image_url = self._image_to_url(image)
return self._delete(image_url, session)
@classmethod
def _delete(cls, image, session=None):
raise NotImplementedError()
@classmethod
@tenacity.retry( # Retry up to 5 times with jittered exponential backoff
reraise=True,
retry=tenacity.retry_if_exception_type(
requests.exceptions.RequestException
),
wait=tenacity.wait_random_exponential(multiplier=1, max=10),
stop=tenacity.stop_after_attempt(5)
)
def _tags_for_image(cls, image, session):
url = cls._image_to_url(image)
parts = {
'image': url.path,
}
tags_url = cls._build_url(
url, CALL_TAGS % parts
)
r = session.get(tags_url, timeout=30)
if r.status_code in (403, 404):
return image, []
tags = r.json()
return image, tags.get('tags', [])
@classmethod
def _image_to_url(cls, image):
if '://' not in image:
image = 'docker://' + image
url = parse.urlparse(image)
return url
@classmethod
def _discover_tag_from_inspect(cls, i, image, tag_from_label=None,
fallback_tag=None):
labels = i.get('Labels', {})
if hasattr(labels, 'keys'):
label_keys = ', '.join(labels.keys())
else:
label_keys = ""
if not tag_from_label:
raise ImageUploaderException(
'No label specified. Available labels: %s' % label_keys
)
if "{" in tag_from_label:
try:
tag_label = tag_from_label.format(**labels)
except ValueError as e:
raise ImageUploaderException(e)
except KeyError as e:
if fallback_tag:
tag_label = fallback_tag
else:
raise ImageUploaderException(
'Image %s %s. Available labels: %s' %
(image, e, label_keys)
)
else:
tag_label = None
if isinstance(labels, dict):
tag_label = labels.get(tag_from_label)
if tag_label is None:
if fallback_tag:
tag_label = fallback_tag
else:
raise ImageUploaderException(
'Image %s has no label %s. Available labels: %s' %
(image, tag_from_label, label_keys)
)
# confirm the tag exists by checking for an entry in RepoTags
repo_tags = i.get('RepoTags', [])
if tag_label not in repo_tags:
raise ImageUploaderException(
'Image %s has no tag %s.\nAvailable tags: %s' %
(image, tag_label, ', '.join(repo_tags))
)
return tag_label
def discover_image_tags(self, images, tag_from_label=None):
image_urls = [self._image_to_url(i) for i in images]
# prime self.insecure_registries by testing every image
for url in image_urls:
self.is_insecure_registry(registry_host=url)
discover_args = []
for image in images:
discover_args.append((self, image, tag_from_label))
versioned_images = {}
with futures.ThreadPoolExecutor(max_workers=16) as p:
for image, versioned_image in p.map(discover_tag_from_inspect,
discover_args):
versioned_images[image] = versioned_image
return versioned_images
def discover_image_tag(self, image, tag_from_label=None,
fallback_tag=None, username=None, password=None):
image_url = self._image_to_url(image)
self.is_insecure_registry(registry_host=image_url.netloc)
session = self.authenticate(
image_url, username=username, password=password)
i = self._inspect(image_url, session)
return self._discover_tag_from_inspect(i, image, tag_from_label,
fallback_tag)
def filter_images_with_labels(self, images, labels,
username=None, password=None):
images_with_labels = []
for image in images:
url = self._image_to_url(image)
self.is_insecure_registry(registry_host=url.netloc)
session = self.authenticate(
url, username=username, password=password)
image_labels = self._image_labels(
url, session=session)
if set(labels).issubset(set(image_labels)):
images_with_labels.append(image)
return images_with_labels
def add_upload_task(self, task):
if task.modify_role and task.multi_arch:
raise ImageUploaderException(
'Cannot run a modify role on multi-arch image %s' %
task.image_name
)
# prime insecure_registries
if task.pull_source:
self.is_insecure_registry(
registry_host=self._image_to_url(task.pull_source).netloc
)
else:
self.is_insecure_registry(
registry_host=self._image_to_url(task.image_name).netloc
)
self.is_insecure_registry(
registry_host=self._image_to_url(task.push_destination).netloc
)
self.upload_tasks.append((self, task))
@classmethod
def is_insecure_registry(cls, registry_host):
if registry_host in cls.secure_registries:
return False
if (registry_host in cls.insecure_registries or
registry_host in cls.no_verify_registries):
return True
with requests.Session() as s:
try:
s.get('https://%s/v2' % registry_host, timeout=30)
except requests.exceptions.SSLError:
# Might be just a TLS certificate validation issue
# Just retry without the verification
try:
s.get('https://%s/v2' % registry_host, timeout=30,
verify=False)
cls.no_verify_registries.add(registry_host)
# Techinically these type of registries are insecure when
# the container engine tries to do a pull. The python
# uploader ignores the certificate problem, but they are
# still inscure so we return True here while we'll still
# use https when we access the registry. LP#1833751
return True
except requests.exceptions.SSLError:
# So nope, it's really not a certificate verification issue
cls.insecure_registries.add(registry_host)
return True
except Exception:
# for any other error assume it is a secure registry, because:
# - it is secure registry
# - the host is not accessible
pass
cls.secure_registries.add(registry_host)
return False
@classmethod
@tenacity.retry( # Retry up to 5 times with jittered exponential backoff
reraise=True,
retry=tenacity.retry_if_exception_type(
requests.exceptions.RequestException
),
wait=tenacity.wait_random_exponential(multiplier=1, max=10),
stop=tenacity.stop_after_attempt(5)
)
def _cross_repo_mount(cls, target_image_url, image_layers,
source_layers, session):
netloc = target_image_url.netloc
name = target_image_url.path.split(':')[0][1:]
export = netloc in cls.export_registries
if export:
image_export.cross_repo_mount(
target_image_url, image_layers, source_layers)
return
if netloc in cls.insecure_registries:
scheme = 'http'
else:
scheme = 'https'
url = '%s://%s/v2/%s/blobs/uploads/' % (scheme, netloc, name)
for layer in source_layers:
if layer in image_layers:
existing_name = image_layers[layer].path.split(':')[0][1:]
LOG.info('[%s] Cross repository blob mount from %s' %
(layer, existing_name))
data = {
'mount': layer,
'from': existing_name
}
r = session.post(url, data=data, timeout=30)
cls.check_status(session=session, request=r)
LOG.debug('%s %s' % (r.status_code, r.reason))
class SkopeoImageUploader(BaseImageUploader):
"""Upload images using skopeo copy"""
def upload_image(self, task):
t = task
LOG.info('[%s] Got imagename' % t.image_name)
source_image_local_url = parse.urlparse('containers-storage:%s'
% t.source_image)
target_image_local_url = parse.urlparse('containers-storage:%s' %
t.target_image)
if t.dry_run:
return []
target_username, target_password = self.credentials_for_registry(
t.target_image_url.netloc)
target_session = self.authenticate(
t.target_image_url,
username=target_username,
password=target_password
)
image_exists = False
try:
image_exists = self._image_exists(t.target_image,
target_session)
except Exception:
LOG.warning('[%s] Failed to check if the target '
'image exists' % t.target_image)
pass
if t.modify_role and image_exists:
LOG.warning('[%s] Skipping upload for modified '
'image' % t.target_image)
target_session.close()
return []
# Keep the target session open yet
source_username, source_password = self.credentials_for_registry(
t.source_image_url.netloc)
source_session = self.authenticate(
t.source_image_url,
username=source_username,
password=source_password
)
try:
source_inspect = self._inspect(
t.source_image_url,
session=source_session)
source_layers = source_inspect.get('Layers', [])
self._cross_repo_mount(
t.target_image_url, self.image_layers, source_layers,
session=target_session)
except Exception:
LOG.error('[%s] Failed uploading the target '
'image' % t.target_image)
raise
finally:
source_session.close()
target_session.close()
to_cleanup = []
if t.modify_role:
# Copy from source registry to local storage
self._copy(
t.source_image_url,
source_image_local_url,
)
if t.cleanup in (CLEANUP_FULL, CLEANUP_PARTIAL):
to_cleanup = [t.source_image]
self.run_modify_playbook(
t.modify_role, t.modify_vars, t.source_image,
t.target_image_source_tag, t.append_tag,
container_build_tool='buildah')
if t.cleanup == CLEANUP_FULL:
to_cleanup.append(t.target_image)
# Copy from local storage to target registry
self._copy(
target_image_local_url,
t.target_image_url,
)
for layer in source_layers:
self.image_layers.setdefault(layer, t.target_image_url)
LOG.warning('[%s] Completed modify and upload for '
'image' % t.image_name)
else:
self._copy(
t.source_image_url,
t.target_image_url,
)
LOG.warning('[%s] Completed upload for image' % t.image_name)
for layer in source_layers:
self.image_layers.setdefault(layer, t.target_image_url)
return to_cleanup
@classmethod
@tenacity.retry( # Retry up to 5 times with jittered exponential backoff
reraise=True,
wait=tenacity.wait_random_exponential(multiplier=1, max=10),
stop=tenacity.stop_after_attempt(5)
)
def _copy(cls, source_url, target_url):
source = source_url.geturl()
target = target_url.geturl()
LOG.info('Copying from %s to %s' % (source, target))
cmd = ['skopeo', 'copy']
if source_url.netloc in [cls.insecure_registries,
cls.no_verify_registries]:
cmd.append('--src-tls-verify=false')
if target_url.netloc in [cls.insecure_registries,
cls.no_verify_registries]:
cmd.append('--dest-tls-verify=false')
cmd.append(source)
cmd.append(target)
LOG.info('Running %s' % ' '.join(cmd))
env = os.environ.copy()
process = subprocess.Popen(cmd, env=env, stdout=subprocess.PIPE,
universal_newlines=True)
out, err = process.communicate()
LOG.info(out)
if process.returncode != 0:
raise ImageUploaderException('Error copying image:\n%s\n%s' %
(' '.join(cmd), err))
return out
def _delete(self, image_url, session=None):
insecure = self.is_insecure_registry(registry_host=image_url.netloc)
image = image_url.geturl()
LOG.info('[%s] Deleting image' % image)
cmd = ['skopeo', 'delete']
if insecure:
cmd.append('--tls-verify=false')
cmd.append(image)
LOG.info('Running %s' % ' '.join(cmd))
env = os.environ.copy()
process = subprocess.Popen(cmd, env=env, stdout=subprocess.PIPE,
universal_newlines=True)
out, err = process.communicate()
LOG.info(out.decode('utf-8'))
if process.returncode != 0:
raise ImageUploaderException('Error deleting image:\n%s\n%s' %
(' '.join(cmd), err))
return out
def cleanup(self, local_images):
if not local_images:
return []
for image in sorted(local_images):
if not image:
continue
LOG.warning('[%s] Removing local copy of image' % image)
image_url = parse.urlparse('containers-storage:%s' % image)
self._delete(image_url)
def run_tasks(self):
if not self.upload_tasks:
return
local_images = []
# Pull a single image first, to avoid duplicate pulls of the
# same base layers
local_images.extend(upload_task(args=self.upload_tasks.pop()))
# workers will be half the CPU count, to a minimum of 2
workers = max(2, (processutils.get_worker_count() - 1))
with futures.ThreadPoolExecutor(max_workers=workers) as p:
for result in p.map(upload_task, self.upload_tasks):
local_images.extend(result)
LOG.info('result %s' % local_images)
# Do cleanup after all the uploads so common layers don't get deleted
# repeatedly
self.cleanup(local_images)
class PythonImageUploader(BaseImageUploader):
"""Upload images using a direct implementation of the registry API"""
@classmethod
@tenacity.retry( # Retry until we no longer have collisions
retry=tenacity.retry_if_exception_type(ImageUploaderThreadException),
wait=tenacity.wait_random_exponential(multiplier=1, max=10)
)
def _layer_fetch_lock(cls, layer, lock=None):
if not lock:
LOG.warning('No lock information provided for layer %s' % layer)
return
if layer in lock.objects():
LOG.debug('[%s] Layer is being fetched by another thread' % layer)
raise ImageUploaderThreadException('layer being fetched')
LOG.debug('Locking layer %s' % layer)
LOG.debug('Starting acquire for lock %s' % layer)
with lock.get_lock():
if layer in lock.objects():
LOG.debug('Collision for lock %s' % layer)
raise ImageUploaderThreadException('layer conflict')
LOG.debug('Acquired for lock %s' % layer)
lock.objects().append(layer)
LOG.debug('Updated lock info %s' % layer)
LOG.debug('Got lock on layer %s' % layer)
@classmethod
def _layer_fetch_unlock(cls, layer, lock=None):
if not lock:
LOG.warning('No lock information provided for layer %s' % layer)
return
LOG.debug('Unlocking layer %s' % layer)
LOG.debug('Starting acquire for lock %s' % layer)
with lock.get_lock():
LOG.debug('Acquired for unlock %s' % layer)
if layer in lock.objects():
lock.objects().remove(layer)
LOG.debug('Updated lock info %s' % layer)
LOG.debug('Released lock on layer %s' % layer)
def upload_image(self, task):
"""Upload image from a task
This function takes an UploadTask and pushes it to the appropriate
target destinations. It should be noted that if the source container
is prefix with 'containers-storage:' instead of 'docker://' or no
prefix, this process will assume that the source container is already
local to the system. The local container upload does not currently
support any of the modification actions. In order to run the
modification actions on a container prior to upload, the source must
be a remote image. Additionally, cleanup has no affect when
uploading a local image as well.
:param: task: UploadTask with container information
"""
t = task
LOG.info('[%s] Starting upload image process' % t.image_name)
source_local = t.source_image.startswith('containers-storage:')
target_image_local_url = parse.urlparse('containers-storage:%s' %
t.target_image)
if t.dry_run:
return []
lock = t.lock
target_username, target_password = self.credentials_for_registry(
t.target_image_url.netloc)
target_session = self.authenticate(
t.target_image_url,
username=target_username,
password=target_password
)
try:
self._detect_target_export(t.target_image_url, target_session)
except Exception:
LOG.error('[%s] Failed uploading the target '
'image' % t.target_image)
# Close the session before raising it for more of retrying perhaps
target_session.close()
raise
if source_local:
if t.modify_role:
target_session.close()
raise NotImplementedError('Modify role not implemented for '
'local containers')
if t.cleanup:
LOG.warning('[%s] Cleanup has no effect with a local source '
'container.' % t.image_name)
try:
source_local_url = parse.urlparse(t.source_image)
# Copy from local storage to target registry
self._copy_local_to_registry(
source_local_url,
t.target_image_url,
session=target_session
)
except Exception:
LOG.warning('[%s] Failed copying the target image '
'to the target registry' % t.target_image)
pass
target_session.close()
return []
if t.modify_role:
image_exists = False
try:
image_exists = self._image_exists(t.target_image,
target_session)
except Exception:
LOG.warning('[%s] Failed to check if the target '
'image exists' % t.target_image)
pass
if image_exists:
LOG.warning('[%s] Skipping upload for modified image %s' %
(t.image_name, t.target_image))
target_session.close()
return []
copy_target_url = t.target_image_source_tag_url
else:
copy_target_url = t.target_image_url
# Keep the target session open yet
source_username, source_password = self.credentials_for_registry(
t.source_image_url.netloc)
source_session = self.authenticate(
t.source_image_url,
username=source_username,
password=source_password
)
source_layers = []
manifests_str = []
try:
self._collect_manifests_layers(
t.source_image_url, source_session,
manifests_str, source_layers,
t.multi_arch
)
self._cross_repo_mount(
copy_target_url, self.image_layers, source_layers,
session=target_session)
to_cleanup = []
# Copy unmodified images from source to target
self._copy_registry_to_registry(
t.source_image_url,
copy_target_url,
source_manifests=manifests_str,
source_session=source_session,
target_session=target_session,
source_layers=source_layers,
multi_arch=t.multi_arch,
lock=lock
)
except Exception:
LOG.error('[%s] Failed uploading the target '
'image' % t.target_image)
# Close the sessions before raising it for more of
# retrying perhaps
source_session.close()
target_session.close()
raise
if not t.modify_role:
LOG.info('[%s] Completed upload for image' % t.image_name)
else:
LOG.info('[%s] Copy ummodified image from target to local' %
t.image_name)
try:
self._copy_registry_to_local(t.target_image_source_tag_url)
if t.cleanup in (CLEANUP_FULL, CLEANUP_PARTIAL):
to_cleanup.append(t.target_image_source_tag)
self.run_modify_playbook(
t.modify_role,
t.modify_vars,
t.target_image_source_tag,
t.target_image_source_tag,
t.append_tag,
container_build_tool='buildah')
if t.cleanup == CLEANUP_FULL:
to_cleanup.append(t.target_image)
# cross-repo mount the unmodified image to the modified image
self._cross_repo_mount(
t.target_image_url, self.image_layers, source_layers,
session=target_session)
# Copy from local storage to target registry
self._copy_local_to_registry(
target_image_local_url,
t.target_image_url,
session=target_session
)
LOG.info('[%s] Completed modify and upload for image' %
t.image_name)
except Exception:
LOG.error('[%s] Failed processing the target '
'image' % t.target_image)
# Close the sessions before raising it for more of
# retrying perhaps
source_session.close()
target_session.close()
raise
try:
for layer in source_layers:
self.image_layers.setdefault(layer, t.target_image_url)
except Exception:
LOG.warning('[%s] Failed setting default layer %s for the '
'target image' % (t.target_image, layer))
pass
target_session.close()
source_session.close()
return to_cleanup
@classmethod
@tenacity.retry( # Retry up to 5 times with jittered exponential backoff
reraise=True,
retry=tenacity.retry_if_exception_type(
requests.exceptions.RequestException
),
wait=tenacity.wait_random_exponential(multiplier=1, max=10),
stop=tenacity.stop_after_attempt(5)
)
def _detect_target_export(cls, image_url, session):
if image_url.netloc in cls.export_registries:
return True
if image_url.netloc in cls.push_registries:
return False
# detect if the registry is push-capable by requesting an upload URL.
image, _ = cls._image_tag_from_url(image_url)
upload_req_url = cls._build_url(
image_url,
path=CALL_UPLOAD % {'image': image})
r = session.post(upload_req_url, timeout=30)
if r.status_code in (501, 403, 404, 405):
cls.export_registries.add(image_url.netloc)
return True
cls.check_status(session=session, request=r)
cls.push_registries.add(image_url.netloc)
return False
@classmethod
@tenacity.retry( # Retry up to 5 times with jittered exponential backoff
reraise=True,
retry=tenacity.retry_if_exception_type(
requests.exceptions.RequestException
),
wait=tenacity.wait_random_exponential(multiplier=1, max=10),
stop=tenacity.stop_after_attempt(5)
)
def _fetch_manifest(cls, url, session, multi_arch):
image, tag = cls._image_tag_from_url(url)
parts = {
'image': image,
'tag': tag
}
url = cls._build_url(
url, CALL_MANIFEST % parts
)
if multi_arch:
manifest_headers = {'Accept': MEDIA_MANIFEST_V2_LIST}
else:
manifest_headers = {'Accept': MEDIA_MANIFEST_V2}
r = session.get(url, headers=manifest_headers, timeout=30)
if r.status_code in (403, 404):
raise ImageNotFoundException('Not found image: %s' % url)
cls.check_status(session=session, request=r)
return cls._get_response_text(r)
def _collect_manifests_layers(self, image_url, session,
manifests_str, layers,
multi_arch):
manifest_str = self._fetch_manifest(
image_url,
session=session,
multi_arch=multi_arch
)
manifests_str.append(manifest_str)
manifest = json.loads(manifest_str)
if manifest.get('schemaVersion', 2) == 1:
layers.extend(reversed([l['blobSum']
for l in manifest['fsLayers']]))
elif manifest.get('mediaType') == MEDIA_MANIFEST_V2:
layers.extend(l['digest'] for l in manifest['layers'])
elif manifest.get('mediaType') == MEDIA_MANIFEST_V2_LIST:
image, _, tag = image_url.geturl().rpartition(':')
for man in manifest.get('manifests', []):
# replace image tag with the manifest hash in the list
man_url = parse.urlparse('%s@%s' % (image, man['digest']))
self._collect_manifests_layers(
man_url, session, manifests_str, layers,
multi_arch=False
)
@classmethod
@tenacity.retry( # Retry up to 5 times with jittered exponential backoff
reraise=True,
retry=tenacity.retry_if_exception_type(
requests.exceptions.RequestException
),
wait=tenacity.wait_random_exponential(multiplier=1, max=10),
stop=tenacity.stop_after_attempt(5)
)
def _upload_url(cls, image_url, session, previous_request=None):
if previous_request and 'Location' in previous_request.headers:
return previous_request.headers['Location']
image, tag = cls._image_tag_from_url(image_url)
upload_req_url = cls._build_url(
image_url,
path=CALL_UPLOAD % {'image': image})
r = session.post(upload_req_url, timeout=30)
cls.check_status(session=session, request=r)
return r.headers['Location']
@classmethod
@tenacity.retry( # Retry up to 5 times with jittered exponential backoff
reraise=True,
retry=tenacity.retry_if_exception_type(
requests.exceptions.RequestException
),
wait=tenacity.wait_random_exponential(multiplier=1, max=10),
stop=tenacity.stop_after_attempt(5)
)
def _layer_stream_registry(cls, digest, source_url, calc_digest,
session):
image, tag = cls._image_tag_from_url(source_url)
parts = {
'image': image,
'tag': tag,
'digest': digest
}
source_blob_url = cls._build_url(
source_url, CALL_BLOB % parts)
# NOTE(aschultz): We specify None and let requests figure it out
chunk_size = None
LOG.info("[%s] Fetching layer %s from %s" %
(image, digest, source_blob_url))
with session.get(
source_blob_url, stream=True, timeout=30) as blob_req:
# TODO(aschultz): unsure if necessary or if only when using .text
blob_req.encoding = 'utf-8'
cls.check_status(session=session, request=blob_req)
for data in blob_req.iter_content(chunk_size):
LOG.debug("[%s] Read %i bytes for %s" %
(image, len(data), digest))
if not data:
break
calc_digest.update(data)
yield data
LOG.info("[%s] Done fetching layer %s from registry" % (image, digest))
@classmethod
@tenacity.retry( # Retry up to 5 times with jittered exponential backoff
reraise=True,
retry=tenacity.retry_if_exception_type(
IOError
),
wait=tenacity.wait_random_exponential(multiplier=1, max=10),
stop=tenacity.stop_after_attempt(5)
)
def _copy_layer_registry_to_registry(cls, source_url, target_url,
layer,
source_session=None,
target_session=None,
lock=None):
layer_entry = {'digest': layer}
try:
cls._layer_fetch_lock(layer)
if cls._target_layer_exists_registry(
target_url, layer_entry, [layer_entry], target_session):
cls._layer_fetch_unlock(layer, lock)
return
except ImageUploaderThreadException:
# skip trying to unlock, because that's what threw the exception
raise
except Exception:
cls._layer_fetch_unlock(layer, lock)
raise
digest = layer_entry['digest']
LOG.debug('[%s] Uploading layer' % digest)
calc_digest = hashlib.sha256()
try:
layer_stream = cls._layer_stream_registry(
digest, source_url, calc_digest, source_session)
layer_val = cls._copy_stream_to_registry(
target_url, layer_entry, calc_digest, layer_stream,
target_session)
except Exception:
raise
else:
return layer_val
finally:
cls._layer_fetch_unlock(layer, lock)
@classmethod
def _assert_scheme(cls, url, scheme):
if url.scheme != scheme:
raise ImageUploaderException(
'Expected %s scheme: %s' % (scheme, url.geturl()))
@classmethod
@tenacity.retry( # Retry up to 5 times with jittered exponential backoff
reraise=True,
retry=tenacity.retry_if_exception_type(
requests.exceptions.RequestException
),
wait=tenacity.wait_random_exponential(multiplier=1, max=10),
stop=tenacity.stop_after_attempt(5)
)
def _copy_registry_to_registry(cls, source_url, target_url,
source_manifests,
source_session=None,
target_session=None,
source_layers=None,
multi_arch=False,
lock=None):
cls._assert_scheme(source_url, 'docker')
cls._assert_scheme(target_url, 'docker')
image, tag = cls._image_tag_from_url(source_url)
parts = {
'image': image,
'tag': tag
}
# Upload all layers
copy_jobs = []
jobs_count = 0
jobs_finished = 0
with futures.ThreadPoolExecutor(max_workers=4) as p:
if source_layers:
for layer in source_layers:
copy_jobs.append(p.submit(
cls._copy_layer_registry_to_registry,
source_url, target_url,
layer=layer,
source_session=source_session,
target_session=target_session,
lock=lock
))
jobs_count = len(copy_jobs)
LOG.debug('[%s] Waiting for %i jobs to finish' %
(image, jobs_count))
for job in futures.as_completed(copy_jobs):
e = job.exception()
if e:
raise e
layer = job.result()
if layer:
LOG.debug('[%s] Upload complete for layer %s' %
(image, layer))
jobs_finished += 1
LOG.debug('[%s] Waiting for next job: %i of %i complete' %
(image, jobs_finished, jobs_count))
LOG.debug('[%s] Completed %i jobs' % (image, jobs_count))
for source_manifest in source_manifests:
manifest = json.loads(source_manifest)
LOG.debug('[%s] Current image manifest: [%s]' %
(image, json.dumps(manifest, indent=4)))
config_str = None
if manifest.get('mediaType') == MEDIA_MANIFEST_V2:
config_digest = manifest['config']['digest']
LOG.debug('[%s] Uploading config with digest: %s' %
(image, config_digest))
parts['digest'] = config_digest
source_config_url = cls._build_url(
source_url,
CALL_BLOB % parts
)
r = source_session.get(source_config_url, timeout=30)
cls.check_status(
session=source_session,
request=r
)
config_str = cls._get_response_text(r)
manifest['config']['size'] = len(config_str)
manifest['config']['mediaType'] = MEDIA_CONFIG
cls._copy_manifest_config_to_registry(
target_url=target_url,
manifest_str=source_manifest,
config_str=config_str,
target_session=target_session,
multi_arch=multi_arch
)
LOG.debug('[%s] Finished copying image' % image)
@classmethod
def _copy_manifest_config_to_registry(cls, target_url,
manifest_str,
config_str,
target_session=None,
multi_arch=False):
manifest = json.loads(manifest_str)
if manifest.get('schemaVersion', 2) == 1:
if 'signatures' in manifest:
manifest_type = MEDIA_MANIFEST_V1_SIGNED
else:
manifest_type = MEDIA_MANIFEST_V1
else:
manifest_type = manifest.get(
'mediaType', MEDIA_MANIFEST_V2)
manifest_str = json.dumps(manifest, indent=3)
export = target_url.netloc in cls.export_registries
if export:
image_export.export_manifest_config(
target_url,
manifest_str,
manifest_type,
config_str,
multi_arch=multi_arch
)
return
if config_str is not None:
config_digest = manifest['config']['digest']
# Upload the config json as a blob
upload_url = cls._upload_url(
target_url,
session=target_session)
r = target_session.put(
upload_url,
timeout=30,
params={
'digest': config_digest
},
data=config_str.encode('utf-8'),
headers={
'Content-Length': str(len(config_str)),
'Content-Type': 'application/octet-stream'
}
)
cls.check_status(session=target_session, request=r)
# Upload the manifest
image, tag = cls._image_tag_from_url(target_url)
parts = {
'image': image,
'tag': tag
}
manifest_url = cls._build_url(
target_url, CALL_MANIFEST % parts)
LOG.debug('[%s] Uploading manifest of type %s to: %s' %
(image, manifest_type, manifest_url))
r = target_session.put(
manifest_url,
timeout=30,
data=manifest_str.encode('utf-8'),
headers={
'Content-Type': manifest_type
}
)
if r.status_code == 400:
LOG.error(cls._get_response_text(r))
raise ImageUploaderException('Pushing manifest failed')
cls.check_status(session=target_session, request=r)
@classmethod
@tenacity.retry( # Retry up to 5 times with jittered exponential backoff
reraise=True,
wait=tenacity.wait_random_exponential(multiplier=1, max=10),
stop=tenacity.stop_after_attempt(5)
)
def _copy_registry_to_local(cls, source_url):
cls._assert_scheme(source_url, 'docker')
pull_source = source_url.netloc + source_url.path
cmd = ['buildah', '--debug', 'pull']
if source_url.netloc in [cls.insecure_registries,
cls.no_verify_registries]:
cmd.append('--tls-verify=false')
cmd.append(pull_source)
LOG.info('Pulling %s' % pull_source)
LOG.info('Running %s' % ' '.join(cmd))
process = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True,
close_fds=True
)
out, err = process.communicate()
if process.returncode != 0:
error_msg = (
'Pulling image failed: cmd "{}", stdout "{}",'
' stderr "{}"'.format(
' '.join(cmd),
out,
err
)
)
LOG.error(error_msg)
raise ImageUploaderException(error_msg)
return out
@classmethod
def _target_layer_exists_registry(cls, target_url, layer, check_layers,
session):
image, tag = cls._image_tag_from_url(target_url)
parts = {
'image': image,
'tag': tag
}
# Do a HEAD call for the supplied digests
# to see if the layer is already in the registry
for l in check_layers:
if not l:
continue
parts['digest'] = l['digest']
blob_url = cls._build_url(
target_url, CALL_BLOB % parts)
if session.head(blob_url, timeout=30).status_code == 200:
LOG.debug('[%s] Layer already exists: %s' %
(image, l['digest']))
layer['digest'] = l['digest']
if 'size' in l:
layer['size'] = l['size']
if 'mediaType' in l:
layer['mediaType'] = l['mediaType']
return True
return False
@classmethod
def _layer_stream_local(cls, layer_id, calc_digest):
LOG.debug('[%s] Exporting layer' % layer_id)
tar_split_path = cls._containers_file_path(
'overlay-layers',
'%s.tar-split.gz' % layer_id
)
overlay_path = cls._containers_file_path(
'overlay', layer_id, 'diff'
)
cmd = [
'tar-split', 'asm',
'--input', tar_split_path,
'--path', overlay_path,
'--compress'
]
LOG.debug(' '.join(cmd))
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
chunk_size = 2 ** 20
while True:
data = p.stdout.read(chunk_size)
if not data:
break
calc_digest.update(data)
yield data
p.wait()
if p.returncode != 0:
raise ImageUploaderException('Extracting layer failed')
@classmethod
@tenacity.retry( # Retry up to 5 times with jittered exponential backoff
reraise=True,
retry=tenacity.retry_if_exception_type(
requests.exceptions.RequestException
),
wait=tenacity.wait_random_exponential(multiplier=1, max=10),
stop=tenacity.stop_after_attempt(5)
)
def _copy_layer_local_to_registry(cls, target_url,
session, layer, layer_entry):
# Do a HEAD call for the compressed-diff-digest and diff-digest
# to see if the layer is already in the registry
check_layers = []
compressed_digest = layer_entry.get('compressed-diff-digest')
if compressed_digest:
check_layers.append({
'digest': compressed_digest,
'size': layer_entry.get('compressed-size'),
'mediaType': MEDIA_BLOB_COMPRESSED,
})
digest = layer_entry.get('diff-digest')
if digest:
check_layers.append({
'digest': digest,
'size': layer_entry.get('diff-size'),
'mediaType': MEDIA_BLOB,
})
if cls._target_layer_exists_registry(target_url, layer, check_layers,
session):
return
layer_id = layer_entry['id']
LOG.debug('[%s] Uploading layer' % layer_id)
calc_digest = hashlib.sha256()
layer_stream = cls._layer_stream_local(layer_id, calc_digest)
return cls._copy_stream_to_registry(target_url, layer, calc_digest,
layer_stream, session,
verify_digest=False)
@classmethod
def _copy_stream_to_registry(cls, target_url, layer, calc_digest,
layer_stream, session, verify_digest=True):
layer['mediaType'] = MEDIA_BLOB_COMPRESSED
length = 0
upload_resp = None
export = target_url.netloc in cls.export_registries
if export:
return image_export.export_stream(
target_url, layer, layer_stream, verify_digest=verify_digest)
for chunk in layer_stream:
if not chunk:
break
chunk_length = len(chunk)
upload_url = cls._upload_url(
target_url, session, upload_resp)
upload_resp = session.patch(
upload_url,
timeout=30,
data=chunk,
headers={
'Content-Length': str(chunk_length),
'Content-Range': '%d-%d' % (
length, length + chunk_length - 1),
'Content-Type': 'application/octet-stream'
}
)
cls.check_status(session=session, request=upload_resp)
length += chunk_length
layer_digest = 'sha256:%s' % calc_digest.hexdigest()
LOG.debug('[%s] Calculated layer digest' % layer_digest)
upload_url = cls._upload_url(
target_url, session, upload_resp)
upload_resp = session.put(
upload_url,
timeout=30,
params={
'digest': layer_digest
},
)
cls.check_status(session=session, request=upload_resp)
layer['digest'] = layer_digest
layer['size'] = length
return layer_digest
@classmethod
@tenacity.retry( # Retry up to 5 times with jittered exponential backoff
reraise=True,
retry=tenacity.retry_if_exception_type(
requests.exceptions.RequestException
),
wait=tenacity.wait_random_exponential(multiplier=1, max=10),
stop=tenacity.stop_after_attempt(5)
)
def _copy_local_to_registry(cls, source_url, target_url, session):
cls._assert_scheme(source_url, 'containers-storage')
cls._assert_scheme(target_url, 'docker')
name = '%s%s' % (source_url.netloc, source_url.path)
image, manifest, config_str = cls._image_manifest_config(name)
all_layers = cls._containers_json('overlay-layers', 'layers.json')
layers_by_digest = {}
for l in all_layers:
if 'diff-digest' in l:
layers_by_digest[l['diff-digest']] = l
if 'compressed-diff-digest' in l:
layers_by_digest[l['compressed-diff-digest']] = l
# Upload all layers
copy_jobs = []
jobs_count = 0
jobs_finished = 0
with futures.ThreadPoolExecutor(max_workers=4) as p:
for layer in manifest['layers']:
layer_entry = layers_by_digest[layer['digest']]
copy_jobs.append(p.submit(
cls._copy_layer_local_to_registry,
target_url, session, layer, layer_entry
))
jobs_count = len(copy_jobs)
LOG.debug('[%s] Waiting for %i jobs to finish' %
(name, jobs_count))
for job in futures.as_completed(copy_jobs):
e = job.exception()
if e:
raise e
layer = job.result()
if layer:
LOG.debug('[%s] Upload complete for layer: %s' %
(name, layer))
jobs_finished += 1
LOG.debug('[%s] Waiting for next job: %i of %i complete' %
(name, jobs_finished, jobs_count))
LOG.debug('[%s] Completed %i jobs' % (name, jobs_count))
manifest_str = json.dumps(manifest, indent=3)
cls._copy_manifest_config_to_registry(
target_url=target_url,
manifest_str=manifest_str,
config_str=config_str,
target_session=session
)
LOG.debug('[%s] Finished copying' % name)
@classmethod
def _containers_file_path(cls, *path):
full_path = os.path.join('/var/lib/containers/storage/', *path)
if not os.path.exists(full_path):
raise ImageUploaderException('Missing file %s' % full_path)
return full_path
@classmethod
def _containers_file(cls, *path):
full_path = cls._containers_file_path(*path)
try:
with open(full_path, 'r') as f:
return f.read()
except Exception as e:
raise ImageUploaderException(e)
@classmethod
def _containers_json(cls, *path):
return json.loads(cls._containers_file(*path))
@classmethod
def _image_manifest_config(cls, name):
image = None
images = cls._containers_json('overlay-images', 'images.json')
for i in images:
for n in i.get('names', []):
if name == n:
image = i
break
if image:
break
if not image:
raise ImageNotFoundException('Not found image: %s' % name)
image_id = image['id']
manifest = cls._containers_json('overlay-images', image_id, 'manifest')
config_digest = manifest['config']['digest']
config_id = '=' + base64.b64encode(
six.b(config_digest)).decode("utf-8")
config_str = cls._containers_file('overlay-images', image_id,
config_id)
manifest['config']['size'] = len(config_str)
manifest['config']['mediaType'] = MEDIA_CONFIG
return image, manifest, config_str
@classmethod
def _inspect(cls, image_url, session=None):
if image_url.scheme == 'docker':
return super(PythonImageUploader, cls)._inspect(
image_url, session=session)
if image_url.scheme != 'containers-storage':
raise ImageUploaderException('Inspect not implemented for %s' %
image_url.geturl())
name = '%s%s' % (image_url.netloc, image_url.path)
image, manifest, config_str = cls._image_manifest_config(name)
config = json.loads(config_str)
layers = [l['digest'] for l in manifest['layers']]
i, _ = cls._image_tag_from_url(image_url)
digest = image['digest']
created = image['created']
labels = config['config']['Labels']
architecture = config['architecture']
image_os = config['os']
return {
'Name': i,
'Digest': digest,
'RepoTags': [],
'Created': created,
'DockerVersion': '',
'Labels': labels,
'Architecture': architecture,
'Os': image_os,
'Layers': layers,
}
@classmethod
def _delete_from_registry(cls, image_url, session=None):
if not cls._detect_target_export(image_url, session):
raise NotImplementedError(
'Deleting not supported via the registry API')
return image_export.delete_image(image_url)
@classmethod
def _delete(cls, image_url, session=None):
image = image_url.geturl()
LOG.info('[%s] Deleting image' % image)
if image_url.scheme == 'docker':
return cls._delete_from_registry(image_url, session)
if image_url.scheme != 'containers-storage':
raise ImageUploaderException('Delete not implemented for %s' %
image_url.geturl())
cmd = ['buildah', 'rmi', image_url.path]
LOG.info('Running %s' % ' '.join(cmd))
env = os.environ.copy()
process = subprocess.Popen(cmd, env=env, stdout=subprocess.PIPE,
universal_newlines=True)
out, err = process.communicate()
LOG.info(out)
if process.returncode != 0:
LOG.warning('Error deleting image:\n%s\n%s' % (' '.join(cmd), err))
return out
def cleanup(self, local_images):
if not local_images:
return []
for image in sorted(local_images):
if not image:
continue
LOG.info('[%s] Removing local copy of image' % image)
image_url = parse.urlparse('containers-storage:%s' % image)
self._delete(image_url)
def _get_executor(self):
"""Get executor type based on lock object
We check to see if the lock object is not set or if it is a threading
lock. We cannot check if it is a ProcessLock due to the side effect
of trying to include ProcessLock when running under Mistral breaks
Mistral.
"""
if not self.lock or isinstance(self.lock, threadinglock.ThreadingLock):
# workers will scale from 2 to 8 based on the cpu count // 2
workers = min(max(2, processutils.get_worker_count() // 2), 8)
return futures.ThreadPoolExecutor(max_workers=workers)
else:
# there really isn't an improvement with > 4 workers due to the
# container layer overlaps. The higher the workers, the more
# RAM required which can lead to OOMs. It's best to limit to 4
return futures.ProcessPoolExecutor(max_workers=4)
def run_tasks(self):
if not self.upload_tasks:
return
local_images = []
# Pull a single image first, to avoid duplicate pulls of the
# same base layers
local_images.extend(upload_task(args=self.upload_tasks.pop()))
with self._get_executor() as p:
for result in p.map(upload_task, self.upload_tasks):
local_images.extend(result)
LOG.info('result %s' % local_images)
# Do cleanup after all the uploads so common layers don't get deleted
# repeatedly
self.cleanup(local_images)
class UploadTask(object):
def __init__(self, image_name, pull_source, push_destination,
append_tag, modify_role, modify_vars, dry_run, cleanup,
multi_arch, lock=None):
self.image_name = image_name
self.pull_source = pull_source
self.push_destination = push_destination
self.append_tag = append_tag or ''
self.modify_role = modify_role
self.modify_vars = modify_vars
self.dry_run = dry_run
self.cleanup = cleanup
self.multi_arch = multi_arch
self.lock = lock
if ':' in image_name:
image = image_name.rpartition(':')[0]
self.source_tag = image_name.rpartition(':')[2]
else:
image = image_name
self.source_tag = 'latest'
if pull_source:
# prevent a double // in the url which causes auth problems
# with docker.io
if pull_source.endswith('/'):
pull_source = pull_source[:-1]
self.repo = pull_source + '/' + image
else:
self.repo = image
if push_destination.endswith('/'):
push_destination = push_destination[:-1]
self.target_image_no_tag = (push_destination + '/' +
self.repo.partition('/')[2])
self.target_tag = self.source_tag + self.append_tag
self.source_image = self.repo + ':' + self.source_tag
self.target_image_source_tag = (self.target_image_no_tag + ':' +
self.source_tag)
self.target_image = self.target_image_no_tag + ':' + self.target_tag
image_to_url = BaseImageUploader._image_to_url
self.source_image_url = image_to_url(self.source_image)
self.target_image_url = image_to_url(self.target_image)
self.target_image_source_tag_url = image_to_url(
self.target_image_source_tag
)
def upload_task(args):
uploader, task = args
return uploader.upload_image(task)
def discover_tag_from_inspect(args):
self, image, tag_from_label = args
image_url = self._image_to_url(image)
username, password = self.credentials_for_registry(image_url.netloc)
session = self.authenticate(
image_url, username=username, password=password)
i = self._inspect(image_url, session=session)
session.close()
if ':' in image_url.path:
# break out the tag from the url to be the fallback tag
path = image.rpartition(':')
fallback_tag = path[2]
image = path[0]
else:
fallback_tag = None
return image, self._discover_tag_from_inspect(
i, image, tag_from_label, fallback_tag)
def tags_for_image(args):
self, image, session = args
return self._tags_for_image(image, session)
| [] | [] | [] | [] | [] | python | 0 | 0 | |
tuner.py | import subprocess
import os
import sys
logdir = 'dp_tuning'
data_size = 10_000
hidden_sizes = [128, 256, 512]
epsilons = [0.01, 0.1, 1.0, 10.0]
lambdas = [0.01, 0.1, 1.0, 10.0]
dropouts = [0.0, 0.2, 0.4]
learning_rate = [0.01, 0.001, 0.0001]
# for hidden_size in hidden_sizes:
# for lr in learning_rate:
# for dropout in dropouts:
# subprocess.call([sys.executable,
# 'main.py',
# "--log_dir",
# logdir,
# "--data_split",
# str(data_size),
# "--hidden_size",
# str(hidden_size),
# "--validate",
# "--dropout",
# str(dropout),
# "--tag",
# f"hidden_{hidden_size}_dropout_{dropout}_lr_{lr}"],
# env=os.environ.copy())
for epsilon in epsilons:
subprocess.call([sys.executable,
'main.py',
"--log_dir",
logdir,
"--data_split",
str(data_size),
"--epsilon",
str(epsilon),
"--dp",
"--adversarial",
"--validate",
"--tag",
f"epsilon_{epsilon}"],
env=os.environ.copy())
for lbd in lambdas:
subprocess.call([sys.executable,
'main.py',
"--log_dir",
logdir,
"--data_split",
str(data_size),
"--hplambda",
str(lbd),
"--dp",
"--adversarial",
"--validate",
"--tag",
f"lambda_{lbd}"],
env=os.environ.copy())
| [] | [] | [] | [] | [] | python | 0 | 0 | |
contrib/spendfrom/spendfrom.py | #!/usr/bin/env python
#
# Use the raw transactions API to spend bitcoins received on particular addresses,
# and send any change back to that same address.
#
# Example usage:
# spendfrom.py # Lists available funds
# spendfrom.py --from=ADDRESS --to=ADDRESS --amount=11.00
#
# Assumes it will talk to a bitcoind or Bitcoin-Qt running
# on localhost.
#
# Depends on jsonrpc
#
from decimal import *
import getpass
import math
import os
import os.path
import platform
import sys
import time
from jsonrpc import ServiceProxy, json
BASE_FEE=Decimal("0.001")
def check_json_precision():
"""Make sure json library being used does not lose precision converting BTC values"""
n = Decimal("20000000.00000003")
satoshis = int(json.loads(json.dumps(float(n)))*1.0e8)
if satoshis != 2000000000000003:
raise RuntimeError("JSON encode/decode loses precision")
def determine_db_dir():
"""Return the default location of the bitcoin data directory"""
if platform.system() == "Darwin":
return os.path.expanduser("~/Library/Application Support/Bitcoin/")
elif platform.system() == "Windows":
return os.path.join(os.environ['APPDATA'], "Bitcoin")
return os.path.expanduser("~/.bitcoin")
def read_bitcoin_config(dbdir):
"""Read the bitcoin.conf file from dbdir, returns dictionary of settings"""
from ConfigParser import SafeConfigParser
class FakeSecHead(object):
def __init__(self, fp):
self.fp = fp
self.sechead = '[all]\n'
def readline(self):
if self.sechead:
try: return self.sechead
finally: self.sechead = None
else:
s = self.fp.readline()
if s.find('#') != -1:
s = s[0:s.find('#')].strip() +"\n"
return s
config_parser = SafeConfigParser()
config_parser.readfp(FakeSecHead(open(os.path.join(dbdir, "bitcoin.conf"))))
return dict(config_parser.items("all"))
def connect_JSON(config):
"""Connect to a bitcoin JSON-RPC server"""
testnet = config.get('testnet', '0')
testnet = (int(testnet) > 0) # 0/1 in config file, convert to True/False
if not 'rpcport' in config:
config['rpcport'] = 18550 if testnet else 8550
connect = "http://%s:%s@127.0.0.1:%s"%(config['rpcuser'], config['rpcpassword'], config['rpcport'])
try:
result = ServiceProxy(connect)
# ServiceProxy is lazy-connect, so send an RPC command mostly to catch connection errors,
# but also make sure the bitcoind we're talking to is/isn't testnet:
if result.getmininginfo()['testnet'] != testnet:
sys.stderr.write("RPC server at "+connect+" testnet setting mismatch\n")
sys.exit(1)
return result
except:
sys.stderr.write("Error connecting to RPC server at "+connect+"\n")
sys.exit(1)
def unlock_wallet(bitcoind):
info = bitcoind.getinfo()
if 'unlocked_until' not in info:
return True # wallet is not encrypted
t = int(info['unlocked_until'])
if t <= time.time():
try:
passphrase = getpass.getpass("Wallet is locked; enter passphrase: ")
bitcoind.walletpassphrase(passphrase, 5)
except:
sys.stderr.write("Wrong passphrase\n")
info = bitcoind.getinfo()
return int(info['unlocked_until']) > time.time()
def list_available(bitcoind):
address_summary = dict()
address_to_account = dict()
for info in bitcoind.listreceivedbyaddress(0):
address_to_account[info["address"]] = info["account"]
unspent = bitcoind.listunspent(0)
for output in unspent:
# listunspent doesn't give addresses, so:
rawtx = bitcoind.getrawtransaction(output['txid'], 1)
vout = rawtx["vout"][output['vout']]
pk = vout["scriptPubKey"]
# This code only deals with ordinary pay-to-bitcoin-address
# or pay-to-script-hash outputs right now; anything exotic is ignored.
if pk["type"] != "pubkeyhash" and pk["type"] != "scripthash":
continue
address = pk["addresses"][0]
if address in address_summary:
address_summary[address]["total"] += vout["value"]
address_summary[address]["outputs"].append(output)
else:
address_summary[address] = {
"total" : vout["value"],
"outputs" : [output],
"account" : address_to_account.get(address, "")
}
return address_summary
def select_coins(needed, inputs):
# Feel free to improve this, this is good enough for my simple needs:
outputs = []
have = Decimal("0.0")
n = 0
while have < needed and n < len(inputs):
outputs.append({ "txid":inputs[n]["txid"], "vout":inputs[n]["vout"]})
have += inputs[n]["amount"]
n += 1
return (outputs, have-needed)
def create_tx(bitcoind, fromaddresses, toaddress, amount, fee):
all_coins = list_available(bitcoind)
total_available = Decimal("0.0")
needed = amount+fee
potential_inputs = []
for addr in fromaddresses:
if addr not in all_coins:
continue
potential_inputs.extend(all_coins[addr]["outputs"])
total_available += all_coins[addr]["total"]
if total_available < needed:
sys.stderr.write("Error, only %f BTC available, need %f\n"%(total_available, needed));
sys.exit(1)
#
# Note:
# Python's json/jsonrpc modules have inconsistent support for Decimal numbers.
# Instead of wrestling with getting json.dumps() (used by jsonrpc) to encode
# Decimals, I'm casting amounts to float before sending them to bitcoind.
#
outputs = { toaddress : float(amount) }
(inputs, change_amount) = select_coins(needed, potential_inputs)
if change_amount > BASE_FEE: # don't bother with zero or tiny change
change_address = fromaddresses[-1]
if change_address in outputs:
outputs[change_address] += float(change_amount)
else:
outputs[change_address] = float(change_amount)
rawtx = bitcoind.createrawtransaction(inputs, outputs)
signed_rawtx = bitcoind.signrawtransaction(rawtx)
if not signed_rawtx["complete"]:
sys.stderr.write("signrawtransaction failed\n")
sys.exit(1)
txdata = signed_rawtx["hex"]
return txdata
def compute_amount_in(bitcoind, txinfo):
result = Decimal("0.0")
for vin in txinfo['vin']:
in_info = bitcoind.getrawtransaction(vin['txid'], 1)
vout = in_info['vout'][vin['vout']]
result = result + vout['value']
return result
def compute_amount_out(txinfo):
result = Decimal("0.0")
for vout in txinfo['vout']:
result = result + vout['value']
return result
def sanity_test_fee(bitcoind, txdata_hex, max_fee):
class FeeError(RuntimeError):
pass
try:
txinfo = bitcoind.decoderawtransaction(txdata_hex)
total_in = compute_amount_in(bitcoind, txinfo)
total_out = compute_amount_out(txinfo)
if total_in-total_out > max_fee:
raise FeeError("Rejecting transaction, unreasonable fee of "+str(total_in-total_out))
tx_size = len(txdata_hex)/2
kb = tx_size/1000 # integer division rounds down
if kb > 1 and fee < BASE_FEE:
raise FeeError("Rejecting no-fee transaction, larger than 1000 bytes")
if total_in < 0.01 and fee < BASE_FEE:
raise FeeError("Rejecting no-fee, tiny-amount transaction")
# Exercise for the reader: compute transaction priority, and
# warn if this is a very-low-priority transaction
except FeeError as err:
sys.stderr.write((str(err)+"\n"))
sys.exit(1)
def main():
import optparse
parser = optparse.OptionParser(usage="%prog [options]")
parser.add_option("--from", dest="fromaddresses", default=None,
help="addresses to get bitcoins from")
parser.add_option("--to", dest="to", default=None,
help="address to get send bitcoins to")
parser.add_option("--amount", dest="amount", default=None,
help="amount to send")
parser.add_option("--fee", dest="fee", default="0.0",
help="fee to include")
parser.add_option("--datadir", dest="datadir", default=determine_db_dir(),
help="location of bitcoin.conf file with RPC username/password (default: %default)")
parser.add_option("--testnet", dest="testnet", default=False, action="store_true",
help="Use the test network")
parser.add_option("--dry_run", dest="dry_run", default=False, action="store_true",
help="Don't broadcast the transaction, just create and print the transaction data")
(options, args) = parser.parse_args()
check_json_precision()
config = read_bitcoin_config(options.datadir)
if options.testnet: config['testnet'] = True
bitcoind = connect_JSON(config)
if options.amount is None:
address_summary = list_available(bitcoind)
for address,info in address_summary.iteritems():
n_transactions = len(info['outputs'])
if n_transactions > 1:
print("%s %.8f %s (%d transactions)"%(address, info['total'], info['account'], n_transactions))
else:
print("%s %.8f %s"%(address, info['total'], info['account']))
else:
fee = Decimal(options.fee)
amount = Decimal(options.amount)
while unlock_wallet(bitcoind) == False:
pass # Keep asking for passphrase until they get it right
txdata = create_tx(bitcoind, options.fromaddresses.split(","), options.to, amount, fee)
sanity_test_fee(bitcoind, txdata, amount*Decimal("0.01"))
if options.dry_run:
print(txdata)
else:
txid = bitcoind.sendrawtransaction(txdata)
print(txid)
if __name__ == '__main__':
main()
| [] | [] | [
"APPDATA"
] | [] | ["APPDATA"] | python | 1 | 0 | |
shell/shell/wsgi.py | """
WSGI config for shell project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
from mezzanine.utils.conf import real_project_name
os.environ.setdefault("DJANGO_SETTINGS_MODULE",
"%s.settings" % real_project_name("shell"))
application = get_wsgi_application()
| [] | [] | [] | [] | [] | python | 0 | 0 | |
soracom/generated/cmd/users_permissions_update.go | // Code generated by soracom-cli generate-cmd. DO NOT EDIT.
package cmd
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/url"
"os"
"strings"
"github.com/spf13/cobra"
)
// UsersPermissionsUpdateCmdDescription holds value of 'description' option
var UsersPermissionsUpdateCmdDescription string
// UsersPermissionsUpdateCmdOperatorId holds value of 'operator_id' option
var UsersPermissionsUpdateCmdOperatorId string
// UsersPermissionsUpdateCmdPermission holds value of 'permission' option
var UsersPermissionsUpdateCmdPermission string
// UsersPermissionsUpdateCmdUserName holds value of 'user_name' option
var UsersPermissionsUpdateCmdUserName string
// UsersPermissionsUpdateCmdBody holds contents of request body to be sent
var UsersPermissionsUpdateCmdBody string
func init() {
UsersPermissionsUpdateCmd.Flags().StringVar(&UsersPermissionsUpdateCmdDescription, "description", "", TRAPI(""))
UsersPermissionsUpdateCmd.Flags().StringVar(&UsersPermissionsUpdateCmdOperatorId, "operator-id", "", TRAPI("operator_id"))
UsersPermissionsUpdateCmd.Flags().StringVar(&UsersPermissionsUpdateCmdPermission, "permission", "", TRAPI(""))
UsersPermissionsUpdateCmd.Flags().StringVar(&UsersPermissionsUpdateCmdUserName, "user-name", "", TRAPI("user_name"))
UsersPermissionsUpdateCmd.Flags().StringVar(&UsersPermissionsUpdateCmdBody, "body", "", TRCLI("cli.common_params.body.short_help"))
UsersPermissionsCmd.AddCommand(UsersPermissionsUpdateCmd)
}
// UsersPermissionsUpdateCmd defines 'update' subcommand
var UsersPermissionsUpdateCmd = &cobra.Command{
Use: "update",
Short: TRAPI("/operators/{operator_id}/users/{user_name}/permission:put:summary"),
Long: TRAPI(`/operators/{operator_id}/users/{user_name}/permission:put:description`),
RunE: func(cmd *cobra.Command, args []string) error {
opt := &apiClientOptions{
BasePath: "/v1",
Language: getSelectedLanguage(),
}
ac := newAPIClient(opt)
if v := os.Getenv("SORACOM_VERBOSE"); v != "" {
ac.SetVerbose(true)
}
err := authHelper(ac, cmd, args)
if err != nil {
cmd.SilenceUsage = true
return err
}
param, err := collectUsersPermissionsUpdateCmdParams(ac)
if err != nil {
return err
}
body, err := ac.callAPI(param)
if err != nil {
cmd.SilenceUsage = true
return err
}
if body == "" {
return nil
}
if rawOutput {
_, err = os.Stdout.Write([]byte(body))
} else {
return prettyPrintStringAsJSON(body)
}
return err
},
}
func collectUsersPermissionsUpdateCmdParams(ac *apiClient) (*apiParams, error) {
var body string
var parsedBody interface{}
var err error
if UsersPermissionsUpdateCmdOperatorId == "" {
UsersPermissionsUpdateCmdOperatorId = ac.OperatorID
}
body, err = buildBodyForUsersPermissionsUpdateCmd()
if err != nil {
return nil, err
}
contentType := "application/json"
if contentType == "application/json" {
err = json.Unmarshal([]byte(body), &parsedBody)
if err != nil {
return nil, fmt.Errorf("invalid json format specified for `--body` parameter: %s", err)
}
}
err = checkIfRequiredStringParameterIsSupplied("permission", "permission", "body", parsedBody, UsersPermissionsUpdateCmdPermission)
if err != nil {
return nil, err
}
err = checkIfRequiredStringParameterIsSupplied("user_name", "user-name", "path", parsedBody, UsersPermissionsUpdateCmdUserName)
if err != nil {
return nil, err
}
return &apiParams{
method: "PUT",
path: buildPathForUsersPermissionsUpdateCmd("/operators/{operator_id}/users/{user_name}/permission"),
query: buildQueryForUsersPermissionsUpdateCmd(),
contentType: contentType,
body: body,
noRetryOnError: noRetryOnError,
}, nil
}
func buildPathForUsersPermissionsUpdateCmd(path string) string {
escapedOperatorId := url.PathEscape(UsersPermissionsUpdateCmdOperatorId)
path = strReplace(path, "{"+"operator_id"+"}", escapedOperatorId, -1)
escapedUserName := url.PathEscape(UsersPermissionsUpdateCmdUserName)
path = strReplace(path, "{"+"user_name"+"}", escapedUserName, -1)
return path
}
func buildQueryForUsersPermissionsUpdateCmd() url.Values {
result := url.Values{}
return result
}
func buildBodyForUsersPermissionsUpdateCmd() (string, error) {
var result map[string]interface{}
if UsersPermissionsUpdateCmdBody != "" {
var b []byte
var err error
if strings.HasPrefix(UsersPermissionsUpdateCmdBody, "@") {
fname := strings.TrimPrefix(UsersPermissionsUpdateCmdBody, "@")
// #nosec
b, err = ioutil.ReadFile(fname)
} else if UsersPermissionsUpdateCmdBody == "-" {
b, err = ioutil.ReadAll(os.Stdin)
} else {
b = []byte(UsersPermissionsUpdateCmdBody)
}
if err != nil {
return "", err
}
err = json.Unmarshal(b, &result)
if err != nil {
return "", err
}
}
if result == nil {
result = make(map[string]interface{})
}
if UsersPermissionsUpdateCmdDescription != "" {
result["description"] = UsersPermissionsUpdateCmdDescription
}
if UsersPermissionsUpdateCmdPermission != "" {
result["permission"] = UsersPermissionsUpdateCmdPermission
}
resultBytes, err := json.Marshal(result)
if err != nil {
return "", err
}
return string(resultBytes), nil
}
| [
"\"SORACOM_VERBOSE\""
] | [] | [
"SORACOM_VERBOSE"
] | [] | ["SORACOM_VERBOSE"] | go | 1 | 0 | |
pqparser.go | package pqparser
import (
"crypto/tls"
"encoding/csv"
"fmt"
"net/url"
"os"
"os/user"
"strconv"
"strings"
"time"
"github.com/go-pg/pg"
)
const (
// TODO: we should find something better
slashReplacement = "HereWasASlash"
)
// Parse a connection string or URI.
// The connection string is parsed as defined in the libpq documentation:
// https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNSTRING
//
// The described environment variables are used exactly the same. If a value does not
// exist, than the corresponding environment variable is taken if it exists.
func Parse(connstr string) (*pg.Options, error) {
// check if this is a url
if strings.HasPrefix(connstr, "postgresql://") || strings.HasPrefix(connstr, "postgres://") {
return parseURI(connstr)
}
// not a valid uri, we handle it as key value
return parseConnstr(connstr)
}
func parseURI(dsn string) (*pg.Options, error) {
options := &pg.Options{}
// remove the prefix, we will add a dummy later for the net/url parser
connuri := strings.TrimPrefix(strings.TrimPrefix(dsn, "postgresql://"), "postgres://")
// split at the first slash
uriparts := strings.SplitN(connuri, "/", 2)
var uripath string
if len(uriparts) > 1 {
uripath = uriparts[1]
}
var userpass string
var netloc string
// check if we have a user delimiter
if strings.ContainsRune(uriparts[0], '@') {
// split the user part away
userhost := strings.SplitN(uriparts[0], "@", 2)
userpass = userhost[0]
netloc = userhost[1]
} else {
netloc = uriparts[0]
}
// there may be cases where there is no slash at all, or the ? separator before the slash
if strings.ContainsRune(netloc, '?') {
parts := strings.SplitN(netloc, "?", 2)
netloc = parts[0]
if len(uriparts) > 1 {
uripath = "/" + uripath
}
uripath = "?" + parts[1] + uripath
}
// remove empty port declaration at the end of the Host
netloc = strings.TrimSuffix(netloc, ":")
// libpq states, that is uses RFC 3986 URIs, but this RFC does not allow %-escapes inside the host part
// expect for ipv6 strings and the % itself. So, we replace %2f sequences in the host part with a placeholder
// and move back to slashes later. The whole splitting above is just because if this ...
netloc = strings.ReplaceAll(strings.ReplaceAll(netloc, "%f2", slashReplacement), "%2F", slashReplacement)
// and now, rebuild the uri
connuri = "postgresql://"
if userpass != "" {
connuri += userpass + "@"
}
connuri += netloc + "/" + uripath
// now, parse the uri
uri, err := url.Parse(connuri)
if err != nil {
return nil, fmt.Errorf("failed to parse URI: %v", err)
}
// now, convert the URI to the final object
options.User = uri.User.Username()
options.Password, _ = uri.User.Password()
options.Database = strings.Trim(uri.Path, "/")
// flatten the query parameters
parameters := make(map[string]string)
queryparam, err := url.ParseQuery(uri.RawQuery)
if err != nil {
return nil, fmt.Errorf("failed to parse URI query: %v", err)
}
for key, values := range queryparam {
if len(values) != 1 {
return nil, fmt.Errorf("failed to parse URI: parameter %v has not exactly one value", key)
}
parameters[key] = values[0]
}
urihost := strings.ReplaceAll(uri.Host, slashReplacement, "/")
if _, exists := parameters["port"]; !exists {
if portstr := uri.Port(); portstr != "" {
urihost = strings.TrimSuffix(urihost, ":"+portstr)
parameters["port"] = portstr
}
}
// set host and port if they not exists in the parameter list
if _, exists := parameters["host"]; !exists && urihost != "" {
parameters["host"] = urihost
}
if err := parseParameters(options, parameters); err != nil {
return nil, err
}
return options, nil
}
func parseConnstr(connstr string) (*pg.Options, error) {
// we use the CSV parser, at it does all the quote handling for us
cr := csv.NewReader(strings.NewReader(connstr))
cr.Comma = ' '
records, err := cr.ReadAll()
if err != nil {
return nil, fmt.Errorf("failed to parse connection string: %v", err)
}
parameters := make(map[string]string)
// we have only one row
if len(records) > 0 {
for _, keyvalue := range records[0] {
// split the key value and
parts := strings.SplitN(keyvalue, "=", 2)
if len(parts) != 2 {
return nil, fmt.Errorf("failed to parse connection string: missing value after %s", keyvalue)
}
parameters[parts[0]] = parts[1]
}
}
options := &pg.Options{}
if err := parseParameters(options, parameters); err != nil {
return nil, err
}
return options, nil
}
func parseParameters(options *pg.Options, parameters map[string]string) error {
var host string
var port int
var fallbackAppname string
var clientCert string
var clientKey string
sslNeedsHostname := false
hasSSLConfig := false
tlsconfig := &tls.Config{}
sslEnabled := false
parseSSLMode := func(mode string) error {
hasSSLConfig = true
switch mode {
case "allow", "prefer", "require", "verify-ca":
// use InsecureSkipVerify for require, as the behavior of libpq is not implementable
// verify-ca can not be implemented, so we skip verification here
tlsconfig.InsecureSkipVerify = true
sslEnabled = true
case "verify-full":
tlsconfig.InsecureSkipVerify = false
// remember we have to add the hostname later
sslNeedsHostname = true
sslEnabled = true
case "disable":
// disable TLS config
sslEnabled = false
default:
return fmt.Errorf("failed to parse sslmode: unsupported mode %s", mode)
}
return nil
}
for key, value := range parameters {
if len(value) == 0 {
return fmt.Errorf("missing value for parameter %v", key)
}
switch key {
case "host", "hostaddr":
host = value
case "port":
var err error
port, err = strconv.Atoi(value)
if err != nil {
return fmt.Errorf("failed to parse URI port: %v", err)
}
case "dbname":
options.Database = value
case "user":
options.User = value
case "password":
options.Password = value
case "connect_timeout":
timeout, err := strconv.Atoi(value)
if err != nil {
return fmt.Errorf("failed to parse URI connect_timeout: %v", err)
}
options.DialTimeout = time.Duration(timeout) * time.Second
case "client_encoding":
// not supported
case "options":
// not supported yet, could use onConnect handler
case "application_name":
options.ApplicationName = value
case "fallback_application_name":
fallbackAppname = value
case "keepalives", "keepalives_idle", "keepalives_interval", "keepalives_count":
// not supported, not required
case "tty":
// legacy
case "sslmode":
if err := parseSSLMode(value); err != nil {
return err
}
case "requiressl":
// deprecated
tlsconfig.InsecureSkipVerify = true
hasSSLConfig = true
sslEnabled = true
case "sslcompression":
// not supported
case "sslcert":
clientCert = value
case "sslkey":
clientKey = value
case "sslrootcert":
// TODO
case "sslcrl":
// TODO
case "requirepeer":
// not supported
case "krbsrvname":
// not supported yet
case "gsslib":
// not supported yet
case "service":
// not supported yet
case "target_session_attrs":
// not supported yet
default:
return fmt.Errorf("invalid parameters %s", key)
}
}
// now, check the environment variables for all missing parameters
if host == "" {
host = os.Getenv("PGHOST")
}
if port == 0 {
portstr := os.Getenv("PGPORT")
if portstr != "" {
var err error
port, err = strconv.Atoi(portstr)
if err != nil {
return fmt.Errorf("failed to parse PGPORT: %v", err)
}
}
}
if options.Database == "" {
options.Database = os.Getenv("PGDATABASE")
}
if options.User == "" {
options.User = os.Getenv("PGUSER")
}
if options.Password == "" {
options.Password = os.Getenv("PGPASSWORD")
}
if options.ApplicationName == "" {
options.ApplicationName = os.Getenv("PGAPPNAME")
}
if !hasSSLConfig {
if sslmode := os.Getenv("PGSSLMODE"); sslmode != "" {
if err := parseSSLMode(sslmode); err != nil {
return err
}
} else if sslrequire := os.Getenv("PGREQUIRESSL"); sslrequire != "" {
// deprecated
tlsconfig.InsecureSkipVerify = true
hasSSLConfig = true
sslEnabled = true
}
}
if clientCert == "" {
clientCert = os.Getenv("PGSSLCERT")
}
if clientKey == "" {
clientKey = os.Getenv("PGSSLKEY")
}
/* TODO:
/ PGSSLROOTCERT behaves the same as the sslrootcert connection parameter.
/ PGSSLCRL behaves the same as the sslcrl connection parameter.
*/
if options.DialTimeout == 0 {
if timeoutstr := os.Getenv("PGCONNECT_TIMEOUT"); timeoutstr != "" {
timeout, err := strconv.Atoi(timeoutstr)
if err != nil {
return fmt.Errorf("failed to parse PGCONNECT_TIMEOUT: %v", err)
}
options.DialTimeout = time.Duration(timeout) * time.Second
}
}
// build the addr
isSocket := false
options.Network = "tcp"
if host == "" {
// default would be the unix socket, but we don't know
// where the socket is on the system, so we fall back to TCP
host = "localhost"
} else if strings.HasPrefix(host, "/") {
options.Network = "unix"
isSocket = true
}
if port == 0 {
port = 5432
}
if isSocket {
options.Addr = fmt.Sprintf("%s/.s.PGSQL.%d", host, port)
} else {
options.Addr = fmt.Sprintf("%s:%d", host, port)
}
// set the default user
if options.User == "" {
if sysuser, err := user.Current(); err == nil {
options.User = sysuser.Username
} else {
options.User = "postgres"
}
}
if options.Database == "" {
options.Database = options.User
}
// check the appname and possible fallback
if options.ApplicationName == "" {
options.ApplicationName = fallbackAppname
}
// set the TLS context
if sslEnabled {
options.TLSConfig = tlsconfig
if sslNeedsHostname {
// if we have a socket connection, we can not validate the hostname
// so we would have to set SSL to non-validating
if isSocket {
options.TLSConfig.InsecureSkipVerify = true
} else {
options.TLSConfig.ServerName = host
}
}
// check if we have ssl private key and cert
if clientKey != "" && clientCert != "" {
if cert, err := tls.LoadX509KeyPair(clientCert, clientKey); err != nil {
return fmt.Errorf("failed to load SSL Keypair: %v", err)
} else {
options.TLSConfig.Certificates = append(options.TLSConfig.Certificates, cert)
}
}
}
return nil
}
| [
"\"PGHOST\"",
"\"PGPORT\"",
"\"PGDATABASE\"",
"\"PGUSER\"",
"\"PGPASSWORD\"",
"\"PGAPPNAME\"",
"\"PGSSLMODE\"",
"\"PGREQUIRESSL\"",
"\"PGSSLCERT\"",
"\"PGSSLKEY\"",
"\"PGCONNECT_TIMEOUT\""
] | [] | [
"PGAPPNAME",
"PGPORT",
"PGSSLKEY",
"PGDATABASE",
"PGUSER",
"PGSSLMODE",
"PGHOST",
"PGPASSWORD",
"PGREQUIRESSL",
"PGSSLCERT",
"PGCONNECT_TIMEOUT"
] | [] | ["PGAPPNAME", "PGPORT", "PGSSLKEY", "PGDATABASE", "PGUSER", "PGSSLMODE", "PGHOST", "PGPASSWORD", "PGREQUIRESSL", "PGSSLCERT", "PGCONNECT_TIMEOUT"] | go | 11 | 0 | |
register_pairs_flirt.py | import argparse
import os
import sys
parser = argparse.ArgumentParser('Register pairs of images (eg, baseline and follow-up) using FSL flirt')
parser.add_argument("--ref_dir", type=str, nargs=1, required=True, help="Directory containing the reference images")
parser.add_argument("--ref_suffix", type=str, nargs=1, required=True, help="Suffix of reference images")
parser.add_argument("--mov_dir", type=str, nargs=1, required=True, help="Directory containing the moving images")
parser.add_argument("--mov_suffix_list", type=str, nargs='+', required=True, help="List of suffixes of moving images (must have same prefix as reference)")
parser.add_argument("--interp", type=str, nargs=1, default=['trilinear'], help="Interpolation: [trilinear,nearestneighbour,sinc,spline]")
parser.add_argument("--out_dir", type=str, nargs=1, required=True, help="Where to store the results to")
parser.add_argument("--out_suffix", type=str, nargs=1, required=True, help="Suffix to be added to the moving image w/o extension")
parser.add_argument("--xfm_dir", type=str, nargs=1, help="(optional) directory with transforms")
parser.add_argument("--xfm_suffix_list", type=str, nargs='+', help="(optional) List of suffixes of transforms (no optimization. If only 1, applied to all moving imgs.)")
parser.add_argument("--searchxyz", type=float, nargs=1, default=[25.], help='search degrees in x, y, z axes (default 25) ')
parser.add_argument("--num_procs", type=int, nargs=1, default=[ ], help='number of concurrent processes ')
args = parser.parse_args()
# args = parser.parse_args(''
# '--ref_dir /home/sanromag/DATA/WMH/train_RS/data_proc '
# '--ref_suffix _FLAIR.nii.gz '
# '--mov_dir /home/sanromag/DATA/WMH/train_RS/data '
# '--mov_suffix_list _brainmask.nii.gz '
# '--interp trilinear '
# '--out_dir /home/sanromag/DATA/WMH/train_RS/kk '
# '--out_suffix Warped.nii.gz '
# '--xfm_dir /home/sanromag/DATA/WMH/train_RS/transform_pairs '
# '--xfm_suffix_list _T1FS.mat '
# '--num_procs 30 '
# ''.split())
from scheduler import Launcher
launcher = Launcher(args.num_procs[0])
#
# Initial checks
#
if args.xfm_suffix_list is not None:
assert len(args.xfm_suffix_list) == 1 or len(args.xfm_suffix_list) == len(args.mov_suffix_list), "Must have only one transform OR the same number as moving images"
files_list = os.listdir(args.ref_dir[0])
ref_list = [f for f in files_list if f.endswith(args.ref_suffix[0])]
assert ref_list, "List of input images is empty"
# create output directory
if not os.path.exists(args.out_dir[0]):
os.makedirs(args.out_dir[0])
#
# Main program
#
# separate ids and dates
id_list = [f.split(args.ref_suffix[0])[0] for f in ref_list]
flirt_path = os.path.join(os.environ['FSLDIR'], 'bin', 'flirt')
name_list = []
for id, ref in zip(id_list, ref_list):
for i, suffix in enumerate(args.mov_suffix_list):
cmdline = [flirt_path]
cmdline.extend(['-in', os.path.join(args.mov_dir[0], id + suffix)])
cmdline.extend(['-ref', os.path.join(args.ref_dir[0], ref)])
cmdline.extend(['-out', os.path.join(args.out_dir[0], id + suffix.split(os.extsep, 1)[0] + args.out_suffix[0])])
cmdline.extend(['-interp', args.interp[0]])
if args.xfm_suffix_list is None:
cmdline.extend(['-omat', os.path.join(args.out_dir[0], id + suffix.split(os.extsep, 1)[0] + '.mat')])
cmdline.extend(['-bins', '256'])
cmdline.extend(['-cost', 'mutualinfo'])
cmdline.extend(['-searchrx', '-%0.2f' % args.searchxyz[0], '%0.2f' % args.searchxyz[0]])
cmdline.extend(['-searchry', '-%0.2f' % args.searchxyz[0], '%0.2f' % args.searchxyz[0]])
cmdline.extend(['-searchrz', '-%0.2f' % args.searchxyz[0], '%0.2f' % args.searchxyz[0]])
cmdline.extend(['-2D'])
cmdline.extend(['-dof', '12'])
else:
cmdline.extend(['-applyxfm'])
if len(args.xfm_suffix_list) == 1: xfm_suffix = args.xfm_suffix_list[0]
else: xfm_suffix = args.xfm_suffix_list[i]
cmdline.extend(['-init', os.path.join(args.xfm_dir[0], id + xfm_suffix)])
# launch
print "Launching registration of subject %s" % (id)
name_list.append(id + suffix.split(os.extsep, 1)[0])
launcher.add(name_list[-1], ' '.join(cmdline), args.out_dir[0])
launcher.run(name_list[-1])
print "Waiting for registration jobs to finish..."
launcher.wait()
print "Registration finished."
| [] | [] | [
"FSLDIR"
] | [] | ["FSLDIR"] | python | 1 | 0 | |
src/main/java/org/javacs/Lib.java | package org.javacs;
import java.io.File;
import java.lang.System;
import java.util.Optional;
import java.util.Arrays;
import java.nio.file.*;
class Lib {
static Optional<Path> srcZipPath() {
return Optional.ofNullable(System.getenv("JAVA_HOME"))
.map(home -> {
return Arrays.asList(new Path[]{
Paths.get(home).resolve("lib/src.zip"),
Paths.get(home).resolve("src.zip"),
});
})
.flatMap(paths -> {
for (Path path : paths) {
if (path.toFile().exists()) {
return Optional.of(path);
}
}
return Optional.empty();
});
}
static final Optional<Path> SRC_ZIP = srcZipPath();
}
| [
"\"JAVA_HOME\""
] | [] | [
"JAVA_HOME"
] | [] | ["JAVA_HOME"] | java | 1 | 0 | |
build.go | // +build ignore
package main
import (
"bytes"
"crypto/md5"
"encoding/json"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"strconv"
"strings"
"time"
)
var (
versionRe = regexp.MustCompile(`-[0-9]{1,3}-g[0-9a-f]{5,10}`)
goarch string
goos string
version string = "v1"
// deb & rpm does not support semver so have to handle their version a little differently
linuxPackageVersion string = "v1"
linuxPackageIteration string = ""
race bool
workingDir string
serverBinaryName string = "grafana-server"
)
const minGoVersion = 1.3
func main() {
log.SetOutput(os.Stdout)
log.SetFlags(0)
ensureGoPath()
readVersionFromPackageJson()
log.Printf("Version: %s, Linux Version: %s, Package Iteration: %s\n", version, linuxPackageVersion, linuxPackageIteration)
flag.StringVar(&goarch, "goarch", runtime.GOARCH, "GOARCH")
flag.StringVar(&goos, "goos", runtime.GOOS, "GOOS")
flag.BoolVar(&race, "race", race, "Use race detector")
flag.Parse()
if flag.NArg() == 0 {
log.Println("Usage: go run build.go build")
return
}
workingDir, _ = os.Getwd()
for _, cmd := range flag.Args() {
switch cmd {
case "setup":
setup()
case "build":
pkg := "."
clean()
build(pkg, []string{})
case "test":
test("./pkg/...")
grunt("test")
case "package":
//verifyGitRepoIsClean()
grunt("release")
createLinuxPackages()
case "latest":
makeLatestDistCopies()
case "clean":
clean()
default:
log.Fatalf("Unknown command %q", cmd)
}
}
}
func makeLatestDistCopies() {
runError("cp", "dist/grafana_"+version+"_amd64.deb", "dist/grafana_latest_amd64.deb")
runError("cp", "dist/grafana-"+strings.Replace(version, "-", "_", 5)+"-1.x86_64.rpm", "dist/grafana-latest-1.x86_64.rpm")
runError("cp", "dist/grafana-"+version+".linux-x64.tar.gz", "dist/grafana-latest.linux-x64.tar.gz")
}
func readVersionFromPackageJson() {
reader, err := os.Open("package.json")
if err != nil {
log.Fatal("Failed to open package.json")
return
}
defer reader.Close()
jsonObj := map[string]interface{}{}
jsonParser := json.NewDecoder(reader)
if err := jsonParser.Decode(&jsonObj); err != nil {
log.Fatal("Failed to decode package.json")
}
version = jsonObj["version"].(string)
linuxPackageVersion = version
linuxPackageIteration = ""
// handle pre version stuff (deb / rpm does not support semver)
parts := strings.Split(version, "-")
if len(parts) > 1 {
linuxPackageVersion = parts[0]
linuxPackageIteration = parts[1]
}
}
type linuxPackageOptions struct {
packageType string
homeDir string
binPath string
configDir string
configFilePath string
ldapFilePath string
etcDefaultPath string
etcDefaultFilePath string
initdScriptFilePath string
systemdServiceFilePath string
postinstSrc string
initdScriptSrc string
defaultFileSrc string
systemdFileSrc string
depends []string
}
func createLinuxPackages() {
createPackage(linuxPackageOptions{
packageType: "deb",
homeDir: "/usr/share/grafana",
binPath: "/usr/sbin/grafana-server",
configDir: "/etc/grafana",
configFilePath: "/etc/grafana/grafana.ini",
ldapFilePath: "/etc/grafana/ldap.toml",
etcDefaultPath: "/etc/default",
etcDefaultFilePath: "/etc/default/grafana-server",
initdScriptFilePath: "/etc/init.d/grafana-server",
systemdServiceFilePath: "/usr/lib/systemd/system/grafana-server.service",
postinstSrc: "packaging/deb/control/postinst",
initdScriptSrc: "packaging/deb/init.d/grafana-server",
defaultFileSrc: "packaging/deb/default/grafana-server",
systemdFileSrc: "packaging/deb/systemd/grafana-server.service",
depends: []string{"adduser", "libfontconfig"},
})
createPackage(linuxPackageOptions{
packageType: "rpm",
homeDir: "/usr/share/grafana",
binPath: "/usr/sbin/grafana-server",
configDir: "/etc/grafana",
configFilePath: "/etc/grafana/grafana.ini",
ldapFilePath: "/etc/grafana/ldap.toml",
etcDefaultPath: "/etc/sysconfig",
etcDefaultFilePath: "/etc/sysconfig/grafana-server",
initdScriptFilePath: "/etc/init.d/grafana-server",
systemdServiceFilePath: "/usr/lib/systemd/system/grafana-server.service",
postinstSrc: "packaging/rpm/control/postinst",
initdScriptSrc: "packaging/rpm/init.d/grafana-server",
defaultFileSrc: "packaging/rpm/sysconfig/grafana-server",
systemdFileSrc: "packaging/rpm/systemd/grafana-server.service",
depends: []string{"initscripts", "fontconfig"},
})
}
func createPackage(options linuxPackageOptions) {
packageRoot, _ := ioutil.TempDir("", "grafana-linux-pack")
// create directories
runPrint("mkdir", "-p", filepath.Join(packageRoot, options.homeDir))
runPrint("mkdir", "-p", filepath.Join(packageRoot, options.configDir))
runPrint("mkdir", "-p", filepath.Join(packageRoot, "/etc/init.d"))
runPrint("mkdir", "-p", filepath.Join(packageRoot, options.etcDefaultPath))
runPrint("mkdir", "-p", filepath.Join(packageRoot, "/usr/lib/systemd/system"))
runPrint("mkdir", "-p", filepath.Join(packageRoot, "/usr/sbin"))
// copy binary
runPrint("cp", "-p", filepath.Join(workingDir, "tmp/bin/"+serverBinaryName), filepath.Join(packageRoot, options.binPath))
// copy init.d script
runPrint("cp", "-p", options.initdScriptSrc, filepath.Join(packageRoot, options.initdScriptFilePath))
// copy environment var file
runPrint("cp", "-p", options.defaultFileSrc, filepath.Join(packageRoot, options.etcDefaultFilePath))
// copy systemd file
runPrint("cp", "-p", options.systemdFileSrc, filepath.Join(packageRoot, options.systemdServiceFilePath))
// copy release files
runPrint("cp", "-a", filepath.Join(workingDir, "tmp")+"/.", filepath.Join(packageRoot, options.homeDir))
// remove bin path
runPrint("rm", "-rf", filepath.Join(packageRoot, options.homeDir, "bin"))
// copy sample ini file to /etc/grafana
runPrint("cp", "conf/sample.ini", filepath.Join(packageRoot, options.configFilePath))
// copy sample ldap toml config file to /etc/grafana/ldap.toml
runPrint("cp", "conf/ldap.toml", filepath.Join(packageRoot, options.ldapFilePath))
args := []string{
"-s", "dir",
"--description", "Grafana",
"-C", packageRoot,
"--vendor", "Grafana",
"--url", "http://grafana.org",
"--license", "Apache 2.0",
"--maintainer", "contact@grafana.org",
"--config-files", options.configFilePath,
"--config-files", options.initdScriptFilePath,
"--config-files", options.etcDefaultFilePath,
"--config-files", options.systemdServiceFilePath,
"--after-install", options.postinstSrc,
"--name", "grafana",
"--version", linuxPackageVersion,
"-p", "./dist",
}
if linuxPackageIteration != "" {
args = append(args, "--iteration", linuxPackageIteration)
}
// add dependenciesj
for _, dep := range options.depends {
args = append(args, "--depends", dep)
}
args = append(args, ".")
fmt.Println("Creating package: ", options.packageType)
runPrint("fpm", append([]string{"-t", options.packageType}, args...)...)
}
func verifyGitRepoIsClean() {
rs, err := runError("git", "ls-files", "--modified")
if err != nil {
log.Fatalf("Failed to check if git tree was clean, %v, %v\n", string(rs), err)
return
}
count := len(string(rs))
if count > 0 {
log.Fatalf("Git repository has modified files, aborting")
}
log.Println("Git repository is clean")
}
func ensureGoPath() {
if os.Getenv("GOPATH") == "" {
cwd, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
gopath := filepath.Clean(filepath.Join(cwd, "../../../../"))
log.Println("GOPATH is", gopath)
os.Setenv("GOPATH", gopath)
}
}
func ChangeWorkingDir(dir string) {
os.Chdir(dir)
}
func grunt(params ...string) {
runPrint("./node_modules/grunt-cli/bin/grunt", params...)
}
func setup() {
runPrint("go", "get", "-v", "github.com/tools/godep")
runPrint("go", "get", "-v", "github.com/blang/semver")
runPrint("go", "get", "-v", "github.com/mattn/go-sqlite3")
runPrint("go", "install", "-v", "github.com/mattn/go-sqlite3")
}
func test(pkg string) {
setBuildEnv()
runPrint("go", "test", "-short", "-timeout", "60s", pkg)
}
func build(pkg string, tags []string) {
binary := "./bin/" + serverBinaryName
if goos == "windows" {
binary += ".exe"
}
rmr(binary, binary+".md5")
args := []string{"build", "-ldflags", ldflags()}
if len(tags) > 0 {
args = append(args, "-tags", strings.Join(tags, ","))
}
if race {
args = append(args, "-race")
}
args = append(args, "-o", binary)
args = append(args, pkg)
setBuildEnv()
runPrint("go", args...)
// Create an md5 checksum of the binary, to be included in the archive for
// automatic upgrades.
err := md5File(binary)
if err != nil {
log.Fatal(err)
}
}
func ldflags() string {
var b bytes.Buffer
b.WriteString("-w")
b.WriteString(fmt.Sprintf(" -X main.version '%s'", version))
b.WriteString(fmt.Sprintf(" -X main.commit '%s'", getGitSha()))
b.WriteString(fmt.Sprintf(" -X main.buildstamp %d", buildStamp()))
return b.String()
}
func rmr(paths ...string) {
for _, path := range paths {
log.Println("rm -r", path)
os.RemoveAll(path)
}
}
func clean() {
rmr("bin", "Godeps/_workspace/pkg", "Godeps/_workspace/bin")
rmr("dist")
rmr("tmp")
rmr(filepath.Join(os.Getenv("GOPATH"), fmt.Sprintf("pkg/%s_%s/github.com/grafana", goos, goarch)))
}
func setBuildEnv() {
os.Setenv("GOOS", goos)
if strings.HasPrefix(goarch, "armv") {
os.Setenv("GOARCH", "arm")
os.Setenv("GOARM", goarch[4:])
} else {
os.Setenv("GOARCH", goarch)
}
if goarch == "386" {
os.Setenv("GO386", "387")
}
wd, err := os.Getwd()
if err != nil {
log.Println("Warning: can't determine current dir:", err)
log.Println("Build might not work as expected")
}
os.Setenv("GOPATH", fmt.Sprintf("%s%c%s", filepath.Join(wd, "Godeps", "_workspace"), os.PathListSeparator, os.Getenv("GOPATH")))
log.Println("GOPATH=" + os.Getenv("GOPATH"))
}
func getGitSha() string {
v, err := runError("git", "describe", "--always", "--dirty")
if err != nil {
return "unknown-dev"
}
v = versionRe.ReplaceAllFunc(v, func(s []byte) []byte {
s[0] = '+'
return s
})
return string(v)
}
func buildStamp() int64 {
bs, err := runError("git", "show", "-s", "--format=%ct")
if err != nil {
return time.Now().Unix()
}
s, _ := strconv.ParseInt(string(bs), 10, 64)
return s
}
func buildArch() string {
os := goos
if os == "darwin" {
os = "macosx"
}
return fmt.Sprintf("%s-%s", os, goarch)
}
func run(cmd string, args ...string) []byte {
bs, err := runError(cmd, args...)
if err != nil {
log.Println(cmd, strings.Join(args, " "))
log.Println(string(bs))
log.Fatal(err)
}
return bytes.TrimSpace(bs)
}
func runError(cmd string, args ...string) ([]byte, error) {
ecmd := exec.Command(cmd, args...)
bs, err := ecmd.CombinedOutput()
if err != nil {
return nil, err
}
return bytes.TrimSpace(bs), nil
}
func runPrint(cmd string, args ...string) {
log.Println(cmd, strings.Join(args, " "))
ecmd := exec.Command(cmd, args...)
ecmd.Stdout = os.Stdout
ecmd.Stderr = os.Stderr
err := ecmd.Run()
if err != nil {
log.Fatal(err)
}
}
func md5File(file string) error {
fd, err := os.Open(file)
if err != nil {
return err
}
defer fd.Close()
h := md5.New()
_, err = io.Copy(h, fd)
if err != nil {
return err
}
out, err := os.Create(file + ".md5")
if err != nil {
return err
}
_, err = fmt.Fprintf(out, "%x\n", h.Sum(nil))
if err != nil {
return err
}
return out.Close()
}
| [
"\"GOPATH\"",
"\"GOPATH\"",
"\"GOPATH\"",
"\"GOPATH\""
] | [] | [
"GOPATH"
] | [] | ["GOPATH"] | go | 1 | 0 | |
config.py | import os
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY') or "chaihongjing"
SSL_REDIRECT = False
SQLALCHEMY_TRACK_MODIFICATIONS = False
SQLALCHEMY_RECORD_QUERIES = True
FLASKY_PER_PAGE = 10
SQLALCHEMY_POOL_SIZE = 5
@staticmethod
def init_app(app):
pass
class DevelopmentConfig(Config):
DEBUG = True
SQLALCHEMY_DATABASE_URI = "mysql+mysqlconnector://root:11111111@127.0.0.1:3306/flaskvueadmin"
class TestingConfig(Config):
TESTING = True
SQLALCHEMY_DATABASE_URI = "mysql+mysqlconnector://root:11111111@127.0.0.1:3306/flaskvueadmin"
class ProductionConfig(Config):
SQLALCHEMY_DATABASE_URI = "mysql+mysqlconnector://root:11111111@172.19.0.3:3306/flaskvueadmin"
config = {
'development': DevelopmentConfig,
'testing': TestingConfig,
'production': ProductionConfig,
'default': DevelopmentConfig
}
| [] | [] | [
"SECRET_KEY"
] | [] | ["SECRET_KEY"] | python | 1 | 0 | |
src/react-material-backend/routes/off.py | import os
import sys,json
def read_in():
lines = sys.stdin.readlines()
# Since our input would only be having one line, parse our JSON data from that
return json.loads(lines[0])
var=read_in()
t=int(var[0])
# print(t)
os.system("sshpass -p 'mouni1995' ssh 'user@10.2.24.157' 'cd tools;python off.py %d' "%t)
# print ("hello")
| [] | [] | [] | [] | [] | python | null | null | null |
compiler/tests/22_sram_1bank_nomux_func_test.py | #!/usr/bin/env python3
# See LICENSE for licensing information.
#
# Copyright (c) 2016-2021 Regents of the University of California and The Board
# of Regents for the Oklahoma Agricultural and Mechanical College
# (acting for and on behalf of Oklahoma State University)
# All rights reserved.
#
import unittest
from testutils import *
import sys, os
sys.path.append(os.getenv("OPENRAM_HOME"))
import globals
from globals import OPTS
from sram_factory import factory
import debug
#@unittest.skip("SKIPPING 22_sram_func_test")
class sram_1bank_nomux_func_test(openram_test):
def runTest(self):
config_file = "{}/tests/configs/config".format(os.getenv("OPENRAM_HOME"))
globals.init_openram(config_file)
OPTS.analytical_delay = False
OPTS.netlist_only = True
OPTS.trim_netlist = False
# This is a hack to reload the characterizer __init__ with the spice version
from importlib import reload
import characterizer
reload(characterizer)
from characterizer import functional
from sram_config import sram_config
c = sram_config(word_size=4,
num_words=16,
num_banks=1)
c.words_per_row=1
c.recompute_sizes()
debug.info(1, "Functional test for sram with "
"{} bit words, {} words, {} words per row, {} banks".format(c.word_size,
c.num_words,
c.words_per_row,
c.num_banks))
s = factory.create(module_type="sram", sram_config=c)
f = functional(s.s)
(fail, error) = f.run()
self.assertTrue(fail, error)
globals.end_openram()
# run the test from the command line
if __name__ == "__main__":
(OPTS, args) = globals.parse_args()
del sys.argv[1:]
header(__file__, OPTS.tech_name)
unittest.main(testRunner=debugTestRunner())
| [] | [] | [
"OPENRAM_HOME"
] | [] | ["OPENRAM_HOME"] | python | 1 | 0 | |
pkg/config/raw_meta.go | package config
import (
"fmt"
"os"
"github.com/werf/werf/pkg/slug"
)
type rawMeta struct {
ConfigVersion *int `yaml:"configVersion,omitempty"`
Project *string `yaml:"project,omitempty"`
DeployTemplates *rawMetaDeployTemplates `yaml:"deploy,omitempty"`
Cleanup *rawMetaCleanup `yaml:"cleanup,omitempty"`
doc *doc `yaml:"-"` // parent
UnsupportedAttributes map[string]interface{} `yaml:",inline"`
}
func (c *rawMeta) UnmarshalYAML(unmarshal func(interface{}) error) error {
parentStack.Push(c)
type plain rawMeta
err := unmarshal((*plain)(c))
parentStack.Pop()
if err != nil {
return err
}
if err := checkOverflow(c.UnsupportedAttributes, nil, c.doc); err != nil {
return err
}
if c.ConfigVersion == nil || *c.ConfigVersion != 1 {
return newDetailedConfigError("'configVersion: 1' field required!", nil, c.doc)
}
if c.Project == nil || *c.Project == "" {
return newDetailedConfigError("'project' field cannot be empty!", nil, c.doc)
}
if err := slug.ValidateProject(*c.Project); err != nil {
return newDetailedConfigError(fmt.Sprintf("bad project name '%s' specified in config: %s", *c.Project, err), nil, c.doc)
}
return nil
}
func (c *rawMeta) toMeta() *Meta {
meta := &Meta{}
if c.ConfigVersion != nil {
meta.ConfigVersion = *c.ConfigVersion
}
if c.Project != nil {
werfProjectName := os.Getenv("WERF_PROJECT_NAME")
if werfProjectName != "" {
meta.Project = werfProjectName
} else {
meta.Project = *c.Project
}
}
if c.Cleanup != nil {
meta.Cleanup = c.Cleanup.toMetaCleanup()
}
if c.DeployTemplates != nil {
meta.DeployTemplates = c.DeployTemplates.toDeployTemplates()
}
return meta
}
| [
"\"WERF_PROJECT_NAME\""
] | [] | [
"WERF_PROJECT_NAME"
] | [] | ["WERF_PROJECT_NAME"] | go | 1 | 0 | |
core/creator/src/main/java/io/quarkus/creator/phase/nativeimage/NativeImagePhase.java | /*
* Copyright 2018 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.quarkus.creator.phase.nativeimage;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
import java.util.concurrent.CountDownLatch;
import java.util.stream.Collectors;
import org.eclipse.microprofile.config.Config;
import org.jboss.logging.Logger;
import io.quarkus.creator.AppCreationPhase;
import io.quarkus.creator.AppCreator;
import io.quarkus.creator.AppCreatorException;
import io.quarkus.creator.config.reader.PropertiesHandler;
import io.quarkus.creator.config.reader.PropertyContext;
import io.quarkus.creator.outcome.OutcomeProviderRegistration;
import io.quarkus.creator.phase.augment.AugmentOutcome;
import io.quarkus.creator.phase.runnerjar.RunnerJarOutcome;
import io.quarkus.creator.util.IoUtils;
import io.smallrye.config.SmallRyeConfigProviderResolver;
/**
* The outcome of this phase is a native image
*
* @author Alexey Loubyansky
*/
public class NativeImagePhase implements AppCreationPhase<NativeImagePhase>, NativeImageOutcome {
private static final Logger log = Logger.getLogger(NativeImagePhase.class);
private static final String GRAALVM_HOME = "GRAALVM_HOME";
private static final String QUARKUS_PREFIX = "quarkus.";
private static final boolean IS_LINUX = System.getProperty("os.name").toLowerCase(Locale.ROOT).contains("linux");
private Path outputDir;
private boolean reportErrorsAtRuntime;
private boolean debugSymbols;
private boolean debugBuildProcess;
private boolean cleanupServer;
private boolean enableHttpUrlHandler;
private boolean enableHttpsUrlHandler;
private boolean enableAllSecurityServices;
private boolean enableRetainedHeapReporting;
private boolean enableCodeSizeReporting;
private boolean enableIsolates;
private String graalvmHome;
private boolean enableServer;
private boolean enableJni;
private boolean autoServiceLoaderRegistration;
private boolean dumpProxies;
private String nativeImageXmx;
private String dockerBuild;
private boolean enableVMInspection;
private boolean fullStackTraces;
private boolean disableReports;
private List<String> additionalBuildArgs;
public NativeImagePhase setOutputDir(Path outputDir) {
this.outputDir = outputDir;
return this;
}
public NativeImagePhase setReportErrorsAtRuntime(boolean reportErrorsAtRuntime) {
this.reportErrorsAtRuntime = reportErrorsAtRuntime;
return this;
}
public NativeImagePhase setDebugSymbols(boolean debugSymbols) {
this.debugSymbols = debugSymbols;
return this;
}
public NativeImagePhase setDebugBuildProcess(boolean debugBuildProcess) {
this.debugBuildProcess = debugBuildProcess;
return this;
}
public NativeImagePhase setCleanupServer(boolean cleanupServer) {
this.cleanupServer = cleanupServer;
return this;
}
public NativeImagePhase setEnableHttpUrlHandler(boolean enableHttpUrlHandler) {
this.enableHttpUrlHandler = enableHttpUrlHandler;
return this;
}
public NativeImagePhase setEnableHttpsUrlHandler(boolean enableHttpsUrlHandler) {
this.enableHttpsUrlHandler = enableHttpsUrlHandler;
return this;
}
public NativeImagePhase setEnableAllSecurityServices(boolean enableAllSecurityServices) {
this.enableAllSecurityServices = enableAllSecurityServices;
return this;
}
public NativeImagePhase setEnableRetainedHeapReporting(boolean enableRetainedHeapReporting) {
this.enableRetainedHeapReporting = enableRetainedHeapReporting;
return this;
}
public NativeImagePhase setEnableCodeSizeReporting(boolean enableCodeSizeReporting) {
this.enableCodeSizeReporting = enableCodeSizeReporting;
return this;
}
public NativeImagePhase setEnableIsolates(boolean enableIsolates) {
this.enableIsolates = enableIsolates;
return this;
}
public NativeImagePhase setGraalvmHome(String graalvmHome) {
this.graalvmHome = graalvmHome;
return this;
}
public NativeImagePhase setEnableServer(boolean enableServer) {
this.enableServer = enableServer;
return this;
}
public NativeImagePhase setEnableJni(boolean enableJni) {
this.enableJni = enableJni;
return this;
}
public NativeImagePhase setAutoServiceLoaderRegistration(boolean autoServiceLoaderRegistration) {
this.autoServiceLoaderRegistration = autoServiceLoaderRegistration;
return this;
}
public NativeImagePhase setDumpProxies(boolean dumpProxies) {
this.dumpProxies = dumpProxies;
return this;
}
public NativeImagePhase setNativeImageXmx(String nativeImageXmx) {
this.nativeImageXmx = nativeImageXmx;
return this;
}
public NativeImagePhase setDockerBuild(String dockerBuild) {
this.dockerBuild = dockerBuild;
return this;
}
public NativeImagePhase setEnableVMInspection(boolean enableVMInspection) {
this.enableVMInspection = enableVMInspection;
return this;
}
public NativeImagePhase setFullStackTraces(boolean fullStackTraces) {
this.fullStackTraces = fullStackTraces;
return this;
}
public NativeImagePhase setDisableReports(boolean disableReports) {
this.disableReports = disableReports;
return this;
}
public NativeImagePhase setAdditionalBuildArgs(List<String> additionalBuildArgs) {
this.additionalBuildArgs = additionalBuildArgs;
return this;
}
@Override
public void register(OutcomeProviderRegistration registration) throws AppCreatorException {
registration.provides(NativeImageOutcome.class);
}
@Override
public void provideOutcome(AppCreator ctx) throws AppCreatorException {
outputDir = outputDir == null ? ctx.getWorkPath() : IoUtils.mkdirs(outputDir);
final RunnerJarOutcome runnerJarOutcome = ctx.resolveOutcome(RunnerJarOutcome.class);
Path runnerJar = runnerJarOutcome.getRunnerJar();
boolean runnerJarCopied = false;
// this trick is here because docker needs the jar in the project dir
if (!runnerJar.getParent().equals(outputDir)) {
try {
runnerJar = IoUtils.copy(runnerJar, outputDir.resolve(runnerJar.getFileName()));
} catch (IOException e) {
throw new AppCreatorException("Failed to copy the runnable jar to the output dir", e);
}
runnerJarCopied = true;
}
final String runnerJarName = runnerJar.getFileName().toString();
Path outputLibDir = outputDir.resolve(runnerJarOutcome.getLibDir().getFileName());
boolean outputLibDirCopied = false;
if (Files.exists(outputLibDir)) {
outputLibDir = null;
} else {
try {
IoUtils.copy(runnerJarOutcome.getLibDir(), outputLibDir);
} catch (IOException e) {
throw new AppCreatorException("Failed to copy the runnable jar and the lib to the docker project dir", e);
}
outputLibDirCopied = true;
}
final Config config = SmallRyeConfigProviderResolver.instance().getConfig();
boolean vmVersionOutOfDate = isThisGraalVMRCObsolete();
HashMap<String, String> env = new HashMap<>(System.getenv());
List<String> nativeImage;
String noPIE = "";
if (dockerBuild != null && !dockerBuild.toLowerCase().equals("false")) {
// E.g. "/usr/bin/docker run -v {{PROJECT_DIR}}:/project --rm quarkus/graalvm-native-image"
nativeImage = new ArrayList<>();
//TODO: use an 'official' image
String image;
if (dockerBuild.toLowerCase().equals("true")) {
image = "swd847/centos-graal-native-image-rc12";
} else {
//allow the use of a custom image
image = dockerBuild;
}
Collections.addAll(nativeImage, "docker", "run", "-v", outputDir.toAbsolutePath() + ":/project:z", "--rm", image);
} else {
if (IS_LINUX) {
noPIE = detectNoPIE();
}
String graalvmHome = this.graalvmHome;
if (graalvmHome != null) {
env.put(GRAALVM_HOME, graalvmHome);
} else {
graalvmHome = env.get(GRAALVM_HOME);
if (graalvmHome == null) {
throw new AppCreatorException("GRAALVM_HOME was not set");
}
}
nativeImage = Collections.singletonList(graalvmHome + File.separator + "bin" + File.separator + "native-image");
}
try {
List<String> command = new ArrayList<>();
command.addAll(nativeImage);
if (cleanupServer) {
List<String> cleanup = new ArrayList<>(nativeImage);
cleanup.add("--server-shutdown");
ProcessBuilder pb = new ProcessBuilder(cleanup.toArray(new String[0]));
pb.directory(outputDir.toFile());
pb.redirectInput(ProcessBuilder.Redirect.INHERIT);
pb.redirectOutput(ProcessBuilder.Redirect.INHERIT);
pb.redirectError(ProcessBuilder.Redirect.INHERIT);
Process process = pb.start();
process.waitFor();
}
// TODO this is a temp hack
final Path propsFile = ctx.resolveOutcome(AugmentOutcome.class).getAppClassesDir()
.resolve("native-image.properties");
boolean enableSslNative = false;
if (Files.exists(propsFile)) {
final Properties properties = new Properties();
try (BufferedReader reader = Files.newBufferedReader(propsFile, StandardCharsets.UTF_8)) {
properties.load(reader);
}
for (String propertyName : properties.stringPropertyNames()) {
if (propertyName.startsWith(QUARKUS_PREFIX)) {
continue;
}
final String propertyValue = properties.getProperty(propertyName);
// todo maybe just -D is better than -J-D in this case
if (propertyValue == null) {
command.add("-J-D" + propertyName);
} else {
command.add("-J-D" + propertyName + "=" + propertyValue);
}
}
enableSslNative = properties.getProperty("quarkus.ssl.native") != null
? Boolean.parseBoolean(properties.getProperty("quarkus.ssl.native"))
: false;
}
if (enableSslNative) {
enableHttpsUrlHandler = true;
enableJni = true;
enableAllSecurityServices = true;
}
if (additionalBuildArgs != null) {
additionalBuildArgs.forEach(command::add);
}
command.add("-H:InitialCollectionPolicy=com.oracle.svm.core.genscavenge.CollectionPolicy$BySpaceAndTime"); //the default collection policy results in full GC's 50% of the time
command.add("-jar");
command.add(runnerJarName);
//https://github.com/oracle/graal/issues/660
command.add("-J-Djava.util.concurrent.ForkJoinPool.common.parallelism=1");
if (reportErrorsAtRuntime) {
command.add("-H:+ReportUnsupportedElementsAtRuntime");
}
if (debugSymbols) {
command.add("-g");
}
if (debugBuildProcess) {
command.add("-J-Xrunjdwp:transport=dt_socket,address=5005,server=y,suspend=y");
}
if (!disableReports) {
command.add("-H:+PrintAnalysisCallTree");
}
if (dumpProxies) {
command.add("-Dsun.misc.ProxyGenerator.saveGeneratedFiles=true");
if (enableServer) {
log.warn(
"Options dumpProxies and enableServer are both enabled: this will get the proxies dumped in an unknown external working directory");
}
}
if (nativeImageXmx != null) {
command.add("-J-Xmx" + nativeImageXmx);
}
List<String> protocols = new ArrayList<>(2);
if (enableHttpUrlHandler) {
protocols.add("http");
}
if (enableHttpsUrlHandler) {
protocols.add("https");
}
if (!protocols.isEmpty()) {
command.add("-H:EnableURLProtocols=" + String.join(",", protocols));
}
if (enableAllSecurityServices) {
command.add("--enable-all-security-services");
}
if (!noPIE.isEmpty()) {
command.add("-H:NativeLinkerOption=" + noPIE);
}
if (enableRetainedHeapReporting) {
command.add("-H:+PrintRetainedHeapHistogram");
}
if (enableCodeSizeReporting) {
command.add("-H:+PrintCodeSizeReport");
}
if (!enableIsolates) {
command.add("-H:-SpawnIsolates");
}
if (enableJni) {
command.add("-H:+JNI");
} else {
command.add("-H:-JNI");
}
if (!enableServer) {
command.add("--no-server");
}
if (enableVMInspection) {
command.add("-H:+AllowVMInspection");
}
if (autoServiceLoaderRegistration) {
command.add("-H:+UseServiceLoaderFeature");
//When enabling, at least print what exactly is being added:
command.add("-H:+TraceServiceLoaderFeature");
} else {
command.add("-H:-UseServiceLoaderFeature");
}
if (fullStackTraces) {
command.add("-H:+StackTrace");
} else {
command.add("-H:-StackTrace");
}
log.info(command.stream().collect(Collectors.joining(" ")));
CountDownLatch errorReportLatch = new CountDownLatch(1);
ProcessBuilder pb = new ProcessBuilder(command.toArray(new String[0]));
pb.directory(outputDir.toFile());
pb.redirectInput(ProcessBuilder.Redirect.INHERIT);
pb.redirectOutput(ProcessBuilder.Redirect.INHERIT);
Process process = pb.start();
new Thread(new ErrorReplacingProcessReader(process.getErrorStream(), outputDir.resolve("reports").toFile(),
errorReportLatch)).start();
errorReportLatch.await();
if (process.waitFor() != 0) {
throw new RuntimeException("Image generation failed");
}
System.setProperty("native.image.path", runnerJarName.substring(0, runnerJarName.lastIndexOf('.')));
ctx.pushOutcome(NativeImageOutcome.class, this);
} catch (Exception e) {
throw new AppCreatorException("Failed to build native image", e);
} finally {
if (runnerJarCopied) {
IoUtils.recursiveDelete(runnerJar);
}
if (outputLibDirCopied) {
IoUtils.recursiveDelete(outputLibDir);
}
}
}
//FIXME remove after transition period
private boolean isThisGraalVMRCObsolete() {
final String vmName = System.getProperty("java.vm.name");
log.info("Running Quarkus native-image plugin on " + vmName);
if (vmName.contains("-rc9") || vmName.contains("-rc10") || vmName.contains("-rc11")) {
log.error("Out of date RC build of GraalVM detected! Please upgrade to RC12");
return true;
}
return false;
}
private static String detectNoPIE() {
String argument = testGCCArgument("-no-pie");
return argument.length() == 0 ? testGCCArgument("-nopie") : argument;
}
private static String testGCCArgument(String argument) {
try {
Process gcc = new ProcessBuilder("cc", "-v", "-E", argument, "-").start();
gcc.getOutputStream().close();
if (gcc.waitFor() == 0) {
return argument;
}
} catch (IOException | InterruptedException e) {
// eat
}
return "";
}
@Override
public String getConfigPropertyName() {
return "native-image";
}
@Override
public PropertiesHandler<NativeImagePhase> getPropertiesHandler() {
return new PropertiesHandler<NativeImagePhase>() {
@Override
public NativeImagePhase getTarget() {
return NativeImagePhase.this;
}
@Override
public boolean set(NativeImagePhase t, PropertyContext ctx) {
//System.out.println("native-image.set " + ctx.getRelativeName() + "=" + ctx.getValue());
final String value = ctx.getValue();
switch (ctx.getRelativeName()) {
case "output":
t.setOutputDir(Paths.get(value));
break;
case "report-errors-at-runtime":
t.setReportErrorsAtRuntime(Boolean.parseBoolean(value));
break;
case "debug-symbols":
t.setDebugSymbols(Boolean.parseBoolean(value));
break;
case "debug-build-process":
t.setDebugBuildProcess(Boolean.parseBoolean(value));
break;
case "cleanup-server":
t.setCleanupServer(Boolean.parseBoolean(value));
break;
case "enable-http-url-handler":
t.setEnableHttpUrlHandler(Boolean.parseBoolean(value));
break;
case "enable-https-url-handler":
t.setEnableHttpsUrlHandler(Boolean.parseBoolean(value));
break;
case "enable-all-security-services":
t.setEnableAllSecurityServices(Boolean.parseBoolean(value));
break;
case "enable-retained-heap-reporting":
t.setEnableRetainedHeapReporting(Boolean.parseBoolean(value));
break;
case "enable-code-size-reporting":
t.setEnableCodeSizeReporting(Boolean.parseBoolean(value));
break;
case "enable-isolates":
t.setEnableIsolates(Boolean.parseBoolean(value));
break;
case "graalvm-home":
t.setGraalvmHome(value);
break;
case "enable-server":
t.setEnableServer(Boolean.parseBoolean(value));
break;
case "enable-jni":
t.setEnableJni(Boolean.parseBoolean(value));
break;
case "auto-service-loader-registration":
t.setAutoServiceLoaderRegistration(Boolean.parseBoolean(value));
break;
case "dump-proxies":
t.setDumpProxies(Boolean.parseBoolean(value));
break;
case "native-image-xmx":
t.setNativeImageXmx(value);
break;
case "docker-build":
t.setDockerBuild(value);
break;
case "enable-vm-inspection":
t.setEnableVMInspection(Boolean.parseBoolean(value));
break;
case "full-stack-traces":
t.setFullStackTraces(Boolean.parseBoolean(value));
break;
case "disable-reports":
t.setDisableReports(Boolean.parseBoolean(value));
break;
case "additional-build-args":
t.setAdditionalBuildArgs(Arrays.asList(value.split(",")));
break;
default:
return false;
}
return true;
}
};
}
}
| [] | [] | [] | [] | [] | java | 0 | 0 | |
samples/snippets/conftest.py | # Copyright 2020 Google LLC
#
# 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.
import datetime
import os
import random
import uuid
from google.api_core import client_options
import google.api_core.exceptions
import google.auth
from google.cloud import bigquery
from google.cloud import bigquery_datatransfer
from google.cloud import pubsub_v1
import pytest
RESOURCE_PREFIX = "python_bigquery_datatransfer_samples_snippets"
RESOURCE_DATE_FORMAT = "%Y%m%d%H%M%S"
RESOURCE_DATE_LENGTH = 4 + 2 + 2 + 2 + 2 + 2
def resource_prefix() -> str:
timestamp = datetime.datetime.utcnow().strftime(RESOURCE_DATE_FORMAT)
random_string = hex(random.randrange(1000000))[2:]
return f"{RESOURCE_PREFIX}_{timestamp}_{random_string}"
def resource_name_to_date(resource_name: str):
start_date = len(RESOURCE_PREFIX) + 1
date_string = resource_name[start_date : start_date + RESOURCE_DATE_LENGTH]
parsed_date = datetime.datetime.strptime(date_string, RESOURCE_DATE_FORMAT)
return parsed_date
@pytest.fixture(scope="session", autouse=True)
def cleanup_pubsub_topics(pubsub_client: pubsub_v1.PublisherClient, project_id):
yesterday = datetime.datetime.utcnow() - datetime.timedelta(days=1)
for topic in pubsub_client.list_topics(project=f"projects/{project_id}"):
topic_id = topic.name.split("/")[-1]
if (
topic_id.startswith(RESOURCE_PREFIX)
and resource_name_to_date(topic_id) < yesterday
):
pubsub_client.delete_topic(topic=topic.name)
def temp_suffix():
now = datetime.datetime.now()
return f"{now.strftime('%Y%m%d%H%M%S')}_{uuid.uuid4().hex[:8]}"
@pytest.fixture(scope="session")
def bigquery_client(default_credentials):
credentials, project_id = default_credentials
return bigquery.Client(credentials=credentials, project=project_id)
@pytest.fixture(scope="session")
def pubsub_client(default_credentials):
credentials, _ = default_credentials
return pubsub_v1.PublisherClient(credentials=credentials)
@pytest.fixture(scope="session")
def pubsub_topic(pubsub_client: pubsub_v1.PublisherClient, project_id):
topic_id = resource_prefix()
topic_path = pubsub_v1.PublisherClient.topic_path(project_id, topic_id)
pubsub_client.create_topic(name=topic_path)
yield topic_path
pubsub_client.delete_topic(topic=topic_path)
@pytest.fixture(scope="session")
def dataset_id(bigquery_client, project_id):
dataset_id = f"bqdts_{temp_suffix()}"
bigquery_client.create_dataset(f"{project_id}.{dataset_id}")
yield dataset_id
bigquery_client.delete_dataset(dataset_id, delete_contents=True)
@pytest.fixture(scope="session")
def default_credentials():
return google.auth.default(["https://www.googleapis.com/auth/cloud-platform"])
@pytest.fixture(scope="session")
def project_id():
return os.environ["GOOGLE_CLOUD_PROJECT"]
@pytest.fixture(scope="session")
def service_account_name(default_credentials):
credentials, _ = default_credentials
# The service_account_email attribute is not available when running with
# user account credentials, but should be available when running from our
# continuous integration tests.
return getattr(credentials, "service_account_email", None)
@pytest.fixture(scope="session")
def transfer_client(default_credentials, project_id):
credentials, _ = default_credentials
options = client_options.ClientOptions(quota_project_id=project_id)
transfer_client = bigquery_datatransfer.DataTransferServiceClient(
credentials=credentials, client_options=options
)
# Ensure quota is always attributed to the correct project.
bigquery_datatransfer.DataTransferServiceClient = lambda: transfer_client
return transfer_client
@pytest.fixture(scope="session")
def transfer_config_name(transfer_client, project_id, dataset_id, service_account_name):
from . import manage_transfer_configs, scheduled_query
# Use the transfer_client fixture so we know quota is attributed to the
# correct project.
assert transfer_client is not None
# To conserve limited BQ-DTS quota, this fixture creates only one transfer
# config for a whole session and is used to test the scheduled_query.py and
# the delete operation in manage_transfer_configs.py.
transfer_config = scheduled_query.create_scheduled_query(
{
"project_id": project_id,
"dataset_id": dataset_id,
"service_account_name": service_account_name,
}
)
yield transfer_config.name
manage_transfer_configs.delete_config(
{"transfer_config_name": transfer_config.name}
)
@pytest.fixture
def to_delete_configs(transfer_client):
to_delete = []
yield to_delete
for config_name in to_delete:
try:
transfer_client.delete_transfer_config(name=config_name)
except google.api_core.exceptions.GoogleAPICallError:
pass
| [] | [] | [
"GOOGLE_CLOUD_PROJECT"
] | [] | ["GOOGLE_CLOUD_PROJECT"] | python | 1 | 0 | |
kernel_image_puller.py | import logging
import os
import queue
import requests
import time
from threading import Thread
cri_sock = os.getenv("KIP_CRI_SOCK", "unix:///var/run/containerd/containerd.sock")
cri_client = os.getenv("KIP_CRI_CLI", False)
gateway_host = os.getenv("KIP_GATEWAY_HOST", "http://localhost:8888")
num_pullers = int(os.getenv("KIP_NUM_PULLERS", "2"))
num_retries = int(os.getenv("KIP_NUM_RETRIES", "3"))
interval = int(os.getenv("KIP_INTERVAL", "300"))
log_level = os.getenv("KIP_LOG_LEVEL", "INFO")
POLICY_IF_NOT_PRESENT = "IfNotPresent"
POLICY_ALYWAYS = "Always"
policies = (POLICY_IF_NOT_PRESENT, POLICY_ALYWAYS)
policy = os.getenv("KIP_PULL_POLICY", POLICY_IF_NOT_PRESENT)
if cri_client or cri_client in ('Yes', 'yes', 'True', 'true'):
from docker.errors import NotFound
from cri_api.channel import Channel
from cri_api.images import Images
from cri_api.exceptions import ImageServiceException as APIError
class DockerMocker:
def __init__(self, cli):
self.cli=cli
def get(self, img_name):
ret=self.cli.get_image(img_name)
if ret is None:
raise NotFound
else:
return ret
def pull(self, img_name):
try:
self.cli.pull_image(img_name)
except APIError as err:
if "failed to resolve image" in str(err):
raise NotFound(err)
else:
raise APIError(err)
class CriClient:
def __init__(self, cri_sock):
self.channel=Channel(cri_sock)
self.cli=Images(self.channel)
self.images=DockerMocker(self.cli)
docker_client = CriClient(cri_sock)
else:
from docker.client import DockerClient
from docker.errors import APIError
from docker.errors import NotFound
docker_client = DockerClient.from_env()
logging.basicConfig(format='[%(levelname)1.1s %(asctime)s %(name)s.%(threadName)s] %(message)s')
def get_kernelspecs():
"""Fetches the set of kernelspecs from the gateway, returning a dict of configured kernel specs"""
end_point = '{}/api/kernelspecs'.format(gateway_host)
logger.info("Fetching kernelspecs from '{}' ...".format(end_point))
resp = requests.get(end_point)
if not resp.ok:
raise requests.exceptions.HTTPError('Gateway server response: {}'.format(resp.status_code))
return resp.json()
def fetch_image_names():
"""Fetches the image names by hitting the /api/kernelspecs endpoint of the Gateway.
For process-proxy kernelspecs, the image names are contained in the config stanza - which
resides in the process-proxy stanza located in the metadata.
"""
kspecs = None
try:
kspecs_response = get_kernelspecs()
kspecs = kspecs_response.get('kernelspecs')
except Exception as ex:
logger.error("Got exception attempting to retrieve kernelspecs - retrying. Exception was: {}".format(ex))
finally:
if kspecs is None:
return False
# Locate the configured images within the kernelspecs and add to set for duplicate management
images = set()
for key in kspecs.keys():
metadata = kspecs.get(key).get('spec').get('metadata')
if metadata is not None:
process_proxy = metadata.get('process_proxy')
if process_proxy is not None:
config = process_proxy.get('config')
if config is not None:
image_name = config.get('image_name')
if image_name is not None:
images.add(image_name)
executor_image_name = config.get('executor_image_name')
if executor_image_name is not None:
images.add(executor_image_name)
# Add the image names to the name queue
for image_name in images:
name_queue.put_nowait(image_name)
return True
def pull_image(image_name):
"""Pulls the image.
If the policy is `IfNotPresent` the set of pulled image names is
checked and, if present, the method returns. Otherwise, the pull attempt is made
and the set of pulled images is updated, when successful.
Since NotFound exceptions are tolerated, we trap for only that exception and let
the caller handle others.
"""
if policy == POLICY_IF_NOT_PRESENT:
if image_name in pulled_images:
# Image has been pulled, but make sure it still exists. If it doesn't exist
# let this drop through to actual pull
logger.info("Image '{}' already pulled and policy is '{}'. Checking existence.".
format(image_name, policy))
try:
t1 = time.time()
docker_client.images.get(image_name)
t2 = time.time()
logger.debug("Checked existence of image '{}' in {:.3f} secs.".format(image_name, t2 - t1))
return
except NotFound:
pulled_images.remove(image_name)
logger.warning("Previously pulled image '{}' was not found - attempting pull...".format(image_name))
logger.debug("Pulling image '{}'...".format(image_name))
try:
t1 = time.time()
docker_client.images.pull(image_name)
t2 = time.time()
pulled_images.add(image_name)
logger.info("Pulled image '{}' in {:.3f} secs.".format(image_name, t2 - t1))
except NotFound:
logger.warning("Image '{}' was not found!".format(image_name))
def puller():
"""Thread-based puller.
Gets image name from the queue and attempts to pull the image. Any issues, except
for NotFound, are retried up to num_retries times. Once the image has been pulled, it's not found or the
retries have been exceeded, the queue task is marked as done.
"""
while True:
image_name = name_queue.get()
if image_name is None:
break
i = 0
while i < num_retries:
try:
pull_image(image_name)
break
except APIError as ex:
i += 1
if i < num_retries:
logger.warning("Attempt {} to pull image '{}' encountered exception - retrying. Exception was: {}".
format(i, image_name, ex))
else:
logger.error("Attempt {} to pull image '{}' failed with exception: {}".
format(i, image_name, ex))
name_queue.task_done()
if __name__ == "__main__":
logger = logging.getLogger('kernel_image_puller')
logger.setLevel(log_level)
# Determine pull policy.
pulled_images = set()
if policy not in policies:
logger.warning("Invalid pull policy detected in KIP_PULL_POLICY: '{}'. Using policy '{}'.".
format(policy, POLICY_IF_NOT_PRESENT))
policy = POLICY_IF_NOT_PRESENT
logger.info("Starting Kernel Image Puller with the following parameters:")
logger.info("KIP_GATEWAY_HOST: {}".format(gateway_host))
logger.info("KIP_CRI_CLI: {}".format(cri_client))
logger.info("KIP_CRI_SOCK: {}".format(cri_sock))
logger.info("KIP_INTERVAL: {} secs".format(interval))
logger.info("KIP_NUM_PULLERS: {}".format(num_pullers))
logger.info("KIP_NUM_RETRIES: {}".format(num_retries))
logger.info("KIP_PULL_POLICY: {}".format(policy))
logger.info("KIP_LOG_LEVEL: {}\n".format(log_level))
# Create an empty queue and start the puller threads. The number of puller threads is configurable.
name_queue = queue.Queue()
threads = []
for i in range(num_pullers):
t = Thread(target=puller, name="t{}".format(i + 1))
t.start()
threads.append(t)
# Fetch the image names, then wait for name queue to drain. Once drained, or if there were issues
# fetching the image names, wait the interval number of seconds and perform the operation again.
wait_interval = 5 # Start with 5 seconds to ensure EG service gets started...
time.sleep(wait_interval)
while True:
fetched = fetch_image_names()
if fetched:
wait_interval = interval # Once we have fetched kernelspecs, update wait_interval
name_queue.join()
logger.info("Images pulled. Sleeping {} seconds...\n".format(wait_interval))
else:
logger.info("Sleeping {} seconds to fetch image names...\n".format(wait_interval))
time.sleep(wait_interval)
| [] | [] | [
"KIP_GATEWAY_HOST",
"KIP_CRI_CLI",
"KIP_LOG_LEVEL",
"KIP_NUM_PULLERS",
"KIP_CRI_SOCK",
"KIP_INTERVAL",
"KIP_PULL_POLICY",
"KIP_NUM_RETRIES"
] | [] | ["KIP_GATEWAY_HOST", "KIP_CRI_CLI", "KIP_LOG_LEVEL", "KIP_NUM_PULLERS", "KIP_CRI_SOCK", "KIP_INTERVAL", "KIP_PULL_POLICY", "KIP_NUM_RETRIES"] | python | 8 | 0 | |
conf.py | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
# flake8: noqa
# -*- coding: utf-8 -*-
#
# Spack documentation build configuration file, created by
# sphinx-quickstart on Mon Dec 9 15:32:41 2013.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
import re
import subprocess
from glob import glob
# -- Spack customizations -----------------------------------------------------
# Add the Spack bin directory to the path so that we can use its output in docs.
os.environ['SPACK_ROOT'] = os.path.abspath('_spack_root')
os.environ['PATH'] += "%s%s" % (os.pathsep, os.path.abspath('_spack_root/bin'))
# Set an environment variable so that colify will print output like it would to
# a terminal.
os.environ['COLIFY_SIZE'] = '25x120'
os.environ['COLUMNS'] = '120'
# Enable todo items
todo_include_todos = True
#
# Disable duplicate cross-reference warnings.
#
from sphinx.domains.python import PythonDomain
class PatchedPythonDomain(PythonDomain):
def resolve_xref(self, env, fromdocname, builder, typ, target, node, contnode):
if 'refspecific' in node:
del node['refspecific']
return super(PatchedPythonDomain, self).resolve_xref(
env, fromdocname, builder, typ, target, node, contnode)
def setup(sphinx):
sphinx.add_domain(PatchedPythonDomain, override=True)
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
needs_sphinx = '1.8'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.graphviz',
'sphinx.ext.todo',
'sphinx_copybutton']
# Set default graphviz options
graphviz_dot_args = [
'-Grankdir=LR', '-Gbgcolor=transparent',
'-Nshape=box', '-Nfontname=monaco', '-Nfontsize=10']
# Get nice vector graphics
graphviz_output_format = "svg"
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Spack Tutorial'
copyright = u'2013-2021, Lawrence Livermore National Laboratory.'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
#import spack
#version = '.'.join(str(s) for s in spack.spack_version_info[:2])
# The full version, including alpha/beta/rc tags.
#release = spack.spack_version
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# Places to look for .po/.mo files for doc translations
#locale_dirs = []
# Sphinx gettext settings
gettext_compact = True
gettext_uuid = False
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build', '_spack_root']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
# We use our own extension of the default style with a few modifications
from pygments.style import Style
from pygments.styles.default import DefaultStyle
from pygments.token import Generic, Comment, Text
class SpackStyle(DefaultStyle):
styles = DefaultStyle.styles.copy()
background_color = "#f4f4f8"
styles[Generic.Output] = "#355"
styles[Generic.Prompt] = "bold #346ec9"
import pkg_resources
dist = pkg_resources.Distribution(__file__)
sys.path.append('.') # make 'conf' module findable
ep = pkg_resources.EntryPoint.parse('spack = conf:SpackStyle', dist=dist)
dist._ep_map = {'pygments.styles': {'plugin1': ep}}
pkg_resources.working_set.add(dist)
pygments_style = 'spack'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'sphinx_rtd_theme'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
html_theme_options = { 'logo_only' : True }
# Add any paths that contain custom themes here, relative to this directory.
# html_theme_path = ["_themes"]
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
html_logo = '_spack_root/share/spack/logo/spack-logo-white-text.svg'
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
html_favicon = '_spack_root/share/spack/logo/favicon.ico'
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = False
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'Spackdoc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'Spack.tex', u'Spack Documentation',
u'Todd Gamblin', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'spack', u'Spack Documentation',
[u'Todd Gamblin'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'Spack', u'Spack Documentation',
u'Todd Gamblin', 'Spack', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
| [] | [] | [
"COLIFY_SIZE",
"SPACK_ROOT",
"PATH",
"COLUMNS"
] | [] | ["COLIFY_SIZE", "SPACK_ROOT", "PATH", "COLUMNS"] | python | 4 | 0 | |
backend/cloud-function-trigger/slack.py | from slacker import Slacker
import os
API_KEY = os.environ["SLACK_API_KEY"]
CHANNEL = os.environ["SLACK_CHANNEL"]
slacker = Slacker(API_KEY)
def post(_str, pretext=None, title=None, color="good", channel=None, image_url=None):
if channel is None:
channel = CHANNEL
slacker.chat.post_message(
channel,
attachments=[
{
"title": title,
"pretext": pretext,
"color": color,
"text": _str,
"image_url": image_url,
}
],
username="fast-cat",
icon_emoji=":cat-sit:",
)
| [] | [] | [
"SLACK_API_KEY",
"SLACK_CHANNEL"
] | [] | ["SLACK_API_KEY", "SLACK_CHANNEL"] | python | 2 | 0 | |
conf.py | #!/usr/bin/env python3# -*- coding: utf-8 -*-
# This is the configuration file of Sphynx, edit it as needed.
import sys
sys.path.append('.') # for rtd
import os
on_rtd = os.environ.get('READTHEDOCS') == 'True'
#keep it first so we don't get deprecation warnings
import jupman_tools as jmt
import recommonmark
from recommonmark.transform import AutoStructify
from recommonmark.parser import CommonMarkParser
import datetime
import glob
import re
################### TODO EDIT AS NEEDED !! ####################
jm = jmt.Jupman()
# TODO CHANGE
jm.subtitle = "A template manager for online books made with Jupyter notebooks and NBSphinx doc generator"""
jm.course = "Applied Pythonics" # TODO CHANGE
jm.degree = "Nuclear Templates Engineering" # TODO CHANGE
author = 'People That Write a Lot' # TODO CHANGE
# TODO FIRST YEAR
copyright = '# 2020 - %s, %s' % (datetime.datetime.now().year, author)
##### 'jm.filename' IS *VERY* IMPORTANT !!!!
##### IT IS PREPENDED IN MANY GENERATED FILES
##### AND IT SHOULD ALSO BE THE SAME NAME ON READTHEDOCS
##### (like i.e. jupman.readthedocs.org)
jm.filename = 'jupman' # The filename without the extension
# common files for exercise and exams as paths. Paths are intended relative to the project root. Globs like /**/* are allowed.
jm.chapter_files = ['jupman.py', 'my_lib.py', '_static/img/cc-by.png',
'_static/js/jupman.js', # these files are injected when you call jupman.init()
'_static/css/jupman.css',
'_static/js/toc.js',
'_static/js/pytutor-embed.bundle.min.js',]
jm.chapter_patterns = ['*/']
jm.chapter_exclude_patterns = ['[^_]*/','exams/', 'project/']
# words used in ipynb files - you might want to translate these in your language.
# Use singular
jm.ipynb_show_solution = "Show solution"
jm.ipynb_hide_solution = "Hide"
jm.ipynb_show_answer = "Show answer"
jm.ipynb_hide_answer = "Hide"
# Use plural
jm.ipynb_solutions = "SOLUTIONS"
jm.ipynb_exercises = "EXERCISES"
#NOTE: this string is not just a translation, it's also a command that when building the exercises
# removes the content after it in the Python cell it is contained in
# If the user inserts extra spaces the phrase will be recognized anyway
jm.write_solution_here = jmt.tag_regex("# write here", must_begin=False, preserve_line=True)
#NOTE: this string is not just a translation, it's also a command that when building the exercises
# completely removes the content of the python cell it is contained in (solution comment included).
# If the user inserts extra spaces the phrase will be recognized anyway
jm.solution = jmt.tag_regex("# SOLUTION")
#NOTE: this string is not just a translation, it's also a command that
# when building the exercises removes the content after it in the markdown cell
# it is contained in
jm.markdown_answer = jmt.tag_regex('**ANSWER**:')
#################################################################
jm.zip_ignored = ['__pycache__', '**.ipynb_checkpoints', '.pyc', '.cache', '.pytest_cache', '.vscode']
jm.formats = ["html", "epub", "latex"]
jm.build = "_build"
jm.manuals = {
"student": {
"name" : "Jupman", # TODO put manual name, like "Scientific Programming"
"audience" : "studenti",
"args" : "",
"output" : ""
}
}
jm.manual = 'student'
project = jm.manuals[jm.manual]['name']
jm.raise_exc = "jupman-raise"
jm.strip = "jupman-strip"
#WARNING: this string can end end up in a .ipynb json, so it must be a valid JSON string !
# Be careful with the double quotes and \n !!
jm.raise_exc_code = "raise Exception('TODO IMPLEMENT ME !')"
jm.tags = [jm.raise_exc, jm.strip]
# Use sphinx-quickstart to create your own conf.py file!
# After that, you have to edit a few things. See below.
# Select nbsphinx and, if needed, add a math extension (mathjax or pngmath):
extensions = [
'nbsphinx',
'sphinx.ext.mathjax',
'sphinx.ext.intersphinx',
'sphinx.ext.todo',
'sphinx.ext.ifconfig',
'recommonmark',
# July 2020: does not work, see https://github.com/DavidLeoni/jupman/issues/48
#'sphinxcontrib.googleanalytics'
# note: might be needed also for github actions, see https://github.com/DavidLeoni/jupman/issues/46
#'readthedocs_ext.readthedocs'
#, 'rst2pdf.pdfbuilder'
]
# Exclude build directory and Jupyter backup files:
exclude_patterns = [jm.build,
jm.generated,
"**-chal-sol.*",
"_templates/exam-server",
"_private",
"_test",
'README.md',
'readme.md']
exclude_patterns.extend(jm.zip_ignored)
# Default language for syntax highlighting in reST and Markdown cells
highlight_language = 'none'
# Don't add .txt suffix to source files (available for Sphinx >= 1.5):
html_sourcelink_suffix = ''
# Execute notebooks before conversion: 'always', 'never', 'auto' (default)
nbsphinx_execute = 'never'
# Use this kernel instead of the one stored in the notebook metadata:
nbsphinx_kernel_name = 'python3'
# List of arguments to be passed to the kernel that executes the notebooks:
#nbsphinx_execute_arguments = ['--InlineBackend.figure_formats={"png", "pdf"}']
# If True, the build process is continued even if an exception occurs:
#nbsphinx_allow_errors = True
# Controls when a cell will time out (defaults to 30; use -1 for no timeout):
#nbsphinx_timeout = 60
# Default Pygments lexer for syntax highlighting in code cells:
nbsphinx_codecell_lexer = 'ipython3'
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# Width of input/output prompts used in CSS:
#nbsphinx_prompt_width = '8ex'
# If window is narrower than this, input/output prompts are on separate lines:
#nbsphinx_responsive_width = '700px'
# -- The settings below this line are not specific to nbsphinx ------------
master_doc = 'toc-page'
linkcheck_ignore = [r'http://localhost:\d+/']
# -- Get version information from Git -------------------------------------
release = jmt.detect_release()
version = jmt.get_version(release)
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# -- Options for HTML output ----------------------------------------------
html_title = project # + ' version ' + release
# canonical url for documentation
# since sphinx 1.8
html_baseurl = 'https://jupman.softpython.org/en/latest/'
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = True
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#
html_theme_options = {
# fix for https://github.com/DavidLeoni/jupman/issues/38
'collapse_navigation': False,
# needed for big docs https://github.com/DavidLeoni/jupman/issues/77
'navigation_depth': 5
}
# NOTE: in order to have complete collapsible menu,
# IT IS *FUNDAMENTAL* FOR html_theme to be defined
# see https://github.com/DavidLeoni/jupman/issues/38
html_theme = 'sphinx_rtd_theme'
if not on_rtd:
import sphinx_rtd_theme
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static/']
#html_extra_path = []
html_js_files = [
'js/jupman.js', # shared among jupyter and ReadTheDocs
'js/pytutor-embed.bundle.min.js',
]
html_css_files = [
'css/jupman.css', # shared among jupyter and website
'css/jupman-web.css', # only on website
#'css/softpython-theme.css', #uncomment to activate
]
# -- Options for HTMLHelp output ------------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = project + 'doc'
templates_path = ['_templates']
#JUPMAN: you can use html_additional_pages for directly copying html files from _templates to the project root
# For example, it could be useful for copying Google Search Console files.
# Just put the google file in the _templates directory,
# and add the following code. Note that afterwards you would still need to
# go to readthethedocs and in Redirects section add an absolute redirect
# like /google3dea3b29336ca0e5.html -> /it/latest/google3dea3b29336ca0e5.html
# NOTE: don't put the extension on the left !
#html_additional_pages = {
# 'google3dea3b29336ca0e5': 'google3dea3b29336ca0e5.html',
#}
#'sphinxcontrib.googleanalytics'
#googleanalytics_id = os.environ.get('GOOGLE_ANALYTICS')
latex_engine='xelatex'
# allow utf8 characters
latex_elements = {
'preamble' : r'''
\usepackage{newunicodechar}
\usepackage{amsmath}
\usepackage{wasysym}
\usepackage{graphicx}
\makeatletter
% Actually APLlog is a a thin star against white circle, could't find anything better
\newunicodechar{✪}{\APLlog}
\newunicodechar{✓}{\checkmark}
''',
'maketitle': jm.latex_maketitle(html_baseurl),
}
latex_show_urls = 'footnote'
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, jm.filename + '.tex', project,
author, 'manual'),
]
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, jm.filename, project,
[author], 1)
]
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, jm.filename, project,
author, project, '',
'Miscellaneous'),
]
# -- Options for Epub output ----------------------------------------------
# Bibliographic Dublin Core info.
epub_basename = jm.filename
epub_title = project
epub_author = author
epub_publisher = author
epub_copyright = copyright
# The unique identifier of the text. This can be a ISBN number
# or the project homepage.
#
# epub_identifier = ''
# A unique identification for the text.
#
# epub_uid = ''
# A list of files that should not be packed into the epub file.
epub_exclude_files = ['search.html']
# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {'https://docs.python.org/': None}
# -- Options for PDF output --------------------------------------------------
# Grouping the document tree into PDF files. List of tuples
# (source start file, target name, title, author, options).
#
# If there is more than one author, separate them with \\.
# For example: r'Guido van Rossum\\Fred L. Drake, Jr., editor'
#
# The options element is a dictionary that lets you override
# this config per-document.
# For example,
# ('index', u'MyProject', u'My Project', u'Author Name',
# dict(pdf_compressed = True))
# would mean that specific document would be compressed
# regardless of the global pdf_compressed setting.
pdf_documents = [
('index', jm.filename, project, author.replace(",","\\"))
]
# A comma-separated list of custom stylesheets. Example:
pdf_stylesheets = ['sphinx','kerning','a4']
# A list of folders to search for stylesheets. Example:
pdf_style_path = ['.', '_styles']
# Create a compressed PDF
# Use True/False or 1/0
# Example: compressed=True
#pdf_compressed = False
# A colon-separated list of folders to search for fonts. Example:
# pdf_font_path = ['/usr/share/fonts', '/usr/share/texmf-dist/fonts/']
# Language to be used for hyphenation support
#pdf_language = "en_US"
# Mode for literal blocks wider than the frame. Can be
# overflow, shrink or truncate
#pdf_fit_mode = "shrink"
# Section level that forces a break page.
# For example: 1 means top-level sections start in a new page
# 0 means disabled
#pdf_break_level = 0
# When a section starts in a new page, force it to be 'even', 'odd',
# or just use 'any'
#pdf_breakside = 'any'
# Insert footnotes where they are defined instead of
# at the end.
#pdf_inline_footnotes = True
# verbosity level. 0 1 or 2
#pdf_verbosity = 0
# If false, no index is generated.
#pdf_use_index = True
# If false, no modindex is generated.
#pdf_use_modindex = True
# If false, no coverpage is generated.
#pdf_use_coverpage = True
# Name of the cover page template to use
#pdf_cover_template = 'sphinxcover.tmpl'
# Documents to append as an appendix to all manuals.
#pdf_appendices = []
# Enable experimental feature to split table cells. Use it
# if you get "DelayedTable too big" errors
#pdf_splittables = False
# Set the default DPI for images
#pdf_default_dpi = 72
# Enable rst2pdf extension modules (default is only vectorpdf)
# you need vectorpdf if you want to use sphinx's graphviz support
#pdf_extensions = ['vectorpdf']
# Page template name for "regular" pages
#pdf_page_template = 'cutePage'
# Show Table Of Contents at the beginning?
#pdf_use_toc = True
# How many levels deep should the table of contents be
pdf_toc_depth = 9999
# Add section number to section references
pdf_use_numbered_links = False
# Background images fitting mode
pdf_fit_background_mode = 'scale'
def setup(app):
jmt.init(jm, globals())
app.add_config_value( 'recommonmark_config', {
'auto_toc_tree_section': 'Contents',
'enable_eval_rst':True
}, True)
app.add_transform(AutoStructify)
for folder in jm.get_exercise_folders():
jm.zip_folder(folder)
jm.zip_folders('exams/*/solutions',
lambda x: '%s-%s-exam' % (jm.filename, x.split('/')[-2]))
# Build Project
def remap(x):
if x == 'requirements.txt':
return 'NAME-SURNAME-ID/requirements.txt'
elif x.startswith('project/'):
return 'NAME-SURNAME-ID/%s' % x[len('project/'):]
else:
return x
jm.zip_paths(['project', 'requirements.txt'],
'_static/generated/project-template',
remap=remap)
source_suffix = {
'.rst': 'restructuredtext',
'.txt': 'markdown',
'.md': 'markdown'
}
| [] | [] | [
"GOOGLE_ANALYTICS",
"READTHEDOCS"
] | [] | ["GOOGLE_ANALYTICS", "READTHEDOCS"] | python | 2 | 0 | |
jax/experimental/jax2tf/tests/jax_primitives_coverage_test.py | # Copyright 2020 Google LLC
#
# 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
#
# https://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.
"""Tests the primitive harness limitations.
Runs all the harnesses surfaces the errors, and detects cases when we have
too many or too few limitations.
"""
import collections
import datetime
import logging
import os
from typing import Any, Dict, Sequence, Tuple
import unittest
from absl.testing import absltest
from jax._src import test_util as jtu
from jax.config import config
import numpy as np
config.parse_flags_with_absl()
# Import after parsing flags
from jax.experimental.jax2tf.tests import primitive_harness
class JaxPrimitiveTest(jtu.JaxTestCase):
# This test runs for all primitive harnesses. For each primitive "xxx" the
# test will be called "test_jax_implemented_xxx_...". The test harnesses,
# including which dtypes are expected to fail, are defined in the
# file primitive_harness.py.
# If you want to run this test for only one harness, add parameter
# `one_containing="foo"` to parameterized below.
@primitive_harness.parameterized(primitive_harness.all_harnesses,
include_jax_unimpl=True)
@jtu.ignore_warning(category=UserWarning,
message="Using reduced precision for gradient.*")
def test_jax_implemented(self, harness: primitive_harness.Harness):
"""Runs all harnesses just with JAX to verify the jax_unimplemented field.
"""
jax_unimpl = [l for l in harness.jax_unimplemented
if l.filter(device=jtu.device_under_test(),
dtype=harness.dtype)]
if any([lim.skip_run for lim in jax_unimpl]):
logging.info(
"Skipping run with expected JAX limitations: %s in harness %s",
[u.description for u in jax_unimpl], harness.fullname)
return
try:
harness.dyn_fun(*harness.dyn_args_maker(self.rng()))
except Exception as e:
if jax_unimpl:
logging.info(
"Found expected JAX error %s with expected JAX limitations: "
"%s in harness %s",
e, [u.description for u in jax_unimpl], harness.fullname)
return
else:
raise e
if jax_unimpl:
logging.warning("Found no JAX error but expected JAX limitations: %s in "
"harness: %s",
[u.description for u in jax_unimpl], harness.fullname)
# We assert that we don't have too strict limitations. This assert can
# fail if somebody fixes a JAX or XLA limitation. In that case, you should
# find and remove the Limitation in primitive_harness. Alternatively,
# uncomment this assert and ping an OWNER of primitive_harness.
# self.assertEmpty(msg)
def test_generate_primitives_coverage_doc(self):
harnesses = primitive_harness.all_harnesses
print(f"Found {len(harnesses)} harnesses")
harness_groups: Dict[str, Sequence[primitive_harness.Harness]] = collections.defaultdict(list)
def unique_hash(h: primitive_harness.Harness, l: primitive_harness.Limitation):
return (h.group_name, l.description, l.devices,
tuple([np.dtype(d).name for d in l.dtypes]))
unique_limitations: Dict[Any, Tuple[primitive_harness.Harness,
primitive_harness.Limitation]] = {}
for h in harnesses:
harness_groups[h.group_name].append(h)
for l in h.jax_unimplemented:
if l.enabled:
unique_limitations[hash(unique_hash(h, l))] = (h, l)
primitive_coverage_table = ["""
| Primitive | Total test harnesses | dtypes supported on at least one device | dtypes NOT tested on any device |
| --- | --- | --- | --- |"""]
all_dtypes = set(jtu.dtypes.all)
for group_name in sorted(harness_groups.keys()):
hlist = harness_groups[group_name]
dtypes_tested = set() # Tested on at least some device
for h in hlist:
dtypes_tested = dtypes_tested.union({h.dtype})
primitive_coverage_table.append(
f"| {group_name} | {len(hlist)} | "
f"{primitive_harness.dtypes_to_str(dtypes_tested)} | "
f"{primitive_harness.dtypes_to_str(all_dtypes - dtypes_tested)} |")
print(f"Found {len(unique_limitations)} unique limitations")
primitive_unimpl_table = ["""
| Affected primitive | Description of limitation | Affected dtypes | Affected devices |
| --- | --- | --- | --- |"""]
for h, l in sorted(
unique_limitations.values(), key=lambda pair: unique_hash(*pair)):
devices = ", ".join(l.devices)
primitive_unimpl_table.append(
f"|{h.group_name}|{l.description}|"
f"{primitive_harness.dtypes_to_str(l.dtypes, empty_means_all=True)}|{devices}|")
if not os.environ.get("JAX_OUTPUT_LIMITATIONS_DOC"):
raise unittest.SkipTest("Set JAX_OUTPUT_LIMITATIONS_DOC=1 to enable the generation of the documentation")
# The CPU/GPU have more supported types than TPU.
self.assertEqual("cpu", jtu.device_under_test(), "The documentation can be generated only on CPU")
self.assertTrue(config.x64_enabled, "The documentation must be generated with JAX_ENABLE_X64=1")
with open(os.path.join(os.path.dirname(__file__),
'../g3doc/jax_primitives_coverage.md.template')) as f:
template = f.read()
output_file = os.path.join(os.path.dirname(__file__),
'../g3doc/jax_primitives_coverage.md')
with open(output_file, "w") as f:
f.write(template.replace("{{generation_date}}", str(datetime.date.today())) \
.replace("{{nr_harnesses}}", str(len(harnesses))) \
.replace("{{nr_primitives}}", str(len(harness_groups))) \
.replace("{{primitive_unimpl_table}}", "\n".join(primitive_unimpl_table)) \
.replace("{{primitive_coverage_table}}", "\n".join(primitive_coverage_table)))
if __name__ == "__main__":
absltest.main(testLoader=jtu.JaxTestLoader())
| [] | [] | [
"JAX_OUTPUT_LIMITATIONS_DOC"
] | [] | ["JAX_OUTPUT_LIMITATIONS_DOC"] | python | 1 | 0 | |
muses.go | package muses
import (
"fmt"
"github.com/goecology/muses/pkg/app"
"github.com/goecology/muses/pkg/common"
"github.com/goecology/muses/pkg/logger"
"github.com/goecology/muses/pkg/prom"
)
func Container(cfg interface{}, callerFuncs ...common.CallerFunc) (err error) {
var cfgByte []byte
switch cfg.(type) {
case string:
cfgByte, err = parseFile(cfg.(string))
if err != nil {
return
}
case []byte:
cfgByte = cfg.([]byte)
default:
return fmt.Errorf("type is error %s", cfg)
}
allCallers := []common.CallerFunc{app.Register, logger.Register, prom.Register}
allCallers = append(allCallers, callerFuncs...)
callers, err := sortCallers(allCallers)
if err != nil {
return
}
for _, caller := range callers {
name := getCallerName(caller)
fmt.Println("module", name, "start")
if err = caller.InitCfg(cfgByte); err != nil {
fmt.Println("module", name, "init config error")
return
}
fmt.Println("module", name, "init config ok")
if err = caller.InitCaller(); err != nil {
fmt.Println("module", name, "init caller error")
return
}
fmt.Println("module", name, "init caller ok")
fmt.Println("module", name, "end")
}
return nil
}
| [] | [] | [] | [] | [] | go | null | null | null |