├── .circleci └── config.yml ├── .gitignore ├── .travis.yml ├── Dockerfile ├── Gopkg.lock ├── Gopkg.toml ├── LICENSE.txt ├── README.md ├── build.sh ├── docs ├── flexvolume.png └── user-guide.md ├── example ├── README.md ├── cpfs-deploy.yaml ├── cpfs-pod.yaml ├── cpfs-pv.yaml ├── cpfs-pvc.yaml ├── disk-deploy.yaml ├── disk-pod.yaml ├── disk-pv.yaml ├── disk-pvc.yaml ├── flexvolume.yaml ├── nas-deploy.yaml ├── nas-pod.yaml ├── nas-pv.yaml ├── nas-pvc.yaml ├── oss-deploy.yaml ├── oss-pod.yaml ├── oss-pv.yaml ├── oss-pvc.yaml ├── pod-pvc.yaml ├── pod.yaml ├── pv.yaml └── pvc.yaml ├── main.go ├── package ├── Dockerfile ├── build.sh ├── cpfs-client-1.2.1-centos.x86_64.rpm ├── entrypoint.sh ├── kernel-devel-3.10.0-693.2.2.el7.x86_64.rpm ├── kernel-devel-3.10.0-862.14.4.el7.x86_64.rpm ├── kernel-devel-3.10.0-957.5.1.el7.x86_64.rpm ├── nsenter ├── ossfs ├── ossfs_1.80.3_centos7.0_x86_64.rpm ├── ossfs_1.80.3_ubuntu14.04_amd64.deb └── ossfs_1.80.3_ubuntu16.04_amd64.deb ├── provider ├── cpfs │ └── cpfs.go ├── disk │ ├── disk.go │ └── disk_test.go ├── driver │ ├── k8s.go │ └── swarm.go ├── monitor │ ├── fix_orphaned_pod.go │ └── monitoring.go ├── nas │ ├── nas.go │ └── nas_test.go ├── oss │ ├── oss.go │ └── oss_test.go └── utils │ ├── help.go │ └── utils.go └── vendor └── github.com ├── denverdino └── aliyungo │ ├── LICENSE.txt │ ├── common │ ├── client.go │ ├── endpoint.go │ ├── endpoints.xml │ ├── regions.go │ ├── request.go │ ├── types.go │ └── version.go │ ├── ecs │ ├── client.go │ ├── client_test.go │ ├── config_test.go │ ├── disks.go │ ├── disks_test.go │ ├── eni.go │ ├── forward_entry.go │ ├── images.go │ ├── images_test.go │ ├── instance_types.go │ ├── instance_types_test.go │ ├── instances.go │ ├── monitoring.go │ ├── monitoring_test.go │ ├── nat_gateway.go │ ├── nat_gateway_test.go │ ├── networks.go │ ├── networks_test.go │ ├── regions.go │ ├── route_tables.go │ ├── route_tables_test.go │ ├── router_interface.go │ ├── router_interface_test.go │ ├── security_groups.go │ ├── security_groups_test.go │ ├── snapshots.go │ ├── snapshots_test.go │ ├── snat_entry.go │ ├── snat_entry_test.go │ ├── ssh_key_pair.go │ ├── tags.go │ ├── tags_test.go │ ├── vpcs.go │ ├── vpcs_test.go │ ├── vrouters.go │ ├── vrouters_test.go │ ├── vswitches.go │ ├── vswitches_test.go │ └── zones.go │ ├── location │ ├── client.go │ ├── endpoints.go │ ├── regions.go │ └── services.go │ ├── metadata │ └── client.go │ ├── nas │ ├── CreateAccessRule.go │ ├── CreateFileSystem.go │ ├── CreateMountTarget.go │ ├── DescribeAccessRules.go │ ├── DescribeFileSystems.go │ ├── DescribeMountTargets.go │ └── client.go │ ├── ram │ ├── account.go │ ├── account_test.go │ ├── ak.go │ ├── ak_test.go │ ├── api.go │ ├── client.go │ ├── client_test.go │ ├── error.go │ ├── group.go │ ├── group_test.go │ ├── mfa.go │ ├── mfa_test.go │ ├── policy.go │ ├── policy_test.go │ ├── profile.go │ ├── profile_test.go │ ├── role.go │ ├── role_test.go │ ├── security.go │ ├── security_test.go │ └── types.go │ └── util │ ├── attempt.go │ ├── attempt_test.go │ ├── encoding.go │ ├── encoding_test.go │ ├── iso6801.go │ ├── iso6801_test.go │ ├── signature.go │ ├── signature_test.go │ ├── util.go │ └── util_test.go ├── nightlyone └── lockfile │ ├── README.md │ ├── lockfile.go │ ├── lockfile_unix.go │ └── lockfile_windows.go └── sirupsen └── logrus ├── LICENSE ├── README.md ├── alt_exit.go ├── doc.go ├── entry.go ├── exported.go ├── formatter.go ├── hooks.go ├── json_formatter.go ├── logger.go ├── logrus.go ├── terminal_appengine.go ├── terminal_bsd.go ├── terminal_linux.go ├── terminal_notwindows.go ├── terminal_solaris.go ├── terminal_windows.go ├── text_formatter.go └── writer.go /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | jobs: 3 | build: 4 | docker: 5 | - image: circleci/golang:1.9 6 | working_directory: /go/src/github.com/AliyunContainerService/flexvolume 7 | steps: 8 | - checkout 9 | - run: go vet ./... 10 | - run: go build 11 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # binaries 2 | flexvolume 3 | .idea 4 | flexvolume-linux 5 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | 3 | go: 4 | - 1.9.7 5 | 6 | # let us have speedy Docker-based Travis workers 7 | sudo: false 8 | install: 9 | - true 10 | script: 11 | - go build 12 | - go vet ./... 13 | - go test ./... -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM golang:1.9.7 AS build-env 2 | COPY . /go/src/github.com/AliyunContainerService/flexvolume/ 3 | RUN cd /go/src/github.com/AliyunContainerService/flexvolume/ && ./build.sh 4 | 5 | FROM alpine:3.7 6 | RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/' /etc/apk/repositories \ 7 | && apk --no-cache add fuse curl libxml2 openssl libstdc++ libgcc 8 | COPY package /acs 9 | COPY --from=build-env /go/src/github.com/AliyunContainerService/flexvolume/flexvolume-linux /acs/flexvolume 10 | 11 | RUN chmod 755 /acs/* 12 | 13 | ENTRYPOINT ["/acs/entrypoint.sh"] 14 | -------------------------------------------------------------------------------- /Gopkg.lock: -------------------------------------------------------------------------------- 1 | # This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. 2 | 3 | 4 | [[projects]] 5 | branch = "master" 6 | name = "github.com/denverdino/aliyungo" 7 | packages = ["common","ecs","metadata","nas","util"] 8 | revision = "3f1df87ed446bd21146b79ecb99ef136efec43e5" 9 | 10 | [[projects]] 11 | name = "github.com/sirupsen/logrus" 12 | packages = ["."] 13 | revision = "c155da19408a8799da419ed3eeb0cb5db0ad5dbc" 14 | version = "v1.0.5" 15 | 16 | [[projects]] 17 | branch = "master" 18 | name = "golang.org/x/crypto" 19 | packages = ["ssh/terminal"] 20 | revision = "a49355c7e3f8fe157a85be2f77e6e269a0f89602" 21 | 22 | [[projects]] 23 | branch = "master" 24 | name = "golang.org/x/sys" 25 | packages = ["unix","windows"] 26 | revision = "7138fd3d9dc8335c567ca206f4333fb75eb05d56" 27 | 28 | [solve-meta] 29 | analyzer-name = "dep" 30 | analyzer-version = 1 31 | inputs-digest = "7471977f86d836bba81599e74753a3552fa847f70678f4bfc97146c5d809392b" 32 | solver-name = "gps-cdcl" 33 | solver-version = 1 34 | -------------------------------------------------------------------------------- /Gopkg.toml: -------------------------------------------------------------------------------- 1 | 2 | # Gopkg.toml example 3 | # 4 | # Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md 5 | # for detailed Gopkg.toml documentation. 6 | # 7 | # required = ["github.com/user/thing/cmd/thing"] 8 | # ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"] 9 | # 10 | # [[constraint]] 11 | # name = "github.com/user/project" 12 | # version = "1.0.0" 13 | # 14 | # [[constraint]] 15 | # name = "github.com/user/project2" 16 | # branch = "dev" 17 | # source = "github.com/myfork/project2" 18 | # 19 | # [[override]] 20 | # name = "github.com/x/y" 21 | # version = "2.4.0" 22 | 23 | 24 | [[constraint]] 25 | branch = "master" 26 | name = "github.com/denverdino/aliyungo" 27 | 28 | [[constraint]] 29 | name = "github.com/sirupsen/logrus" 30 | version = "1.0.5" 31 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 阿里云容器服务 K8S Flexvolume 插件 2 | 3 | [![Build Status](https://travis-ci.org/AliyunContainerService/flexvolume.svg?branch=master)](https://travis-ci.org/AliyunContainerService/flexvolume) [![CircleCI](https://circleci.com/gh/AliyunContainerService/flexvolume.svg?style=svg)](https://circleci.com/gh/AliyunContainerService/flexvolume) [![Go Report Card](https://goreportcard.com/badge/github.com/AliyunContainerService/flexvolume)](https://goreportcard.com/report/github.com/AliyunContainerService/flexvolume) 4 | 5 | 针对阿里云云盘、NAS、OSS存储开发的flexvolume 插件,可以支持kubernetes pod 自动绑定阿里云存储服务。 6 | 7 | 此版本支持Flexvolume, 静态pv. 对于动态pv尚不支持. 8 | 9 | ## 部署框架 10 | ![系统框架图](docs/flexvolume.png) 11 | 12 | ## 安装使用该插件: 13 | 14 | 15 | 通过下面yaml配置进行部署阿里云K8S存储插件,目前支持CentOS 7 操作系统; 16 | 17 | **注意:** 18 | > 1. 使用oss数据卷服务时必须配置Secret,如果只使用nas、云盘,则可以不配置Secret; 19 | > 2. 使用flexvolume需要kubelet关闭`--enable-controller-attach-detach`选项。默认阿里云K8S集群已经关闭此选项; 20 | > 3. 在kube-system用户空间部署flexvolume; 21 | 22 | 23 | ``` 24 | apiVersion: apps/v1 # for versions before 1.8.0 use extensions/v1beta1 25 | kind: DaemonSet 26 | metadata: 27 | name: flexvolume 28 | namespace: kube-system 29 | labels: 30 | k8s-volume: flexvolume 31 | spec: 32 | selector: 33 | matchLabels: 34 | name: acs-flexvolume 35 | template: 36 | metadata: 37 | labels: 38 | name: acs-flexvolume 39 | spec: 40 | hostPID: true 41 | hostNetwork: true 42 | tolerations: 43 | - key: node-role.kubernetes.io/master 44 | operator: Exists 45 | effect: NoSchedule 46 | containers: 47 | - name: acs-flexvolume 48 | image: flexvolume:*** 49 | imagePullPolicy: Always 50 | securityContext: 51 | privileged: true 52 | env: 53 | - name: ACS_DISK 54 | value: "true" 55 | - name: ACS_NAS 56 | value: "true" 57 | - name: ACS_OSS 58 | value: "true" 59 | - name: ACCESS_KEY_ID 60 | value: "" 61 | - name: ACCESS_KEY_SECRET 62 | value: "" 63 | - name: SLB_ENDPOINT 64 | value: "" 65 | - name: ECS_ENDPOINT 66 | value: "" 67 | resources: 68 | limits: 69 | memory: 200Mi 70 | requests: 71 | cpu: 100m 72 | memory: 200Mi 73 | volumeMounts: 74 | - name: usrdir 75 | mountPath: /host/usr/ 76 | - name: etcdir 77 | mountPath: /host/etc/ 78 | - name: logdir 79 | mountPath: /var/log/alicloud/ 80 | volumes: 81 | - name: usrdir 82 | hostPath: 83 | path: /usr/ 84 | - name: etcdir 85 | hostPath: 86 | path: /etc/ 87 | - name: logdir 88 | hostPath: 89 | path: /var/log/alicloud/ 90 | updateStrategy: 91 | type: RollingUpdate 92 | ``` 93 | 94 | 95 | ## ROADMAP 96 | 97 | -------------------------------------------------------------------------------- /build.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -e 3 | 4 | cd ${GOPATH}/src/github.com/AliyunContainerService/flexvolume/ 5 | GIT_SHA=`git rev-parse --short HEAD || echo "HEAD"` 6 | 7 | 8 | export GOARCH="amd64" 9 | export GOOS="linux" 10 | if [[ "$(uname -s)" == "Linux" ]];then 11 | CGO_ENABLED=1 go build -tags 'netgo' --ldflags '-extldflags "-static"' -o flexvolume-linux 12 | else 13 | CGO_ENABLED=0 go build -o flexvolume-linux 14 | fi 15 | 16 | -------------------------------------------------------------------------------- /docs/flexvolume.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AliyunContainerService/flexvolume/4f17fb650f32666d6287d247a0f134e8ab0aea12/docs/flexvolume.png -------------------------------------------------------------------------------- /example/README.md: -------------------------------------------------------------------------------- 1 | ## 使用说明 2 | 3 | - 配置文件中的volumename和pvname要和阿里云盘id保持一致 4 | -------------------------------------------------------------------------------- /example/cpfs-deploy.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: extensions/v1beta1 2 | kind: Deployment 3 | metadata: 4 | name: nginx-nas-deploy 5 | spec: 6 | replicas: 2 7 | template: 8 | metadata: 9 | labels: 10 | app: nginx 11 | spec: 12 | containers: 13 | - name: nginx-flexvolume-cpfs 14 | image: nginx 15 | volumeMounts: 16 | - name: "cpfs1" 17 | mountPath: "/data" 18 | volumes: 19 | - name: "cpfs1" 20 | flexVolume: 21 | driver: "alicloud/cpfs" 22 | options: 23 | server: "192.168.0.1@tcp" 24 | fileSystem: "cpfs" -------------------------------------------------------------------------------- /example/cpfs-pod.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Pod 3 | metadata: 4 | name: "flexvolume-cpfs-example" 5 | spec: 6 | containers: 7 | - name: "nginx" 8 | image: "nginx" 9 | volumeMounts: 10 | - name: pvc-cpfs 11 | mountPath: "/data" 12 | volumes: 13 | - name: pvc-cpfs 14 | persistentVolumeClaim: 15 | claimName: pvc-cpfs 16 | -------------------------------------------------------------------------------- /example/cpfs-pv.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: PersistentVolume 3 | metadata: 4 | name: pv-cpfs 5 | spec: 6 | capacity: 7 | storage: 5Gi 8 | accessModes: 9 | - ReadWriteMany 10 | flexVolume: 11 | driver: "alicloud/cpfs" 12 | options: 13 | server: "192.168.0.1@tcp" 14 | fileSystem: "cpfs" 15 | -------------------------------------------------------------------------------- /example/cpfs-pvc.yaml: -------------------------------------------------------------------------------- 1 | kind: PersistentVolumeClaim 2 | apiVersion: v1 3 | metadata: 4 | name: pvc-cpfs 5 | spec: 6 | accessModes: 7 | - ReadWriteMany 8 | resources: 9 | requests: 10 | storage: 5Gi 11 | -------------------------------------------------------------------------------- /example/disk-deploy.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: extensions/v1beta1 2 | kind: Deployment 3 | metadata: 4 | name: nginx-disk-deploy 5 | spec: 6 | replicas: 1 7 | template: 8 | metadata: 9 | labels: 10 | app: nginx 11 | spec: 12 | containers: 13 | - name: nginx-flexvolume-disk 14 | image: nginx 15 | volumeMounts: 16 | - name: "d-bp1j17ifxfasvts3tf40" 17 | mountPath: "/data" 18 | volumes: 19 | - name: "d-bp1j17ifxfasvts3tf40" 20 | flexVolume: 21 | driver: "alicloud/disk" 22 | fsType: "ext4" 23 | options: 24 | volumeId: "d-bp1j17ifxfasvts3tf40" -------------------------------------------------------------------------------- /example/disk-pod.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Pod 3 | metadata: 4 | name: "flexvolume-alicloud-example" 5 | spec: 6 | containers: 7 | - name: "nginx" 8 | image: "nginx" 9 | volumeMounts: 10 | - name: pvc-disk 11 | mountPath: "/data" 12 | volumes: 13 | - name: pvc-disk 14 | persistentVolumeClaim: 15 | claimName: pvc-disk 16 | -------------------------------------------------------------------------------- /example/disk-pv.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: PersistentVolume 3 | metadata: 4 | name: d-bp1j17ifxfasvts3tf40 5 | spec: 6 | capacity: 7 | storage: 20Gi 8 | accessModes: 9 | - ReadWriteOnce 10 | flexVolume: 11 | driver: "alicloud/disk" 12 | fsType: "ext4" 13 | options: 14 | volumeId: "d-bp1j17ifxfasvts3tf40" 15 | -------------------------------------------------------------------------------- /example/disk-pvc.yaml: -------------------------------------------------------------------------------- 1 | kind: PersistentVolumeClaim 2 | apiVersion: v1 3 | metadata: 4 | name: pvc-disk 5 | spec: 6 | accessModes: 7 | - ReadWriteOnce 8 | resources: 9 | requests: 10 | storage: 20Gi -------------------------------------------------------------------------------- /example/flexvolume.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 # for versions before 1.8.0 use extensions/v1beta1 2 | kind: DaemonSet 3 | metadata: 4 | name: flexvolume 5 | namespace: kube-system 6 | labels: 7 | k8s-volume: flexvolume 8 | spec: 9 | selector: 10 | matchLabels: 11 | name: acs-flexvolume 12 | template: 13 | metadata: 14 | labels: 15 | name: acs-flexvolume 16 | spec: 17 | hostPID: true 18 | hostNetwork: true 19 | tolerations: 20 | - key: node-role.kubernetes.io/master 21 | operator: Exists 22 | effect: NoSchedule 23 | containers: 24 | - name: acs-flexvolume 25 | image: flexvolume:*** 26 | imagePullPolicy: Always 27 | securityContext: 28 | privileged: true 29 | env: 30 | - name: ACS_DISK 31 | value: "true" 32 | - name: ACS_NAS 33 | value: "true" 34 | - name: ACS_OSS 35 | value: "true" 36 | - name: ACCESS_KEY_ID 37 | value: "" 38 | - name: ACCESS_KEY_SECRET 39 | value: "" 40 | - name: SLB_ENDPOINT 41 | value: "" 42 | - name: ECS_ENDPOINT 43 | value: "" 44 | resources: 45 | limits: 46 | memory: 200Mi 47 | requests: 48 | cpu: 100m 49 | memory: 200Mi 50 | volumeMounts: 51 | - name: usrdir 52 | mountPath: /host/usr/ 53 | - name: etcdir 54 | mountPath: /host/etc/ 55 | - name: logdir 56 | mountPath: /var/log/alicloud/ 57 | volumes: 58 | - name: usrdir 59 | hostPath: 60 | path: /usr/ 61 | - name: etcdir 62 | hostPath: 63 | path: /etc/ 64 | - name: logdir 65 | hostPath: 66 | path: /var/log/alicloud/ 67 | updateStrategy: 68 | type: RollingUpdate 69 | -------------------------------------------------------------------------------- /example/nas-deploy.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: extensions/v1beta1 2 | kind: Deployment 3 | metadata: 4 | name: nginx-nas-deploy 5 | spec: 6 | replicas: 1 7 | template: 8 | metadata: 9 | labels: 10 | app: nginx 11 | spec: 12 | containers: 13 | - name: nginx-flexvolume-nas 14 | image: nginx 15 | volumeMounts: 16 | - name: "nas1" 17 | mountPath: "/data" 18 | volumes: 19 | - name: "nas1" 20 | flexVolume: 21 | driver: "alicloud/nas" 22 | options: 23 | server: "*-uih75.cn-hangzhou.nas.aliyuncs.com" 24 | path: "/k8s" 25 | vers: "4.0" 26 | -------------------------------------------------------------------------------- /example/nas-pod.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Pod 3 | metadata: 4 | name: "flexvolume-nas-example" 5 | spec: 6 | containers: 7 | - name: "nginx" 8 | image: "nginx" 9 | volumeMounts: 10 | - name: pvc-nas 11 | mountPath: "/data" 12 | volumes: 13 | - name: pvc-nas 14 | persistentVolumeClaim: 15 | claimName: pvc-nas 16 | -------------------------------------------------------------------------------- /example/nas-pv.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: PersistentVolume 3 | metadata: 4 | name: pv-nas 5 | spec: 6 | capacity: 7 | storage: 5Gi 8 | accessModes: 9 | - ReadWriteMany 10 | flexVolume: 11 | driver: "alicloud/nas" 12 | options: 13 | server: "**-uih75.cn-hangzhou.nas.aliyuncs.com" 14 | path: "/k8s" 15 | vers: "4.0" 16 | -------------------------------------------------------------------------------- /example/nas-pvc.yaml: -------------------------------------------------------------------------------- 1 | kind: PersistentVolumeClaim 2 | apiVersion: v1 3 | metadata: 4 | name: pvc-nas 5 | spec: 6 | accessModes: 7 | - ReadWriteMany 8 | resources: 9 | requests: 10 | storage: 5Gi 11 | -------------------------------------------------------------------------------- /example/oss-deploy.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: extensions/v1beta1 2 | kind: Deployment 3 | metadata: 4 | name: nginx-oss-deploy 5 | spec: 6 | replicas: 1 7 | template: 8 | metadata: 9 | labels: 10 | app: nginx 11 | spec: 12 | containers: 13 | - name: nginx-flexvolume-oss 14 | image: nginx 15 | volumeMounts: 16 | - name: "oss1" 17 | mountPath: "/data" 18 | volumes: 19 | - name: "oss1" 20 | flexVolume: 21 | driver: "alicloud/oss" 22 | options: 23 | bucket: "sigma-python" 24 | url: "oss-cn-hangzhou.aliyuncs.com" 25 | otherOpts: "-o max_stat_cache_size=0 -o allow_other" 26 | akId: "" 27 | akSecret: "" 28 | -------------------------------------------------------------------------------- /example/oss-pod.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Pod 3 | metadata: 4 | name: "flexvolume-oss-example" 5 | spec: 6 | containers: 7 | - name: "nginx" 8 | image: "nginx" 9 | volumeMounts: 10 | - name: pvc-oss 11 | mountPath: "/data" 12 | volumes: 13 | - name: pvc-oss 14 | persistentVolumeClaim: 15 | claimName: pvc-oss -------------------------------------------------------------------------------- /example/oss-pv.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: PersistentVolume 3 | metadata: 4 | name: pv-oss 5 | spec: 6 | capacity: 7 | storage: 5Gi 8 | accessModes: 9 | - ReadWriteMany 10 | flexVolume: 11 | driver: "alicloud/oss" 12 | options: 13 | bucket: "sigma-python" 14 | url: "oss-cn-hangzhou.aliyuncs.com" 15 | otherOpts: "-o max_stat_cache_size=0 -o allow_other" 16 | akId: "" 17 | akSecret: "" 18 | -------------------------------------------------------------------------------- /example/oss-pvc.yaml: -------------------------------------------------------------------------------- 1 | kind: PersistentVolumeClaim 2 | apiVersion: v1 3 | metadata: 4 | name: pvc-oss 5 | spec: 6 | accessModes: 7 | - ReadWriteMany 8 | resources: 9 | requests: 10 | storage: 5Gi 11 | -------------------------------------------------------------------------------- /example/pod-pvc.yaml: -------------------------------------------------------------------------------- 1 | kind: Pod 2 | apiVersion: v1 3 | metadata: 4 | name: pod-nginx-flexvolume-alicloud-pv 5 | spec: 6 | volumes: 7 | - name: task-pv-storage 8 | persistentVolumeClaim: 9 | claimName: pv-claim 10 | 11 | containers: 12 | - name: task-pv-container 13 | image: nginx 14 | volumeMounts: 15 | - mountPath: "/var/lib" 16 | name: task-pv-storage 17 | -------------------------------------------------------------------------------- /example/pod.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Pod 3 | metadata: 4 | name: "flexvolume-alicloud-example" 5 | spec: 6 | containers: 7 | - name: "nginx" 8 | image: "nginx" 9 | volumeMounts: 10 | - name: "d-bp1au6l6mbscl64apz0n" 11 | mountPath: "/var/lib" 12 | volumes: 13 | - name: "d-bp1au6l6mbscl64apz0n" 14 | flexVolume: 15 | driver: "alicloud/disk" 16 | fsType: "ext4" 17 | options: 18 | volumeId: "d-bp1au6l6mbscl64apz0n" 19 | -------------------------------------------------------------------------------- /example/pv.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: PersistentVolume 3 | metadata: 4 | name: d-bp1au6l6mbscl64apz0n 5 | spec: 6 | capacity: 7 | storage: 20Gi 8 | accessModes: 9 | - ReadWriteOnce 10 | storageClassName: slow 11 | flexVolume: 12 | driver: "alicloud/disk" 13 | fsType: "ext4" 14 | options: 15 | volumeId: "d-bp1au6l6mbscl64apz0n" 16 | -------------------------------------------------------------------------------- /example/pvc.yaml: -------------------------------------------------------------------------------- 1 | kind: PersistentVolumeClaim 2 | apiVersion: v1 3 | metadata: 4 | name: pv-claim 5 | spec: 6 | storageClassName: slow 7 | accessModes: 8 | - ReadWriteOnce 9 | resources: 10 | requests: 11 | storage: 20Gi 12 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | driver "github.com/AliyunContainerService/flexvolume/provider/driver" 6 | utils "github.com/AliyunContainerService/flexvolume/provider/utils" 7 | "os" 8 | "strings" 9 | ) 10 | 11 | // Expect to support K8s and Swarm platform 12 | // Under K8s, plugin will run in cli mode, process running and exit after the actions. 13 | // Under swarm, plugin will be running always, and communicate with docker by socket. 14 | func main() { 15 | 16 | // get the environment of platform 17 | platform := os.Getenv("ACS_PLATFORM") 18 | if platform == "swarm" { 19 | driver.RunningInSwarm() 20 | } else { 21 | driver.RunK8sAction() 22 | } 23 | } 24 | 25 | // check running environment and print help 26 | func init() { 27 | if len(os.Args) == 1 { 28 | utils.Usage() 29 | os.Exit(0) 30 | } 31 | 32 | argsOne := strings.ToLower(os.Args[1]) 33 | if argsOne == "--version" || argsOne == "version" || argsOne == "-v" { 34 | fmt.Printf(utils.PluginVersion()) 35 | os.Exit(0) 36 | } 37 | 38 | if argsOne == "--help" || argsOne == "help" || argsOne == "-h" { 39 | utils.Usage() 40 | os.Exit(0) 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /package/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM registry.aliyuncs.com/acs/alpine:3.3 2 | RUN apk add --update curl && rm -rf /var/cache/apk/* 3 | RUN apk --update add fuse curl libxml2 openssl libstdc++ libgcc && rm -rf /var/cache/apk/* 4 | 5 | RUN mkdir -p /acs 6 | COPY nsenter /acs/nsenter 7 | COPY bin/flexvolume /acs/flexvolume 8 | COPY entrypoint.sh /acs/entrypoint.sh 9 | COPY ossfs_1.80.3_centos7.0_x86_64.rpm /acs/ossfs_1.80.3_centos7.0_x86_64.rpm 10 | COPY ossfs_1.80.3_ubuntu14.04_amd64.deb /acs/ossfs_1.80.3_ubuntu14.04_amd64.deb 11 | COPY ossfs_1.80.3_ubuntu16.04_amd64.deb /acs/ossfs_1.80.3_ubuntu16.04_amd64.deb 12 | COPY cpfs-client-1.2.1-centos.x86_64.rpm /acs/cpfs-client-1.2.1-centos.x86_64.rpm 13 | COPY kernel-devel-3.10.0-693.2.2.el7.x86_64.rpm /acs/kernel-devel-3.10.0-693.2.2.el7.x86_64.rpm 14 | COPY kernel-devel-3.10.0-862.14.4.el7.x86_64.rpm /acs/kernel-devel-3.10.0-862.14.4.el7.x86_64.rpm 15 | COPY kernel-devel-3.10.0-957.5.1.el7.x86_64.rpm /acs/kernel-devel-3.10.0-957.5.1.el7.x86_64.rpm 16 | 17 | RUN chmod 755 /acs/* 18 | 19 | ENTRYPOINT ["/acs/entrypoint.sh"] 20 | -------------------------------------------------------------------------------- /package/build.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -e 3 | 4 | cd flexvolume/ 5 | GIT_SHA=`git rev-parse --short HEAD || echo "HEAD"` 6 | 7 | 8 | export GOARCH="amd64" 9 | export GOOS="linux" 10 | if [[ "$(uname -s)" == "Linux" ]];then 11 | CGO_ENABLED=1 go build -tags 'netgo' --ldflags '-extldflags "-static"' -o flexvolume-linux 12 | else 13 | CGO_ENABLED=0 go build -o flexvolume-linux 14 | fi 15 | 16 | mkdir -p package/bin 17 | mv flexvolume-linux package/bin/flexvolume 18 | 19 | 20 | docker build -t=flexvolume:version ./ 21 | -------------------------------------------------------------------------------- /package/cpfs-client-1.2.1-centos.x86_64.rpm: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AliyunContainerService/flexvolume/4f17fb650f32666d6287d247a0f134e8ab0aea12/package/cpfs-client-1.2.1-centos.x86_64.rpm -------------------------------------------------------------------------------- /package/kernel-devel-3.10.0-693.2.2.el7.x86_64.rpm: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AliyunContainerService/flexvolume/4f17fb650f32666d6287d247a0f134e8ab0aea12/package/kernel-devel-3.10.0-693.2.2.el7.x86_64.rpm -------------------------------------------------------------------------------- /package/kernel-devel-3.10.0-862.14.4.el7.x86_64.rpm: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AliyunContainerService/flexvolume/4f17fb650f32666d6287d247a0f134e8ab0aea12/package/kernel-devel-3.10.0-862.14.4.el7.x86_64.rpm -------------------------------------------------------------------------------- /package/kernel-devel-3.10.0-957.5.1.el7.x86_64.rpm: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AliyunContainerService/flexvolume/4f17fb650f32666d6287d247a0f134e8ab0aea12/package/kernel-devel-3.10.0-957.5.1.el7.x86_64.rpm -------------------------------------------------------------------------------- /package/nsenter: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AliyunContainerService/flexvolume/4f17fb650f32666d6287d247a0f134e8ab0aea12/package/nsenter -------------------------------------------------------------------------------- /package/ossfs: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AliyunContainerService/flexvolume/4f17fb650f32666d6287d247a0f134e8ab0aea12/package/ossfs -------------------------------------------------------------------------------- /package/ossfs_1.80.3_centos7.0_x86_64.rpm: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AliyunContainerService/flexvolume/4f17fb650f32666d6287d247a0f134e8ab0aea12/package/ossfs_1.80.3_centos7.0_x86_64.rpm -------------------------------------------------------------------------------- /package/ossfs_1.80.3_ubuntu14.04_amd64.deb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AliyunContainerService/flexvolume/4f17fb650f32666d6287d247a0f134e8ab0aea12/package/ossfs_1.80.3_ubuntu14.04_amd64.deb -------------------------------------------------------------------------------- /package/ossfs_1.80.3_ubuntu16.04_amd64.deb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AliyunContainerService/flexvolume/4f17fb650f32666d6287d247a0f134e8ab0aea12/package/ossfs_1.80.3_ubuntu16.04_amd64.deb -------------------------------------------------------------------------------- /provider/disk/disk_test.go: -------------------------------------------------------------------------------- 1 | package disk 2 | 3 | import "testing" 4 | 5 | func TestGetDevicePath(t *testing.T) { 6 | 7 | before := []string{} 8 | after := []string{} 9 | before = append(before, "/dev/vdb", "/dev/vdc") 10 | after = append(after, "/dev/vdb", "/dev/vdc", "/dev/vdd") 11 | devices := getDevicePath(before, after) 12 | t.Log(devices) 13 | } 14 | -------------------------------------------------------------------------------- /provider/driver/swarm.go: -------------------------------------------------------------------------------- 1 | package driver 2 | 3 | // RunningInSwarm expect to support running on swarm 4 | func RunningInSwarm() { 5 | 6 | } 7 | -------------------------------------------------------------------------------- /provider/monitor/monitoring.go: -------------------------------------------------------------------------------- 1 | package monitor 2 | 3 | import ( 4 | "fmt" 5 | "io/ioutil" 6 | "os" 7 | "strings" 8 | "time" 9 | 10 | "github.com/AliyunContainerService/flexvolume/provider/utils" 11 | log "github.com/sirupsen/logrus" 12 | ) 13 | 14 | // const values for monitoring 15 | const ( 16 | NSENTER_CMD = "/acs/nsenter --mount=/proc/1/ns/mnt " 17 | DISK_BIN = "/usr/libexec/kubernetes/kubelet-plugins/volume/exec/alicloud~disk/disk" 18 | OSS_BIN = "/usr/libexec/kubernetes/kubelet-plugins/volume/exec/alicloud~oss/oss" 19 | NAS_BIN = "/usr/libexec/kubernetes/kubelet-plugins/volume/exec/alicloud~nas/nas" 20 | 21 | FLEXVOLUME_CONFIG_FILE = "/host/etc/kubernetes/flexvolume.conf" 22 | HOST_SYS_LOG = "/host/var/log/messages" 23 | DEFAULT_SLEEP_SECOND = 60 24 | ) 25 | 26 | // configs for orphan pod issue 27 | var globalFixOrphanedPod = false 28 | var hostFixOrphanedPod = "no_set" 29 | 30 | // Monitoring running for plugin status check 31 | func Monitoring() { 32 | // Parse fix_orphaned pod global env 33 | processFixIssues := strings.ToLower(os.Getenv("FIX_ISSUES")) 34 | 35 | // check global config for issues; 36 | fixIssuesList := strings.Split(processFixIssues, ",") 37 | for _, fixIssue := range fixIssuesList { 38 | fixIssue = strings.ToLower(fixIssue) 39 | if fixIssue == "fix_orphaned_pod" { 40 | globalFixOrphanedPod = true 41 | } 42 | } 43 | 44 | // parse host flexvolume config 45 | go parseFlexvolumeHostConfig() 46 | 47 | // fix orphan pod with umounted path; github issue: https://github.com/kubernetes/kubernetes/issues/60987 48 | go fixIssueOrphanPod() 49 | 50 | // monitoring in loop 51 | for { 52 | version := utils.PluginVersion() 53 | // check Disk plugin status 54 | if os.Getenv("ACS_DISK") == "true" { 55 | mntCmd := fmt.Sprintf("%s %s --version", NSENTER_CMD, DISK_BIN) 56 | if out, err := utils.Run(mntCmd); err != nil { 57 | log.Printf("Warning, Monitoring disk error: %s", err.Error()) 58 | } else if out != version { 59 | log.Printf("Warning, the disk plugin version is not right, running: %s, expect: %s", out, version) 60 | } 61 | } 62 | 63 | if os.Getenv("ACS_NAS") == "true" { 64 | mntCmd := fmt.Sprintf("%s %s --version", NSENTER_CMD, NAS_BIN) 65 | if out, err := utils.Run(mntCmd); err != nil { 66 | log.Printf("Warning, Monitoring nas error: %s", err.Error()) 67 | } else if out != version { 68 | log.Printf("Warning, the nas plugin version is not right, running: %s, expect: %s", out, version) 69 | } 70 | } 71 | 72 | if os.Getenv("ACS_OSS") == "true" { 73 | mntCmd := fmt.Sprintf("%s %s --version", NSENTER_CMD, OSS_BIN) 74 | if out, err := utils.Run(mntCmd); err != nil { 75 | log.Printf("Warning, Monitoring oss error: %s", err.Error()) 76 | } else if out != version { 77 | log.Printf("Warning, the Oss plugin version is not right, running: %s, expect: %s", out, version) 78 | } 79 | } 80 | 81 | time.Sleep(DEFAULT_SLEEP_SECOND * time.Second) 82 | } 83 | } 84 | 85 | // parse flexvolume global config 86 | func parseFlexvolumeHostConfig() { 87 | for { 88 | if utils.IsFileExisting(FLEXVOLUME_CONFIG_FILE) { 89 | raw, err := ioutil.ReadFile(FLEXVOLUME_CONFIG_FILE) 90 | if err != nil { 91 | log.Errorf("Read flexvolume config file error: %s", err.Error()) 92 | continue 93 | } 94 | lines := strings.Split(string(raw), "\n") 95 | setFlag := false 96 | for _, line := range lines { 97 | lowLine := strings.ToLower(line) 98 | 99 | // Parse fix_orphaned_pod config 100 | if strings.Contains(lowLine, "fix_orphaned_pod:") && strings.Contains(lowLine, "true") { 101 | hostFixOrphanedPod = "true" 102 | setFlag = true 103 | break 104 | } else if strings.Contains(lowLine, "fix_orphaned_pod:") && strings.Contains(lowLine, "false") { 105 | hostFixOrphanedPod = "false" 106 | setFlag = true 107 | break 108 | } 109 | } 110 | if !setFlag { 111 | hostFixOrphanedPod = "no_set" 112 | } 113 | } else { 114 | hostFixOrphanedPod = "no_set" 115 | } 116 | 117 | SLEEP_SECOND := DEFAULT_SLEEP_SECOND 118 | time.Sleep(time.Duration(SLEEP_SECOND) * time.Second) 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /provider/nas/nas_test.go: -------------------------------------------------------------------------------- 1 | package nas 2 | 3 | import "testing" 4 | 5 | func TestCheckOptions(t *testing.T) { 6 | plugin := &NasPlugin{} 7 | optin := &NasOptions{Server: "", Path: "/k8s", Vers: "4.0", Mode: "755"} 8 | plugin.checkOptions(optin) 9 | } 10 | -------------------------------------------------------------------------------- /provider/oss/oss_test.go: -------------------------------------------------------------------------------- 1 | package oss 2 | 3 | import "testing" 4 | 5 | func TestCheckOptions(t *testing.T) { 6 | plugin := &OssPlugin{} 7 | optin := &OssOptions{Bucket: "aliyun", Url: "oss-cn-hangzhou.aliyuncs.com", OtherOpts: "-o max_stat_cache_size=0 -o allow_other", AkId: "1223455", AkSecret: "22334567"} 8 | plugin.checkOptions(optin) 9 | } 10 | -------------------------------------------------------------------------------- /provider/utils/help.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import "fmt" 4 | 5 | var ( 6 | // VERSION should be updated by hand at each release 7 | VERSION = "v1.12.6" 8 | 9 | // GITCOMMIT will be overwritten automatically by the build system 10 | GITCOMMIT = "HEAD" 11 | ) 12 | 13 | // PluginVersion 14 | func PluginVersion() string { 15 | return VERSION 16 | } 17 | 18 | // Usage help 19 | func Usage() { 20 | fmt.Printf("In K8s Mode: " + 21 | "Use binary file as the first parameter, and format support:\n" + 22 | " plugin init: \n" + 23 | " plugin attach: for alicloud disk plugin\n" + 24 | " plugin detach: for alicloud disk plugin\n" + 25 | " plugin mount: for nas, oss plugin\n" + 26 | " plugin umount: for nas, oss plugin\n\n" + 27 | "You can refer to K8s flexvolume docs: \n") 28 | } 29 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/common/endpoint.go: -------------------------------------------------------------------------------- 1 | package common 2 | 3 | import ( 4 | "encoding/xml" 5 | "fmt" 6 | "io/ioutil" 7 | "os" 8 | "strings" 9 | ) 10 | 11 | const ( 12 | // LocationDefaultEndpoint is the default API endpoint of Location services 13 | locationDefaultEndpoint = "https://location.aliyuncs.com" 14 | locationAPIVersion = "2015-06-12" 15 | HTTP_PROTOCOL = "http" 16 | HTTPS_PROTOCOL = "https" 17 | ) 18 | 19 | var ( 20 | endpoints = make(map[Region]map[string]string) 21 | ) 22 | 23 | //init endpoints from file 24 | func init() { 25 | 26 | } 27 | 28 | func NewLocationClient(accessKeyId, accessKeySecret string) *Client { 29 | endpoint := os.Getenv("LOCATION_ENDPOINT") 30 | if endpoint == "" { 31 | endpoint = locationDefaultEndpoint 32 | } 33 | 34 | client := &Client{} 35 | client.Init(endpoint, locationAPIVersion, accessKeyId, accessKeySecret) 36 | return client 37 | } 38 | 39 | func (client *Client) DescribeEndpoint(args *DescribeEndpointArgs) (*DescribeEndpointResponse, error) { 40 | response := &DescribeEndpointResponse{} 41 | err := client.Invoke("DescribeEndpoint", args, response) 42 | if err != nil { 43 | return nil, err 44 | } 45 | return response, err 46 | } 47 | 48 | func getProductRegionEndpoint(region Region, serviceCode string) string { 49 | if sp, ok := endpoints[region]; ok { 50 | if endpoint, ok := sp[serviceCode]; ok { 51 | return endpoint 52 | } 53 | } 54 | 55 | return "" 56 | } 57 | 58 | func setProductRegionEndpoint(region Region, serviceCode string, endpoint string) { 59 | endpoints[region] = map[string]string{ 60 | serviceCode: endpoint, 61 | } 62 | } 63 | 64 | func (client *Client) DescribeOpenAPIEndpoint(region Region, serviceCode string) string { 65 | if endpoint := getProductRegionEndpoint(region, serviceCode); endpoint != "" { 66 | return endpoint 67 | } 68 | 69 | defaultProtocols := HTTP_PROTOCOL 70 | 71 | args := &DescribeEndpointArgs{ 72 | Id: region, 73 | ServiceCode: serviceCode, 74 | Type: "openAPI", 75 | } 76 | 77 | endpoint, err := client.DescribeEndpoint(args) 78 | if err != nil || endpoint.Endpoint == "" { 79 | return "" 80 | } 81 | 82 | for _, protocol := range endpoint.Protocols.Protocols { 83 | if strings.ToLower(protocol) == HTTPS_PROTOCOL { 84 | defaultProtocols = HTTPS_PROTOCOL 85 | break 86 | } 87 | } 88 | 89 | ep := fmt.Sprintf("%s://%s", defaultProtocols, endpoint.Endpoint) 90 | 91 | setProductRegionEndpoint(region, serviceCode, ep) 92 | return ep 93 | } 94 | 95 | func loadEndpointFromFile(region Region, serviceCode string) string { 96 | data, err := ioutil.ReadFile("./endpoints.xml") 97 | if err != nil { 98 | return "" 99 | } 100 | 101 | var endpoints Endpoints 102 | err = xml.Unmarshal(data, &endpoints) 103 | if err != nil { 104 | return "" 105 | } 106 | 107 | for _, endpoint := range endpoints.Endpoint { 108 | if endpoint.RegionIds.RegionId == string(region) { 109 | for _, product := range endpoint.Products.Product { 110 | if strings.ToLower(product.ProductName) == serviceCode { 111 | return fmt.Sprintf("%s://%s", HTTPS_PROTOCOL, product.DomainName) 112 | } 113 | } 114 | } 115 | } 116 | 117 | return "" 118 | } 119 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/common/regions.go: -------------------------------------------------------------------------------- 1 | package common 2 | 3 | // Region represents ECS region 4 | type Region string 5 | 6 | // Constants of region definition 7 | const ( 8 | Hangzhou = Region("cn-hangzhou") 9 | Qingdao = Region("cn-qingdao") 10 | Beijing = Region("cn-beijing") 11 | Hongkong = Region("cn-hongkong") 12 | Shenzhen = Region("cn-shenzhen") 13 | Shanghai = Region("cn-shanghai") 14 | Zhangjiakou = Region("cn-zhangjiakou") 15 | 16 | APSouthEast1 = Region("ap-southeast-1") 17 | APNorthEast1 = Region("ap-northeast-1") 18 | APSouthEast2 = Region("ap-southeast-2") 19 | APSouthEast3 = Region("ap-southeast-3") 20 | 21 | USWest1 = Region("us-west-1") 22 | USEast1 = Region("us-east-1") 23 | 24 | MEEast1 = Region("me-east-1") 25 | 26 | EUCentral1 = Region("eu-central-1") 27 | 28 | ShenZhenFinance = Region("cn-shenzhen-finance-1") 29 | ShanghaiFinance = Region("cn-shanghai-finance-1") 30 | ) 31 | 32 | var ValidRegions = []Region{ 33 | Hangzhou, Qingdao, Beijing, Shenzhen, Hongkong, Shanghai, Zhangjiakou, 34 | USWest1, USEast1, 35 | APNorthEast1, APSouthEast1, APSouthEast2, APSouthEast3, 36 | MEEast1, 37 | EUCentral1, 38 | ShenZhenFinance, ShanghaiFinance, 39 | } 40 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/common/request.go: -------------------------------------------------------------------------------- 1 | package common 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "time" 7 | 8 | "github.com/denverdino/aliyungo/util" 9 | ) 10 | 11 | // Constants for Aliyun API requests 12 | const ( 13 | SignatureVersion = "1.0" 14 | SignatureMethod = "HMAC-SHA1" 15 | JSONResponseFormat = "JSON" 16 | XMLResponseFormat = "XML" 17 | ECSRequestMethod = "GET" 18 | ) 19 | 20 | type Request struct { 21 | Format string 22 | Version string 23 | RegionId Region 24 | AccessKeyId string 25 | SecurityToken string 26 | Signature string 27 | SignatureMethod string 28 | Timestamp util.ISO6801Time 29 | SignatureVersion string 30 | SignatureNonce string 31 | ResourceOwnerAccount string 32 | Action string 33 | } 34 | 35 | func (request *Request) init(version string, action string, AccessKeyId string, securityToken string, regionId Region) { 36 | request.Format = JSONResponseFormat 37 | request.Timestamp = util.NewISO6801Time(time.Now().UTC()) 38 | request.Version = version 39 | request.SignatureVersion = SignatureVersion 40 | request.SignatureMethod = SignatureMethod 41 | request.SignatureNonce = util.CreateRandomString() 42 | request.Action = action 43 | request.AccessKeyId = AccessKeyId 44 | request.SecurityToken = securityToken 45 | request.RegionId = regionId 46 | } 47 | 48 | type Response struct { 49 | RequestId string 50 | } 51 | 52 | type ErrorResponse struct { 53 | Response 54 | HostId string 55 | Code string 56 | Message string 57 | } 58 | 59 | // An Error represents a custom error for Aliyun API failure response 60 | type Error struct { 61 | ErrorResponse 62 | StatusCode int //Status Code of HTTP Response 63 | } 64 | 65 | func (e *Error) Error() string { 66 | return fmt.Sprintf("Aliyun API Error: RequestId: %s Status Code: %d Code: %s Message: %s", e.RequestId, e.StatusCode, e.Code, e.Message) 67 | } 68 | 69 | type Pagination struct { 70 | PageNumber int 71 | PageSize int 72 | } 73 | 74 | func (p *Pagination) SetPageSize(size int) { 75 | p.PageSize = size 76 | } 77 | 78 | func (p *Pagination) Validate() { 79 | if p.PageNumber < 0 { 80 | log.Printf("Invalid PageNumber: %d", p.PageNumber) 81 | p.PageNumber = 1 82 | } 83 | if p.PageSize < 0 { 84 | log.Printf("Invalid PageSize: %d", p.PageSize) 85 | p.PageSize = 10 86 | } else if p.PageSize > 50 { 87 | log.Printf("Invalid PageSize: %d", p.PageSize) 88 | p.PageSize = 50 89 | } 90 | } 91 | 92 | // A PaginationResponse represents a response with pagination information 93 | type PaginationResult struct { 94 | TotalCount int 95 | PageNumber int 96 | PageSize int 97 | } 98 | 99 | // NextPage gets the next page of the result set 100 | func (r *PaginationResult) NextPage() *Pagination { 101 | if r.PageNumber*r.PageSize >= r.TotalCount { 102 | return nil 103 | } 104 | return &Pagination{PageNumber: r.PageNumber + 1, PageSize: r.PageSize} 105 | } 106 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/common/types.go: -------------------------------------------------------------------------------- 1 | package common 2 | 3 | type InternetChargeType string 4 | 5 | const ( 6 | PayByBandwidth = InternetChargeType("PayByBandwidth") 7 | PayByTraffic = InternetChargeType("PayByTraffic") 8 | ) 9 | 10 | type InstanceChargeType string 11 | 12 | const ( 13 | PrePaid = InstanceChargeType("PrePaid") 14 | PostPaid = InstanceChargeType("PostPaid") 15 | ) 16 | 17 | type DescribeEndpointArgs struct { 18 | Id Region 19 | ServiceCode string 20 | Type string 21 | } 22 | 23 | type EndpointItem struct { 24 | Protocols struct { 25 | Protocols []string 26 | } 27 | Type string 28 | Namespace string 29 | Id Region 30 | SerivceCode string 31 | Endpoint string 32 | } 33 | 34 | type DescribeEndpointResponse struct { 35 | Response 36 | EndpointItem 37 | } 38 | 39 | type NetType string 40 | 41 | const ( 42 | Internet = NetType("Internet") 43 | Intranet = NetType("Intranet") 44 | ) 45 | 46 | type TimeType string 47 | 48 | const ( 49 | Hour = TimeType("Hour") 50 | Day = TimeType("Day") 51 | Month = TimeType("Month") 52 | Year = TimeType("Year") 53 | ) 54 | 55 | type NetworkType string 56 | 57 | const ( 58 | Classic = NetworkType("Classic") 59 | VPC = NetworkType("VPC") 60 | ) 61 | 62 | type BusinessInfo struct { 63 | Pack string `json:"pack,omitempty"` 64 | ActivityId string `json:"activityId,omitempty"` 65 | } 66 | 67 | //xml 68 | type Endpoints struct { 69 | Endpoint []Endpoint `xml:"Endpoint"` 70 | } 71 | 72 | type Endpoint struct { 73 | Name string `xml:"name,attr"` 74 | RegionIds RegionIds `xml:"RegionIds"` 75 | Products Products `xml:"Products"` 76 | } 77 | 78 | type RegionIds struct { 79 | RegionId string `xml:"RegionId"` 80 | } 81 | 82 | type Products struct { 83 | Product []Product `xml:"Product"` 84 | } 85 | 86 | type Product struct { 87 | ProductName string `xml:"ProductName"` 88 | DomainName string `xml:"DomainName"` 89 | } 90 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/common/version.go: -------------------------------------------------------------------------------- 1 | package common 2 | 3 | const Version = "0.1" 4 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/ecs/client.go: -------------------------------------------------------------------------------- 1 | package ecs 2 | 3 | import ( 4 | "os" 5 | 6 | "github.com/denverdino/aliyungo/common" 7 | ) 8 | 9 | // Interval for checking status in WaitForXXX method 10 | const DefaultWaitForInterval = 5 11 | 12 | // Default timeout value for WaitForXXX method 13 | const DefaultTimeout = 60 14 | 15 | type Client struct { 16 | common.Client 17 | } 18 | 19 | const ( 20 | // ECSDefaultEndpoint is the default API endpoint of ECS services 21 | ECSDefaultEndpoint = "https://ecs-cn-hangzhou.aliyuncs.com" 22 | ECSAPIVersion = "2014-05-26" 23 | ECSServiceCode = "ecs" 24 | 25 | VPCDefaultEndpoint = "https://vpc.aliyuncs.com" 26 | VPCAPIVersion = "2016-04-28" 27 | VPCServiceCode = "vpc" 28 | ) 29 | 30 | // NewClient creates a new instance of ECS client 31 | func NewClient(accessKeyId, accessKeySecret string) *Client { 32 | endpoint := os.Getenv("ECS_ENDPOINT") 33 | if endpoint == "" { 34 | endpoint = ECSDefaultEndpoint 35 | } 36 | return NewClientWithEndpoint(endpoint, accessKeyId, accessKeySecret) 37 | } 38 | 39 | func NewClientWithRegion(endpoint string, accessKeyId string, accessKeySecret string, regionID common.Region) *Client { 40 | client := &Client{} 41 | client.NewInit(endpoint, ECSAPIVersion, accessKeyId, accessKeySecret, ECSServiceCode, regionID) 42 | return client 43 | } 44 | 45 | func NewClientWithEndpoint(endpoint string, accessKeyId string, accessKeySecret string) *Client { 46 | client := &Client{} 47 | client.Init(endpoint, ECSAPIVersion, accessKeyId, accessKeySecret) 48 | return client 49 | } 50 | 51 | // --------------------------------------- 52 | // NewECSClient creates a new instance of ECS client 53 | // --------------------------------------- 54 | func NewECSClient(accessKeyId, accessKeySecret string, regionID common.Region) *Client { 55 | return NewECSClientWithSecurityToken(accessKeyId, accessKeySecret, "", regionID) 56 | } 57 | 58 | func NewECSClientWithSecurityToken(accessKeyId string, accessKeySecret string, securityToken string, regionID common.Region) *Client { 59 | endpoint := os.Getenv("ECS_ENDPOINT") 60 | if endpoint == "" { 61 | endpoint = ECSDefaultEndpoint 62 | } 63 | 64 | return NewECSClientWithEndpointAndSecurityToken(endpoint, accessKeyId, accessKeySecret, securityToken, regionID) 65 | } 66 | 67 | func NewECSClientWithEndpoint(endpoint string, accessKeyId string, accessKeySecret string, regionID common.Region) *Client { 68 | return NewECSClientWithEndpointAndSecurityToken(endpoint, accessKeyId, accessKeySecret, "", regionID) 69 | } 70 | 71 | func NewECSClientWithEndpointAndSecurityToken(endpoint string, accessKeyId string, accessKeySecret string, securityToken string, regionID common.Region) *Client { 72 | client := &Client{} 73 | client.WithEndpoint(endpoint). 74 | WithVersion(ECSAPIVersion). 75 | WithAccessKeyId(accessKeyId). 76 | WithAccessKeySecret(accessKeySecret). 77 | WithSecurityToken(securityToken). 78 | WithServiceCode(ECSServiceCode). 79 | WithRegionID(regionID). 80 | InitClient() 81 | return client 82 | } 83 | 84 | // --------------------------------------- 85 | // NewVPCClient creates a new instance of VPC client 86 | // --------------------------------------- 87 | func NewVPCClient(accessKeyId string, accessKeySecret string, regionID common.Region) *Client { 88 | return NewVPCClientWithSecurityToken(accessKeyId, accessKeySecret, "", regionID) 89 | } 90 | 91 | func NewVPCClientWithSecurityToken(accessKeyId string, accessKeySecret string, securityToken string, regionID common.Region) *Client { 92 | endpoint := os.Getenv("VPC_ENDPOINT") 93 | if endpoint == "" { 94 | endpoint = VPCDefaultEndpoint 95 | } 96 | 97 | return NewVPCClientWithEndpointAndSecurityToken(endpoint, accessKeyId, accessKeySecret, securityToken, regionID) 98 | } 99 | 100 | func NewVPCClientWithEndpoint(endpoint string, accessKeyId string, accessKeySecret string, regionID common.Region) *Client { 101 | return NewVPCClientWithEndpointAndSecurityToken(endpoint, accessKeyId, accessKeySecret, "", regionID) 102 | } 103 | 104 | func NewVPCClientWithEndpointAndSecurityToken(endpoint string, accessKeyId string, accessKeySecret string, securityToken string, regionID common.Region) *Client { 105 | client := &Client{} 106 | client.WithEndpoint(endpoint). 107 | WithVersion(VPCAPIVersion). 108 | WithAccessKeyId(accessKeyId). 109 | WithAccessKeySecret(accessKeySecret). 110 | WithSecurityToken(securityToken). 111 | WithServiceCode(VPCServiceCode). 112 | WithRegionID(regionID). 113 | InitClient() 114 | return client 115 | } 116 | 117 | // --------------------------------------- 118 | // NewVPCClientWithRegion creates a new instance of VPC client automatically get endpoint 119 | // --------------------------------------- 120 | func NewVPCClientWithRegion(endpoint string, accessKeyId string, accessKeySecret string, regionID common.Region) *Client { 121 | client := &Client{} 122 | client.NewInit(endpoint, VPCAPIVersion, accessKeyId, accessKeySecret, VPCServiceCode, regionID) 123 | return client 124 | } -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/ecs/client_test.go: -------------------------------------------------------------------------------- 1 | package ecs 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestGenerateClientToken(t *testing.T) { 8 | client := NewTestClient() 9 | for i := 0; i < 10; i++ { 10 | t.Log("GenerateClientToken: ", client.GenerateClientToken()) 11 | } 12 | 13 | } 14 | 15 | func TestECSDescribe(t *testing.T) { 16 | if TestQuick { 17 | return 18 | } 19 | client := NewTestClient() 20 | 21 | regions, err := client.DescribeRegions() 22 | 23 | t.Log("regions: ", regions, err) 24 | 25 | for _, region := range regions { 26 | zones, err := client.DescribeZones(region.RegionId) 27 | t.Log("zones: ", zones, err) 28 | for _, zone := range zones { 29 | args := DescribeInstanceStatusArgs{ 30 | RegionId: region.RegionId, 31 | ZoneId: zone.ZoneId, 32 | } 33 | instanceStatuses, pagination, err := client.DescribeInstanceStatus(&args) 34 | t.Logf("instanceStatuses: %v, %++v, %v", instanceStatuses, pagination, err) 35 | for _, instanceStatus := range instanceStatuses { 36 | instance, err := client.DescribeInstanceAttribute(instanceStatus.InstanceId) 37 | t.Logf("Instance: %++v", instance) 38 | t.Logf("Error: %++v", err) 39 | } 40 | args1 := DescribeInstancesArgs{ 41 | RegionId: region.RegionId, 42 | ZoneId: zone.ZoneId, 43 | } 44 | instances, _, err := client.DescribeInstances(&args1) 45 | if err != nil { 46 | t.Errorf("Failed to describe instance by region %s zone %s: %v", region.RegionId, zone.ZoneId, err) 47 | } else { 48 | for _, instance := range instances { 49 | t.Logf("Instance: %++v", instance) 50 | } 51 | } 52 | 53 | } 54 | args := DescribeImagesArgs{RegionId: region.RegionId} 55 | 56 | for { 57 | 58 | images, pagination, err := client.DescribeImages(&args) 59 | if err != nil { 60 | t.Fatalf("Failed to describe images: %v", err) 61 | break 62 | } else { 63 | t.Logf("Image count for region %s total %d from %d", region.RegionId, pagination.TotalCount, pagination.PageNumber*pagination.PageSize) 64 | for _, image := range images { 65 | t.Logf("Image: %++v", image) 66 | } 67 | nextPage := pagination.NextPage() 68 | if nextPage == nil { 69 | break 70 | } 71 | args.Pagination = *nextPage 72 | } 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/ecs/config_test.go: -------------------------------------------------------------------------------- 1 | package ecs 2 | 3 | import ( 4 | "os" 5 | 6 | "github.com/denverdino/aliyungo/common" 7 | ) 8 | 9 | //Modify with your Access Key Id and Access Key Secret 10 | 11 | var ( 12 | TestAccessKeyId = os.Getenv("AccessKeyId") 13 | TestAccessKeySecret = os.Getenv("AccessKeySecret") 14 | TestSecurityToken = os.Getenv("SecurityToken") 15 | TestRegionID = common.Region(os.Getenv("RegionId")) 16 | 17 | TestInstanceId = "MY_TEST_INSTANCEID" 18 | TestSecurityGroupId = "MY_TEST_SECURITY_GROUP_ID" 19 | TestImageId = "MY_IMAGE_ID" 20 | TestAccountId = "MY_TEST_ACCOUNT_ID" //Get from https://account.console.aliyun.com 21 | TestInstanceType = "ecs.n4.large" 22 | TestVSwitchID = "MY_TEST_VSWITCHID" 23 | 24 | TestIAmRich = false 25 | TestQuick = false 26 | ) 27 | 28 | var testClient *Client 29 | 30 | func NewTestClient() *Client { 31 | if testClient == nil { 32 | testClient = NewClient(TestAccessKeyId, TestAccessKeySecret) 33 | } 34 | return testClient 35 | } 36 | 37 | var testDebugClient *Client 38 | 39 | func NewTestClientForDebug() *Client { 40 | if testDebugClient == nil { 41 | testDebugClient = NewClient(TestAccessKeyId, TestAccessKeySecret) 42 | testDebugClient.SetDebug(true) 43 | } 44 | return testDebugClient 45 | } 46 | 47 | var testLocationClient *Client 48 | 49 | func NetTestLocationClientForDebug() *Client { 50 | if testLocationClient == nil { 51 | testLocationClient = NewECSClient(TestAccessKeyId, TestAccessKeySecret, TestRegionID) 52 | testLocationClient.SetDebug(true) 53 | } 54 | 55 | return testLocationClient 56 | } 57 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/ecs/eni.go: -------------------------------------------------------------------------------- 1 | package ecs 2 | 3 | import "github.com/denverdino/aliyungo/common" 4 | 5 | type CreateNetworkInterfaceArgs struct { 6 | RegionId common.Region 7 | VSwitchId string 8 | PrimaryIpAddress string // optional 9 | SecurityGroupId string 10 | NetworkInterfaceName string // optional 11 | Description string // optional 12 | ClientToken string // optional 13 | } 14 | 15 | type CreateNetworkInterfaceResponse struct { 16 | common.Response 17 | NetworkInterfaceId string 18 | } 19 | type DeleteNetworkInterfaceArgs struct { 20 | RegionId common.Region 21 | NetworkInterfaceId string 22 | } 23 | 24 | type DeleteNetworkInterfaceResponse struct { 25 | common.Response 26 | } 27 | 28 | type DescribeNetworkInterfacesArgs struct { 29 | RegionId common.Region 30 | VSwitchId string 31 | PrimaryIpAddress string 32 | SecurityGroupId string 33 | NetworkInterfaceName string 34 | Type string 35 | InstanceId string 36 | NetworkInterfaceId []string 37 | PageNumber int 38 | PageSize int 39 | } 40 | type NetworkInterfaceType struct { 41 | NetworkInterfaceId string 42 | PrimaryIpAddress string 43 | MacAddress string 44 | } 45 | 46 | type DescribeNetworkInterfacesResponse struct { 47 | common.Response 48 | NetworkInterfaceSet []NetworkInterfaceType 49 | TotalCount int 50 | PageNumber int 51 | PageSize int 52 | } 53 | type AttachNetworkInterfaceArgs struct { 54 | RegionId common.Region 55 | NetworkInterfaceId string 56 | InstanceId string 57 | } 58 | 59 | type AttachNetworkInterfaceResponse common.Response 60 | 61 | type DetachNetworkInterfaceArgs AttachNetworkInterfaceArgs 62 | 63 | type DetachNetworkInterfaceResponse common.Response 64 | 65 | type ModifyNetworkInterfaceAttributeArgs struct { 66 | RegionId common.Region 67 | NetworkInterfaceId string 68 | SecurityGroupId []string 69 | NetworkInterfaceName string 70 | Description string 71 | } 72 | type ModifyNetworkInterfaceAttributeResponse common.Response 73 | 74 | func (client *Client) CreateNetworkInterface(args *CreateNetworkInterfaceArgs) (resp *CreateNetworkInterfaceResponse, err error) { 75 | resp = &CreateNetworkInterfaceResponse{} 76 | err = client.Invoke("CreateNetworkInterface", args, resp) 77 | return resp, err 78 | } 79 | 80 | func (client *Client) DeleteNetworkInterface(args *DeleteNetworkInterfaceArgs) (resp *DeleteNetworkInterfaceResponse, err error) { 81 | resp = &DeleteNetworkInterfaceResponse{} 82 | err = client.Invoke("DeleteNetworkInterface", args, resp) 83 | return resp, err 84 | } 85 | 86 | func (client *Client) DescribeNetworkInterfaces(args *DescribeNetworkInterfacesArgs) (resp *DescribeNetworkInterfacesResponse, err error) { 87 | resp = &DescribeNetworkInterfacesResponse{} 88 | err = client.Invoke("DescribeNetworkInterfaces", args, resp) 89 | return resp, err 90 | } 91 | 92 | func (client *Client) AttachNetworkInterface(args *AttachNetworkInterfaceArgs) (resp *AttachNetworkInterfaceResponse, err error) { 93 | resp = &AttachNetworkInterfaceResponse{} 94 | err = client.Invoke("AttachNetworkInterface", args, resp) 95 | return resp, err 96 | } 97 | 98 | func (client *Client) DetachNetworkInterface(args *DetachNetworkInterfaceArgs) (resp *DetachNetworkInterfaceResponse, err error) { 99 | resp = &DetachNetworkInterfaceResponse{} 100 | err = client.Invoke("DetachNetworkInterface", args, resp) 101 | return resp, err 102 | } 103 | 104 | func (client *Client) ModifyNetworkInterfaceAttribute(args *ModifyNetworkInterfaceAttributeArgs) (resp *ModifyNetworkInterfaceAttributeResponse, err error) { 105 | resp = &ModifyNetworkInterfaceAttributeResponse{} 106 | err = client.Invoke("ModifyNetworkInterfaceAttribute", args, resp) 107 | return resp, err 108 | } 109 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/ecs/forward_entry.go: -------------------------------------------------------------------------------- 1 | package ecs 2 | 3 | import "github.com/denverdino/aliyungo/common" 4 | 5 | type CreateForwardEntryArgs struct { 6 | RegionId common.Region 7 | ForwardTableId string 8 | ExternalIp string 9 | ExternalPort string 10 | IpProtocol string 11 | InternalIp string 12 | InternalPort string 13 | } 14 | 15 | type CreateForwardEntryResponse struct { 16 | common.Response 17 | ForwardEntryId string 18 | } 19 | 20 | type DescribeForwardTableEntriesArgs struct { 21 | RegionId common.Region 22 | ForwardTableId string 23 | common.Pagination 24 | } 25 | 26 | type ForwardTableEntrySetType struct { 27 | RegionId common.Region 28 | ExternalIp string 29 | ExternalPort string 30 | ForwardEntryId string 31 | ForwardTableId string 32 | InternalIp string 33 | InternalPort string 34 | IpProtocol string 35 | Status string 36 | } 37 | 38 | type DescribeForwardTableEntriesResponse struct { 39 | common.Response 40 | common.PaginationResult 41 | ForwardTableEntries struct { 42 | ForwardTableEntry []ForwardTableEntrySetType 43 | } 44 | } 45 | 46 | type ModifyForwardEntryArgs struct { 47 | RegionId common.Region 48 | ForwardTableId string 49 | ForwardEntryId string 50 | ExternalIp string 51 | IpProtocol string 52 | ExternalPort string 53 | InternalIp string 54 | InternalPort string 55 | } 56 | 57 | type ModifyForwardEntryResponse struct { 58 | common.Response 59 | } 60 | 61 | type DeleteForwardEntryArgs struct { 62 | RegionId common.Region 63 | ForwardTableId string 64 | ForwardEntryId string 65 | } 66 | 67 | type DeleteForwardEntryResponse struct { 68 | common.Response 69 | } 70 | 71 | func (client *Client) CreateForwardEntry(args *CreateForwardEntryArgs) (resp *CreateForwardEntryResponse, err error) { 72 | response := CreateForwardEntryResponse{} 73 | err = client.Invoke("CreateForwardEntry", args, &response) 74 | if err != nil { 75 | return nil, err 76 | } 77 | return &response, err 78 | } 79 | 80 | func (client *Client) DescribeForwardTableEntries(args *DescribeForwardTableEntriesArgs) (forwardTableEntries []ForwardTableEntrySetType, 81 | pagination *common.PaginationResult, err error) { 82 | response, err := client.DescribeForwardTableEntriesWithRaw(args) 83 | if err != nil { 84 | return nil, nil, err 85 | } 86 | 87 | return response.ForwardTableEntries.ForwardTableEntry, &response.PaginationResult, nil 88 | } 89 | 90 | func (client *Client) DescribeForwardTableEntriesWithRaw(args *DescribeForwardTableEntriesArgs) (response *DescribeForwardTableEntriesResponse, err error) { 91 | args.Validate() 92 | response = &DescribeForwardTableEntriesResponse{} 93 | 94 | err = client.Invoke("DescribeForwardTableEntries", args, response) 95 | 96 | if err != nil { 97 | return nil, err 98 | } 99 | 100 | return response, nil 101 | } 102 | 103 | func (client *Client) ModifyForwardEntry(args *ModifyForwardEntryArgs) error { 104 | response := ModifyForwardEntryResponse{} 105 | return client.Invoke("ModifyForwardEntry", args, &response) 106 | } 107 | 108 | func (client *Client) DeleteForwardEntry(args *DeleteForwardEntryArgs) error { 109 | response := DeleteForwardEntryResponse{} 110 | err := client.Invoke("DeleteForwardEntry", args, &response) 111 | return err 112 | } 113 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/ecs/images_test.go: -------------------------------------------------------------------------------- 1 | package ecs 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/denverdino/aliyungo/common" 7 | ) 8 | 9 | func TestImageCreationAndDeletion(t *testing.T) { 10 | 11 | client := NewTestClient() 12 | 13 | instance, err := client.DescribeInstanceAttribute(TestInstanceId) 14 | if err != nil { 15 | t.Fatalf("Failed to DescribeInstanceAttribute for instance %s: %v", TestInstanceId, err) 16 | } 17 | 18 | args := DescribeSnapshotsArgs{} 19 | 20 | args.InstanceId = TestInstanceId 21 | args.RegionId = instance.RegionId 22 | snapshots, _, err := client.DescribeSnapshots(&args) 23 | 24 | if err != nil { 25 | t.Errorf("Failed to DescribeSnapshots for instance %s: %v", TestInstanceId, err) 26 | } 27 | 28 | if len(snapshots) > 0 { 29 | 30 | createImageArgs := CreateImageArgs{ 31 | RegionId: instance.RegionId, 32 | SnapshotId: snapshots[0].SnapshotId, 33 | 34 | ImageName: "My_Test_Image_for_AliyunGo", 35 | ImageVersion: "1.0", 36 | Description: "My Test Image for AliyunGo description", 37 | ClientToken: client.GenerateClientToken(), 38 | } 39 | imageId, err := client.CreateImage(&createImageArgs) 40 | if err != nil { 41 | t.Errorf("Failed to CreateImage for SnapshotId %s: %v", createImageArgs.SnapshotId, err) 42 | } 43 | t.Logf("Image %s is created successfully.", imageId) 44 | 45 | err = client.DeleteImage(instance.RegionId, imageId) 46 | if err != nil { 47 | t.Errorf("Failed to DeleteImage for %s: %v", imageId, err) 48 | } 49 | t.Logf("Image %s is deleted successfully.", imageId) 50 | 51 | } 52 | } 53 | 54 | func TestModifyImageSharePermission(t *testing.T) { 55 | req := ModifyImageSharePermissionArgs{ 56 | RegionId: common.Beijing, 57 | ImageId: TestImageId, 58 | AddAccount: []string{TestAccountId}, 59 | } 60 | client := NewTestClient() 61 | err := client.ModifyImageSharePermission(&req) 62 | if err != nil { 63 | t.Errorf("Failed to ShareImage: %v", err) 64 | } 65 | 66 | shareInfo, err := client.DescribeImageSharePermission(&req) 67 | if err != nil { 68 | t.Errorf("Failed to ShareImage: %v", err) 69 | } 70 | t.Logf("result:image: %++v", shareInfo) 71 | } 72 | 73 | func TestCopyImage(t *testing.T) { 74 | client := NewTestClient() 75 | req := CopyImageArgs{ 76 | RegionId: common.Beijing, 77 | ImageId: TestImageId, 78 | DestinationRegionId: common.Hangzhou, 79 | DestinationImageName: "My_Test_Image_NAME_for_AliyunGo", 80 | DestinationDescription: "My Test Image for AliyunGo description", 81 | ClientToken: client.GenerateClientToken(), 82 | } 83 | 84 | imageId, err := client.CopyImage(&req) 85 | if err != nil { 86 | t.Errorf("Failed to CopyImage: %v", err) 87 | } 88 | t.Logf("result:image: %++v", imageId) 89 | 90 | if err := client.WaitForImageReady(common.Hangzhou, imageId, 600); err != nil { 91 | t.Errorf("Failed to WaitImage: %v", err) 92 | //return 93 | } 94 | 95 | describeReq := DescribeImagesArgs{ 96 | RegionId: common.Hangzhou, 97 | ImageId: imageId, 98 | Status: ImageStatusAvailable, 99 | ImageOwnerAlias: ImageOwnerSelf, 100 | } 101 | 102 | images, _, err := client.DescribeImages(&describeReq) 103 | if err != nil { 104 | t.Errorf("Failed to describeImage: %v", err) 105 | } 106 | t.Logf("result: images %++v", images) 107 | } 108 | 109 | func TestCancelCopyImage(t *testing.T) { 110 | client := NewTestClient() 111 | if err := client.CancelCopyImage(common.Hangzhou, TestImageId); err != nil { 112 | t.Errorf("Failed to CancelCopyImage: %v", err) 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/ecs/instance_types.go: -------------------------------------------------------------------------------- 1 | package ecs 2 | 3 | import "github.com/denverdino/aliyungo/common" 4 | 5 | type DescribeInstanceTypesArgs struct { 6 | InstanceTypeFamily string 7 | } 8 | 9 | // 10 | // You can read doc at http://docs.aliyun.com/#/pub/ecs/open-api/datatype&instancetypeitemtype 11 | type InstanceTypeItemType struct { 12 | InstanceTypeId string 13 | CpuCoreCount int 14 | MemorySize float64 15 | InstanceTypeFamily string 16 | } 17 | 18 | type DescribeInstanceTypesResponse struct { 19 | common.Response 20 | InstanceTypes struct { 21 | InstanceType []InstanceTypeItemType 22 | } 23 | } 24 | 25 | // DescribeInstanceTypes describes all instance types 26 | // 27 | // You can read doc at http://docs.aliyun.com/#/pub/ecs/open-api/other&describeinstancetypes 28 | func (client *Client) DescribeInstanceTypes() (instanceTypes []InstanceTypeItemType, err error) { 29 | response := DescribeInstanceTypesResponse{} 30 | 31 | err = client.Invoke("DescribeInstanceTypes", &DescribeInstanceTypesArgs{}, &response) 32 | 33 | if err != nil { 34 | return []InstanceTypeItemType{}, err 35 | } 36 | return response.InstanceTypes.InstanceType, nil 37 | 38 | } 39 | 40 | // support user args 41 | func (client *Client) DescribeInstanceTypesNew(args *DescribeInstanceTypesArgs) (instanceTypes []InstanceTypeItemType, err error) { 42 | response := DescribeInstanceTypesResponse{} 43 | 44 | err = client.Invoke("DescribeInstanceTypes", args, &response) 45 | 46 | if err != nil { 47 | return []InstanceTypeItemType{}, err 48 | } 49 | return response.InstanceTypes.InstanceType, nil 50 | 51 | } 52 | 53 | type DescribeInstanceTypeFamiliesArgs struct { 54 | RegionId common.Region 55 | Generation string 56 | } 57 | 58 | type InstanceTypeFamilies struct { 59 | InstanceTypeFamily []InstanceTypeFamily 60 | } 61 | 62 | type InstanceTypeFamily struct { 63 | InstanceTypeFamilyId string 64 | Generation string 65 | } 66 | 67 | type DescribeInstanceTypeFamiliesResponse struct { 68 | common.Response 69 | 70 | InstanceTypeFamilies InstanceTypeFamilies 71 | } 72 | 73 | func (client *Client) DescribeInstanceTypeFamilies(args *DescribeInstanceTypeFamiliesArgs) (*DescribeInstanceTypeFamiliesResponse, error) { 74 | response := &DescribeInstanceTypeFamiliesResponse{} 75 | 76 | err := client.Invoke("DescribeInstanceTypeFamilies", args, response) 77 | if err != nil { 78 | return nil, err 79 | } 80 | 81 | return response, nil 82 | } 83 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/ecs/instance_types_test.go: -------------------------------------------------------------------------------- 1 | package ecs 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestDescribeInstanceTypes(t *testing.T) { 8 | 9 | client := NewTestClient() 10 | instanceTypes, err := client.DescribeInstanceTypes() 11 | if err != nil { 12 | t.Fatalf("Failed to DescribeInstanceTypes: %v", err) 13 | } 14 | for _, instanceType := range instanceTypes { 15 | t.Logf("InstanceType: %++v", instanceType) 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/ecs/monitoring.go: -------------------------------------------------------------------------------- 1 | package ecs 2 | 3 | import ( 4 | "github.com/denverdino/aliyungo/common" 5 | "github.com/denverdino/aliyungo/util" 6 | ) 7 | 8 | type DescribeInstanceMonitorDataArgs struct { 9 | InstanceId string 10 | StartTime util.ISO6801Time 11 | EndTime util.ISO6801Time 12 | Period int //Default 60s 13 | } 14 | 15 | // 16 | // You can read doc at http://docs.aliyun.com/#/pub/ecs/open-api/datatype&instancemonitordatatype 17 | type InstanceMonitorDataType struct { 18 | InstanceId string 19 | CPU int 20 | IntranetRX int 21 | IntranetTX int 22 | IntranetBandwidth int 23 | InternetRX int 24 | InternetTX int 25 | InternetBandwidth int 26 | IOPSRead int 27 | IOPSWrite int 28 | BPSRead int 29 | BPSWrite int 30 | TimeStamp util.ISO6801Time 31 | } 32 | 33 | type DescribeInstanceMonitorDataResponse struct { 34 | common.Response 35 | MonitorData struct { 36 | InstanceMonitorData []InstanceMonitorDataType 37 | } 38 | } 39 | 40 | // DescribeInstanceMonitorData describes instance monitoring data 41 | // 42 | // You can read doc at http://docs.aliyun.com/#/pub/ecs/open-api/monitor&describeinstancemonitordata 43 | func (client *Client) DescribeInstanceMonitorData(args *DescribeInstanceMonitorDataArgs) (monitorData []InstanceMonitorDataType, err error) { 44 | if args.Period == 0 { 45 | args.Period = 60 46 | } 47 | response := DescribeInstanceMonitorDataResponse{} 48 | err = client.Invoke("DescribeInstanceMonitorData", args, &response) 49 | if err != nil { 50 | return nil, err 51 | } 52 | return response.MonitorData.InstanceMonitorData, err 53 | } 54 | 55 | type DescribeEipMonitorDataArgs struct { 56 | AllocationId string 57 | StartTime util.ISO6801Time 58 | EndTime util.ISO6801Time 59 | Period int //Default 60s 60 | } 61 | 62 | // 63 | // You can read doc at http://docs.aliyun.com/#/pub/ecs/open-api/datatype&eipmonitordatatype 64 | type EipMonitorDataType struct { 65 | EipRX int 66 | EipTX int 67 | EipFlow int 68 | EipBandwidth int 69 | EipPackets int 70 | TimeStamp util.ISO6801Time 71 | } 72 | 73 | type DescribeEipMonitorDataResponse struct { 74 | common.Response 75 | EipMonitorDatas struct { 76 | EipMonitorData []EipMonitorDataType 77 | } 78 | } 79 | 80 | // DescribeEipMonitorData describes EIP monitoring data 81 | // 82 | // You can read doc at http://docs.aliyun.com/#/pub/ecs/open-api/monitor&describeeipmonitordata 83 | func (client *Client) DescribeEipMonitorData(args *DescribeEipMonitorDataArgs) (monitorData []EipMonitorDataType, err error) { 84 | if args.Period == 0 { 85 | args.Period = 60 86 | } 87 | response := DescribeEipMonitorDataResponse{} 88 | err = client.Invoke("DescribeEipMonitorData", args, &response) 89 | if err != nil { 90 | return nil, err 91 | } 92 | return response.EipMonitorDatas.EipMonitorData, err 93 | } 94 | 95 | type DescribeDiskMonitorDataArgs struct { 96 | DiskId string 97 | StartTime util.ISO6801Time 98 | EndTime util.ISO6801Time 99 | Period int //Default 60s 100 | } 101 | 102 | // 103 | // You can read doc at http://docs.aliyun.com/#/pub/ecs/open-api/datatype&diskmonitordatatype 104 | type DiskMonitorDataType struct { 105 | DiskId string 106 | IOPSRead int 107 | IOPSWrite int 108 | IOPSTotal int 109 | BPSRead int 110 | BPSWrite int 111 | BPSTotal int 112 | TimeStamp util.ISO6801Time 113 | } 114 | 115 | type DescribeDiskMonitorDataResponse struct { 116 | common.Response 117 | TotalCount int 118 | MonitorData struct { 119 | DiskMonitorData []DiskMonitorDataType 120 | } 121 | } 122 | 123 | // DescribeDiskMonitorData describes disk monitoring data 124 | // 125 | // You can read doc at http://docs.aliyun.com/#/pub/ecs/open-api/monitor&describediskmonitordata 126 | func (client *Client) DescribeDiskMonitorData(args *DescribeDiskMonitorDataArgs) (monitorData []DiskMonitorDataType, totalCount int, err error) { 127 | if args.Period == 0 { 128 | args.Period = 60 129 | } 130 | response := DescribeDiskMonitorDataResponse{} 131 | err = client.Invoke("DescribeDiskMonitorData", args, &response) 132 | if err != nil { 133 | return nil, 0, err 134 | } 135 | return response.MonitorData.DiskMonitorData, response.TotalCount, err 136 | } 137 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/ecs/monitoring_test.go: -------------------------------------------------------------------------------- 1 | package ecs 2 | 3 | import ( 4 | "testing" 5 | "time" 6 | 7 | "github.com/denverdino/aliyungo/util" 8 | ) 9 | 10 | func TestMonitoring(t *testing.T) { 11 | client := NewTestClient() 12 | //client.SetDebug(true) 13 | 14 | //Describe test instance 15 | instance, err := client.DescribeInstanceAttribute(TestInstanceId) 16 | if err != nil { 17 | t.Fatalf("Failed to describe instance %s: %v", TestInstanceId, err) 18 | } 19 | t.Logf("Instance: %++v %v", instance, err) 20 | 21 | //Describe Instance Monitor Data 22 | now := time.Now().UTC() 23 | 24 | starting := time.Date(now.Year(), now.Month(), now.Day(), now.Hour()-2, now.Minute(), now.Second(), now.Nanosecond(), now.Location()) 25 | ending := time.Date(now.Year(), now.Month(), now.Day(), now.Hour()-1, now.Minute(), now.Second(), now.Nanosecond(), now.Location()) 26 | 27 | args := DescribeInstanceMonitorDataArgs{ 28 | InstanceId: TestInstanceId, 29 | StartTime: util.ISO6801Time(starting), 30 | EndTime: util.ISO6801Time(ending), 31 | } 32 | 33 | monitorData, err := client.DescribeInstanceMonitorData(&args) 34 | 35 | if err != nil { 36 | t.Fatalf("Failed to describe monitoring data for instance %s: %v", TestInstanceId, err) 37 | } 38 | 39 | for _, data := range monitorData { 40 | t.Logf("Monitor Data: %++v", data) 41 | } 42 | //Describe EIP monitor data 43 | 44 | //Describe disk monitor data 45 | diskArgs := DescribeDisksArgs{ 46 | InstanceId: TestInstanceId, 47 | RegionId: instance.RegionId, 48 | } 49 | 50 | disks, _, err := client.DescribeDisks(&diskArgs) 51 | if err != nil { 52 | t.Fatalf("Failed to DescribeDisks for instance %s: %v", TestInstanceId, err) 53 | } 54 | 55 | for _, disk := range disks { 56 | args := DescribeDiskMonitorDataArgs{ 57 | DiskId: disk.DiskId, 58 | StartTime: util.ISO6801Time(starting), 59 | EndTime: util.ISO6801Time(ending), 60 | } 61 | monitorData, _, err := client.DescribeDiskMonitorData(&args) 62 | 63 | if err != nil { 64 | t.Fatalf("Failed to describe monitoring data for disk %s: %v", disk.DiskId, err) 65 | } 66 | 67 | for _, data := range monitorData { 68 | t.Logf("Monitor Data: %++v", data) 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/ecs/nat_gateway_test.go: -------------------------------------------------------------------------------- 1 | package ecs 2 | 3 | import "testing" 4 | 5 | 6 | func TestDescribeNatGateway(t *testing.T) { 7 | 8 | client := NewTestClient() 9 | args := DescribeBandwidthPackagesArgs{ 10 | RegionId: "cn-beijing", 11 | BandwidthPackageId: "bwp-2zes6svn910zjqhcyqnxm", 12 | NatGatewayId: "ngw-2zex6oklf8901t76yut6c", 13 | } 14 | packages, err := client.DescribeBandwidthPackages(&args) 15 | if err != nil { 16 | t.Fatalf("Failed to DescribeBandwidthPackages: %v", err) 17 | } 18 | for _, pack := range packages{ 19 | t.Logf("pack.IpCount: %++v", pack.IpCount) 20 | t.Logf("pack.Bandwidth: %++v", pack.Bandwidth) 21 | t.Logf("pack.ZoneId: %++v", pack.ZoneId) 22 | t.Logf("pack.ipAddress: %++v", len(pack.PublicIpAddresses.PublicIpAddresse)) 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/ecs/networks_test.go: -------------------------------------------------------------------------------- 1 | package ecs 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/denverdino/aliyungo/common" 7 | ) 8 | 9 | func TestAllocatePublicIpAddress(t *testing.T) { 10 | 11 | client := NewTestClient() 12 | instance, err := client.DescribeInstanceAttribute(TestInstanceId) 13 | if err != nil { 14 | t.Fatalf("Failed to describe instance %s: %v", TestInstanceId, err) 15 | } 16 | t.Logf("Instance: %++v %v", instance, err) 17 | ipAddr, err := client.AllocatePublicIpAddress(TestInstanceId) 18 | if err != nil { 19 | t.Fatalf("Failed to allocate public IP address for instance %s: %v", TestInstanceId, err) 20 | } 21 | t.Logf("Public IP address of instance %s: %s", TestInstanceId, ipAddr) 22 | 23 | } 24 | 25 | func testEipAddress(t *testing.T, client *Client, regionId common.Region, instanceId string) error { 26 | 27 | args := AllocateEipAddressArgs{ 28 | RegionId: regionId, 29 | Bandwidth: 5, 30 | InternetChargeType: common.PayByTraffic, 31 | ClientToken: client.GenerateClientToken(), 32 | } 33 | ipAddr, allocationId, err := client.AllocateEipAddress(&args) 34 | if err != nil { 35 | t.Errorf("Failed to allocate EIP address: %v", err) 36 | return err 37 | } 38 | t.Logf("EIP address: %s, AllocationId: %s", ipAddr, allocationId) 39 | 40 | err = client.WaitForEip(regionId, allocationId, EipStatusAvailable, 0) 41 | if err != nil { 42 | t.Errorf("Failed to wait EIP %s: %v", allocationId, err) 43 | } 44 | 45 | err = client.AssociateEipAddress(allocationId, instanceId) 46 | if err != nil { 47 | t.Errorf("Failed to associate EIP address: %v", err) 48 | } 49 | err = client.WaitForEip(regionId, allocationId, EipStatusInUse, 0) 50 | if err != nil { 51 | t.Errorf("Failed to wait EIP %s: %v", allocationId, err) 52 | } 53 | err = client.UnassociateEipAddress(allocationId, instanceId) 54 | if err != nil { 55 | t.Errorf("Failed to unassociate EIP address: %v", err) 56 | } 57 | err = client.WaitForEip(regionId, allocationId, EipStatusAvailable, 0) 58 | if err != nil { 59 | t.Errorf("Failed to wait EIP %s: %v", allocationId, err) 60 | } 61 | err = client.ReleaseEipAddress(allocationId) 62 | if err != nil { 63 | t.Errorf("Failed to release EIP address: %v", err) 64 | } 65 | return err 66 | } 67 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/ecs/regions.go: -------------------------------------------------------------------------------- 1 | package ecs 2 | 3 | import "github.com/denverdino/aliyungo/common" 4 | 5 | type DescribeRegionsArgs struct { 6 | } 7 | 8 | // 9 | // You can read doc at http://docs.aliyun.com/#/pub/ecs/open-api/datatype®iontype 10 | type RegionType struct { 11 | RegionId common.Region 12 | LocalName string 13 | } 14 | 15 | type DescribeRegionsResponse struct { 16 | common.Response 17 | Regions struct { 18 | Region []RegionType 19 | } 20 | } 21 | 22 | // DescribeRegions describes regions 23 | // 24 | // You can read doc at http://docs.aliyun.com/#/pub/ecs/open-api/region&describeregions 25 | func (client *Client) DescribeRegions() (regions []RegionType, err error) { 26 | response := DescribeRegionsResponse{} 27 | 28 | err = client.Invoke("DescribeRegions", &DescribeRegionsArgs{}, &response) 29 | 30 | if err != nil { 31 | return []RegionType{}, err 32 | } 33 | return response.Regions.Region, nil 34 | } 35 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/ecs/route_tables_test.go: -------------------------------------------------------------------------------- 1 | package ecs 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/denverdino/aliyungo/common" 7 | ) 8 | 9 | func testRouteTable(t *testing.T, client *Client, regionId common.Region, vpcId string, vrouterId string, routeTableId string, instanceId string) { 10 | cidrBlock := "0.0.0.0/0" 11 | createArgs := CreateRouteEntryArgs{ 12 | RouteTableId: routeTableId, 13 | DestinationCidrBlock: cidrBlock, 14 | NextHopType: NextHopIntance, 15 | NextHopId: instanceId, 16 | ClientToken: client.GenerateClientToken(), 17 | } 18 | 19 | err := client.CreateRouteEntry(&createArgs) 20 | if err != nil { 21 | t.Errorf("Failed to create route entry: %v", err) 22 | } 23 | 24 | describeArgs := DescribeRouteTablesArgs{ 25 | VRouterId: vrouterId, 26 | } 27 | 28 | routeTables, _, err := client.DescribeRouteTables(&describeArgs) 29 | 30 | if err != nil { 31 | t.Errorf("Failed to describe route tables: %v", err) 32 | } else { 33 | t.Logf("RouteTables of VRouter %s: %++v", vrouterId, routeTables) 34 | } 35 | 36 | err = client.WaitForAllRouteEntriesAvailable(vrouterId, routeTableId, 60) 37 | if err != nil { 38 | t.Errorf("Failed to wait route entries: %v", err) 39 | } 40 | deleteArgs := DeleteRouteEntryArgs{ 41 | RouteTableId: routeTableId, 42 | DestinationCidrBlock: cidrBlock, 43 | NextHopId: instanceId, 44 | } 45 | 46 | err = client.DeleteRouteEntry(&deleteArgs) 47 | if err != nil { 48 | t.Errorf("Failed to delete route entry: %v", err) 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/ecs/router_interface_test.go: -------------------------------------------------------------------------------- 1 | package ecs 2 | 3 | import ( 4 | "testing" 5 | "github.com/denverdino/aliyungo/common" 6 | ) 7 | 8 | func TestRouteInterface(t *testing.T) { 9 | 10 | client := NewTestClient() 11 | 12 | routerId := "****" 13 | oldSpec, newSpec := Spec("Middle.1"), Spec("Middle.2") 14 | initName, newName := "initName", "newName" 15 | initDesc, newDesc := "initDesc", "newDesc" 16 | oppositeRouterId, oppositeInterfaceId, oppositeInterfaceOwnerId := "***", "****", "*****" 17 | 18 | createArgs := CreateRouterInterfaceArgs{ 19 | RegionId: common.Beijing, 20 | RouterType: VRouter, 21 | RouterId: routerId, 22 | Role: InitiatingSide, 23 | Spec: oldSpec, 24 | OppositeRegionId: common.Hangzhou, 25 | OppositeRouterType: VRouter, 26 | Name: initName, 27 | Description: initDesc, 28 | } 29 | resp, err := client.CreateRouterInterface(&createArgs) 30 | if err != nil { 31 | t.Errorf("Failed to create route interface: %v", err) 32 | } 33 | 34 | var filter []Filter 35 | filter = append(filter, Filter{Key: "RouterId", Value: []string{createArgs.RouterId}}) 36 | describeArgs := DescribeRouterInterfacesArgs{ 37 | RegionId: common.Beijing, 38 | Filter: filter, 39 | } 40 | _, err = client.DescribeRouterInterfaces(&describeArgs) 41 | if err != nil { 42 | t.Errorf("Failed to describe route interfaces: %v", err) 43 | } 44 | 45 | modifyArgs := ModifyRouterInterfaceSpecArgs{ 46 | Spec: newSpec, 47 | RegionId: createArgs.RegionId, 48 | RouterInterfaceId: resp.RouterInterfaceId, 49 | 50 | } 51 | _, err = client.ModifyRouterInterfaceSpec(&modifyArgs) 52 | if err != nil { 53 | t.Errorf("Failed to modify route interface spec: %v", err) 54 | } 55 | 56 | modifyAArgs := ModifyRouterInterfaceAttributeArgs{ 57 | RegionId: createArgs.RegionId, 58 | RouterInterfaceId: resp.RouterInterfaceId, 59 | Name: newName, 60 | Description: newDesc, 61 | OppositeRouterId: oppositeRouterId, 62 | OppositeInterfaceId: oppositeInterfaceId, 63 | OppositeInterfaceOwnerId: oppositeInterfaceOwnerId, 64 | 65 | } 66 | _, err = client.ModifyRouterInterfaceAttribute(&modifyAArgs) 67 | if err != nil { 68 | t.Errorf("Failed to modify route interface spec: %v", err) 69 | } 70 | 71 | deleteArgs := OperateRouterInterfaceArgs{ 72 | RegionId: createArgs.RegionId, 73 | RouterInterfaceId: resp.RouterInterfaceId, 74 | } 75 | _, err = client.DeleteRouterInterface(&deleteArgs) 76 | if err != nil { 77 | t.Errorf("Failed to delete route interface: %v", err) 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/ecs/security_groups_test.go: -------------------------------------------------------------------------------- 1 | package ecs 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/denverdino/aliyungo/common" 7 | ) 8 | 9 | func TestSecurityGroups(t *testing.T) { 10 | 11 | client := NewTestClient() 12 | regions, err := client.DescribeRegions() 13 | 14 | t.Log("regions: ", regions, err) 15 | 16 | for _, region := range regions { 17 | 18 | arg := DescribeSecurityGroupsArgs{ 19 | RegionId: region.RegionId, 20 | } 21 | 22 | sgs, _, err := client.DescribeSecurityGroups(&arg) 23 | if err != nil { 24 | t.Errorf("Failed to DescribeSecurityGroups for region %s: %v", region.RegionId, err) 25 | continue 26 | } 27 | for _, sg := range sgs { 28 | t.Logf("SecurityGroup: %++v", sg) 29 | 30 | args := DescribeSecurityGroupAttributeArgs{ 31 | SecurityGroupId: sg.SecurityGroupId, 32 | RegionId: region.RegionId, 33 | } 34 | sga, err := client.DescribeSecurityGroupAttribute(&args) 35 | if err != nil { 36 | t.Errorf("Failed to DescribeSecurityGroupAttribute %s: %v", sg.SecurityGroupId, err) 37 | continue 38 | } 39 | t.Logf("SecurityGroup Attribute: %++v", sga) 40 | 41 | } 42 | } 43 | } 44 | 45 | func TestECSSecurityGroupCreationAndDeletion(t *testing.T) { 46 | client := NewTestClient() 47 | instance, err := client.DescribeInstanceAttribute(TestInstanceId) 48 | if err != nil { 49 | t.Fatalf("Failed to describe instance attribute %s: %v", TestInstanceId, err) 50 | } 51 | regionId := instance.RegionId 52 | 53 | _testECSSecurityGroupCreationAndDeletion(t, client, regionId, "") 54 | 55 | } 56 | 57 | func _testECSSecurityGroupCreationAndDeletion(t *testing.T, client *Client, regionId common.Region, vpcId string) { 58 | 59 | sgName := "test-security-group" 60 | args := CreateSecurityGroupArgs{ 61 | RegionId: regionId, 62 | VpcId: vpcId, 63 | SecurityGroupName: sgName, 64 | } 65 | 66 | sgId, err := client.CreateSecurityGroup(&args) 67 | if err != nil { 68 | t.Fatalf("Failed to create security group %s: %v", sgName, err) 69 | } 70 | t.Logf("Security group %s is created successfully.", sgId) 71 | 72 | describeArgs := DescribeSecurityGroupAttributeArgs{ 73 | SecurityGroupId: sgId, 74 | RegionId: regionId, 75 | } 76 | sg, err := client.DescribeSecurityGroupAttribute(&describeArgs) 77 | if err != nil { 78 | t.Errorf("Failed to describe security group %s: %v", sgId, err) 79 | } 80 | t.Logf("Security group %s: %++v", sgId, sg) 81 | 82 | newName := "test-security-group-new" 83 | modifyArgs := ModifySecurityGroupAttributeArgs{ 84 | SecurityGroupId: sgId, 85 | RegionId: regionId, 86 | SecurityGroupName: newName, 87 | } 88 | err = client.ModifySecurityGroupAttribute(&modifyArgs) 89 | if err != nil { 90 | t.Errorf("Failed to modify security group %s: %v", sgId, err) 91 | } else { 92 | sg, err := client.DescribeSecurityGroupAttribute(&describeArgs) 93 | if err != nil { 94 | t.Errorf("Failed to describe security group %s: %v", sgId, err) 95 | } 96 | t.Logf("Security group %s: %++v", sgId, sg) 97 | if sg.SecurityGroupName != newName { 98 | t.Errorf("Failed to modify security group %s with new name %s", sgId, newName) 99 | } 100 | } 101 | 102 | err = client.DeleteSecurityGroup(regionId, sgId) 103 | 104 | if err != nil { 105 | t.Fatalf("Failed to delete security group %s: %v", sgId, err) 106 | } 107 | t.Logf("Security group %s is deleted successfully.", sgId) 108 | } 109 | 110 | func TestDescribeSecurityGroupAttribute(t *testing.T) { 111 | client := NewTestClientForDebug() 112 | args := DescribeSecurityGroupAttributeArgs{ 113 | RegionId: common.Beijing, 114 | SecurityGroupId: TestSecurityGroupId, 115 | } 116 | attr, err := client.DescribeSecurityGroupAttribute(&args) 117 | if err != nil { 118 | t.Fatalf("Failed to describe securitygroup attribute %++v", err) 119 | } 120 | t.Logf("Security group attribute is %++v", attr) 121 | } 122 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/ecs/snapshots.go: -------------------------------------------------------------------------------- 1 | package ecs 2 | 3 | import ( 4 | "time" 5 | 6 | "github.com/denverdino/aliyungo/common" 7 | "github.com/denverdino/aliyungo/util" 8 | ) 9 | 10 | type DescribeSnapshotsArgs struct { 11 | RegionId common.Region 12 | InstanceId string 13 | DiskId string 14 | SnapshotIds []string //["s-xxxxxxxxx", "s-yyyyyyyyy", ..."s-zzzzzzzzz"] 15 | common.Pagination 16 | } 17 | 18 | // 19 | // You can read doc at http://docs.aliyun.com/#/pub/ecs/open-api/datatype&snapshottype 20 | type SnapshotType struct { 21 | SnapshotId string 22 | SnapshotName string 23 | Description string 24 | Progress string 25 | SourceDiskId string 26 | SourceDiskSize int 27 | SourceDiskType string //enum for System | Data 28 | ProductCode string 29 | Status string 30 | Usage string 31 | CreationTime util.ISO6801Time 32 | } 33 | 34 | type DescribeSnapshotsResponse struct { 35 | common.Response 36 | common.PaginationResult 37 | Snapshots struct { 38 | Snapshot []SnapshotType 39 | } 40 | } 41 | 42 | // DescribeSnapshots describe snapshots 43 | // 44 | // You can read doc at http://docs.aliyun.com/#/pub/ecs/open-api/snapshot&describesnapshots 45 | func (client *Client) DescribeSnapshots(args *DescribeSnapshotsArgs) (snapshots []SnapshotType, pagination *common.PaginationResult, err error) { 46 | response, err := client.DescribeSnapshotsWithRaw(args) 47 | if err != nil { 48 | return nil, nil, err 49 | } 50 | return response.Snapshots.Snapshot, &response.PaginationResult, nil 51 | 52 | } 53 | 54 | func (client *Client) DescribeSnapshotsWithRaw(args *DescribeSnapshotsArgs) (response *DescribeSnapshotsResponse, err error) { 55 | args.Validate() 56 | response = &DescribeSnapshotsResponse{} 57 | 58 | err = client.Invoke("DescribeSnapshots", args, response) 59 | 60 | if err != nil { 61 | return nil, err 62 | } 63 | return response, nil 64 | 65 | } 66 | 67 | type DeleteSnapshotArgs struct { 68 | SnapshotId string 69 | } 70 | 71 | type DeleteSnapshotResponse struct { 72 | common.Response 73 | } 74 | 75 | // DeleteSnapshot deletes snapshot 76 | // 77 | // You can read doc at http://docs.aliyun.com/#/pub/ecs/open-api/snapshot&deletesnapshot 78 | func (client *Client) DeleteSnapshot(snapshotId string) error { 79 | args := DeleteSnapshotArgs{SnapshotId: snapshotId} 80 | response := DeleteSnapshotResponse{} 81 | 82 | return client.Invoke("DeleteSnapshot", &args, &response) 83 | } 84 | 85 | type CreateSnapshotArgs struct { 86 | DiskId string 87 | SnapshotName string 88 | Description string 89 | ClientToken string 90 | } 91 | 92 | type CreateSnapshotResponse struct { 93 | common.Response 94 | SnapshotId string 95 | } 96 | 97 | // CreateSnapshot creates a new snapshot 98 | // 99 | // You can read doc at http://docs.aliyun.com/#/pub/ecs/open-api/snapshot&createsnapshot 100 | func (client *Client) CreateSnapshot(args *CreateSnapshotArgs) (snapshotId string, err error) { 101 | 102 | response := CreateSnapshotResponse{} 103 | 104 | err = client.Invoke("CreateSnapshot", args, &response) 105 | if err == nil { 106 | snapshotId = response.SnapshotId 107 | } 108 | return snapshotId, err 109 | } 110 | 111 | // Default timeout value for WaitForSnapShotReady method 112 | const SnapshotDefaultTimeout = 120 113 | 114 | // WaitForSnapShotReady waits for snapshot ready 115 | func (client *Client) WaitForSnapShotReady(regionId common.Region, snapshotId string, timeout int) error { 116 | if timeout <= 0 { 117 | timeout = SnapshotDefaultTimeout 118 | } 119 | for { 120 | args := DescribeSnapshotsArgs{ 121 | RegionId: regionId, 122 | SnapshotIds: []string{snapshotId}, 123 | } 124 | 125 | snapshots, _, err := client.DescribeSnapshots(&args) 126 | if err != nil { 127 | return err 128 | } 129 | if snapshots == nil || len(snapshots) == 0 { 130 | return common.GetClientErrorFromString("Not found") 131 | } 132 | if snapshots[0].Progress == "100%" { 133 | break 134 | } 135 | timeout = timeout - DefaultWaitForInterval 136 | if timeout <= 0 { 137 | return common.GetClientErrorFromString("Timeout") 138 | } 139 | time.Sleep(DefaultWaitForInterval * time.Second) 140 | } 141 | return nil 142 | } 143 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/ecs/snapshots_test.go: -------------------------------------------------------------------------------- 1 | package ecs 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestSnapshot(t *testing.T) { 8 | 9 | client := NewTestClient() 10 | 11 | instance, err := client.DescribeInstanceAttribute(TestInstanceId) 12 | if err != nil { 13 | t.Fatalf("Failed to DescribeInstanceAttribute for instance %s: %v", TestInstanceId, err) 14 | } 15 | 16 | args := DescribeSnapshotsArgs{} 17 | 18 | args.InstanceId = TestInstanceId 19 | args.RegionId = instance.RegionId 20 | snapshots, _, err := client.DescribeSnapshots(&args) 21 | 22 | if err != nil { 23 | t.Errorf("Failed to DescribeSnapshots for instance %s: %v", TestInstanceId, err) 24 | } 25 | 26 | for _, snapshot := range snapshots { 27 | t.Logf("Snapshot of instance %s: %++v", TestInstanceId, snapshot) 28 | } 29 | } 30 | 31 | func TestSnapshotCreationAndDeletion(t *testing.T) { 32 | if TestQuick { 33 | return 34 | } 35 | 36 | client := NewTestClient() 37 | 38 | instance, err := client.DescribeInstanceAttribute(TestInstanceId) 39 | if err != nil { 40 | t.Fatalf("Failed to DescribeInstanceAttribute for instance %s: %v", TestInstanceId, err) 41 | } 42 | 43 | //Describe disk monitor data 44 | diskArgs := DescribeDisksArgs{ 45 | InstanceId: TestInstanceId, 46 | RegionId: instance.RegionId, 47 | } 48 | 49 | disks, _, err := client.DescribeDisks(&diskArgs) 50 | if err != nil { 51 | t.Fatalf("Failed to DescribeDisks for instance %s: %v", TestInstanceId, err) 52 | } 53 | 54 | diskId := disks[0].DiskId 55 | 56 | args := CreateSnapshotArgs{ 57 | DiskId: diskId, 58 | SnapshotName: "My_Test_Snapshot", 59 | Description: "My Test Snapshot Description", 60 | ClientToken: client.GenerateClientToken(), 61 | } 62 | 63 | snapshotId, err := client.CreateSnapshot(&args) 64 | if err != nil { 65 | t.Errorf("Failed to CreateSnapshot for disk %s: %v", diskId, err) 66 | } 67 | client.WaitForSnapShotReady(instance.RegionId, snapshotId, 0) 68 | 69 | err = client.DeleteSnapshot(snapshotId) 70 | if err != nil { 71 | t.Errorf("Failed to DeleteSnapshot for disk %s: %v", diskId, err) 72 | } 73 | 74 | t.Logf("Snapshot %s is deleted successfully.", snapshotId) 75 | 76 | } 77 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/ecs/snat_entry.go: -------------------------------------------------------------------------------- 1 | package ecs 2 | 3 | import "github.com/denverdino/aliyungo/common" 4 | 5 | type CreateSnatEntryArgs struct { 6 | RegionId common.Region 7 | SnatTableId string 8 | SourceVSwitchId string 9 | SnatIp string 10 | } 11 | 12 | type CreateSnatEntryResponse struct { 13 | common.Response 14 | SnatEntryId string 15 | } 16 | 17 | type SnatEntrySetType struct { 18 | RegionId common.Region 19 | SnatEntryId string 20 | SnatIp string 21 | SnatTableId string 22 | SourceCIDR string 23 | SourceVSwitchId string 24 | Status string 25 | } 26 | 27 | type DescribeSnatTableEntriesArgs struct { 28 | RegionId common.Region 29 | SnatTableId string 30 | common.Pagination 31 | } 32 | 33 | type DescribeSnatTableEntriesResponse struct { 34 | common.Response 35 | common.PaginationResult 36 | SnatTableEntries struct { 37 | SnatTableEntry []SnatEntrySetType 38 | } 39 | } 40 | 41 | type ModifySnatEntryArgs struct { 42 | RegionId common.Region 43 | SnatTableId string 44 | SnatEntryId string 45 | SnatIp string 46 | } 47 | 48 | type ModifySnatEntryResponse struct { 49 | common.Response 50 | } 51 | 52 | type DeleteSnatEntryArgs struct { 53 | RegionId common.Region 54 | SnatTableId string 55 | SnatEntryId string 56 | } 57 | 58 | type DeleteSnatEntryResponse struct { 59 | common.Response 60 | } 61 | 62 | func (client *Client) CreateSnatEntry(args *CreateSnatEntryArgs) (resp *CreateSnatEntryResponse, err error) { 63 | response := CreateSnatEntryResponse{} 64 | err = client.Invoke("CreateSnatEntry", args, &response) 65 | if err != nil { 66 | return nil, err 67 | } 68 | return &response, err 69 | } 70 | 71 | func (client *Client) DescribeSnatTableEntries(args *DescribeSnatTableEntriesArgs) (snatTableEntries []SnatEntrySetType, 72 | pagination *common.PaginationResult, err error) { 73 | response, err := client.DescribeSnatTableEntriesWithRaw(args) 74 | if err != nil { 75 | return nil, nil, err 76 | } 77 | 78 | return response.SnatTableEntries.SnatTableEntry, &response.PaginationResult, nil 79 | } 80 | 81 | func (client *Client) DescribeSnatTableEntriesWithRaw(args *DescribeSnatTableEntriesArgs) ( response *DescribeSnatTableEntriesResponse, err error) { 82 | args.Validate() 83 | response = &DescribeSnatTableEntriesResponse{} 84 | 85 | err = client.Invoke("DescribeSnatTableEntries", args, response) 86 | 87 | if err != nil { 88 | return nil, err 89 | } 90 | 91 | return response, nil 92 | } 93 | 94 | func (client *Client) ModifySnatEntry(args *ModifySnatEntryArgs) error { 95 | response := ModifySnatEntryResponse{} 96 | return client.Invoke("ModifySnatEntry", args, &response) 97 | } 98 | 99 | func (client *Client) DeleteSnatEntry(args *DeleteSnatEntryArgs) error { 100 | response := DeleteSnatEntryResponse{} 101 | err := client.Invoke("DeleteSnatEntry", args, &response) 102 | return err 103 | } 104 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/ecs/snat_entry_test.go: -------------------------------------------------------------------------------- 1 | package ecs 2 | 3 | import "testing" 4 | 5 | func TestDescribeSnatTableEntry(t *testing.T) { 6 | 7 | client := NewTestClient() 8 | args := DescribeSnatTableEntriesArgs{ 9 | RegionId: "cn-beijing", 10 | SnatTableId: "stb-abc", 11 | } 12 | _, _, err := client.DescribeSnatTableEntries(&args) 13 | if err != nil { 14 | t.Fatalf("Failed to DescribeBandwidthPackages: %v", err) 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/ecs/ssh_key_pair.go: -------------------------------------------------------------------------------- 1 | package ecs 2 | 3 | import ( 4 | "github.com/denverdino/aliyungo/common" 5 | ) 6 | 7 | type CreateKeyPairArgs struct { 8 | RegionId common.Region 9 | KeyPairName string 10 | } 11 | 12 | type CreateKeyPairResponse struct { 13 | common.Response 14 | KeyPairName string 15 | KeyPairFingerPrint string 16 | PrivateKeyBody string 17 | } 18 | 19 | // CreateKeyPair creates keypair 20 | // 21 | // You can read doc at https://help.aliyun.com/document_detail/51771.html?spm=5176.doc51775.6.910.cedjfr 22 | func (client *Client) CreateKeyPair(args *CreateKeyPairArgs) (resp *CreateKeyPairResponse,err error) { 23 | response := CreateKeyPairResponse{} 24 | err = client.Invoke("CreateKeyPair", args, &response) 25 | if err != nil { 26 | return nil, err 27 | } 28 | return &response, err 29 | } 30 | 31 | type ImportKeyPairArgs struct { 32 | RegionId common.Region 33 | PublicKeyBody string 34 | KeyPairName string 35 | } 36 | 37 | type ImportKeyPairResponse struct { 38 | common.Response 39 | KeyPairName string 40 | KeyPairFingerPrint string 41 | } 42 | 43 | // ImportKeyPair import keypair 44 | // 45 | // You can read doc at https://help.aliyun.com/document_detail/51774.html?spm=5176.doc51771.6.911.BicQq2 46 | func (client *Client) ImportKeyPair(args *ImportKeyPairArgs) (resp *ImportKeyPairResponse,err error) { 47 | response := ImportKeyPairResponse{} 48 | err = client.Invoke("ImportKeyPair", args, &response) 49 | if err != nil { 50 | return nil, err 51 | } 52 | return &response, err 53 | } 54 | 55 | type DescribeKeyPairsArgs struct { 56 | RegionId common.Region 57 | KeyPairFingerPrint string 58 | KeyPairName string 59 | common.Pagination 60 | } 61 | 62 | type KeyPairItemType struct { 63 | KeyPairName string 64 | KeyPairFingerPrint string 65 | } 66 | 67 | type DescribeKeyPairsResponse struct { 68 | common.Response 69 | common.PaginationResult 70 | RegionId common.Region 71 | KeyPairs struct { 72 | KeyPair []KeyPairItemType 73 | } 74 | } 75 | 76 | // DescribeKeyPairs describe keypairs 77 | // 78 | // You can read doc at https://help.aliyun.com/document_detail/51773.html?spm=5176.doc51774.6.912.lyE0iX 79 | func (client *Client) DescribeKeyPairs(args *DescribeKeyPairsArgs) (KeyPairs []KeyPairItemType, pagination *common.PaginationResult, err error) { 80 | response, err := client.DescribeKeyPairsWithRaw(args) 81 | if err != nil { 82 | return nil, nil, err 83 | } 84 | 85 | return response.KeyPairs.KeyPair, &response.PaginationResult, err 86 | } 87 | 88 | func (client *Client) DescribeKeyPairsWithRaw(args *DescribeKeyPairsArgs) (response *DescribeKeyPairsResponse, err error) { 89 | response = &DescribeKeyPairsResponse{} 90 | 91 | err = client.Invoke("DescribeKeyPairs", args, response) 92 | 93 | if err != nil { 94 | return nil, err 95 | } 96 | 97 | return response, err 98 | } 99 | 100 | type AttachKeyPairArgs struct { 101 | RegionId common.Region 102 | KeyPairName string 103 | InstanceIds string 104 | } 105 | 106 | // AttachKeyPair keypars to instances 107 | // 108 | // You can read doc at https://help.aliyun.com/document_detail/51775.html?spm=5176.doc51773.6.913.igEem4 109 | func (client *Client) AttachKeyPair(args *AttachKeyPairArgs) (err error) { 110 | response := common.Response{} 111 | err = client.Invoke("AttachKeyPair", args, &response) 112 | if err != nil { 113 | return err 114 | } 115 | return nil 116 | } 117 | 118 | type DetachKeyPairArgs struct { 119 | RegionId common.Region 120 | KeyPairName string 121 | InstanceIds string 122 | } 123 | 124 | // DetachKeyPair keyparis from instances 125 | // 126 | // You can read doc at https://help.aliyun.com/document_detail/51776.html?spm=5176.doc51775.6.914.DJ7Gmq 127 | func (client *Client) DetachKeyPair(args *DetachKeyPairArgs) (err error) { 128 | response := common.Response{} 129 | err = client.Invoke("DetachKeyPair", args, &response) 130 | if err != nil { 131 | return err 132 | } 133 | return nil 134 | } 135 | 136 | type DeleteKeyPairsArgs struct { 137 | RegionId common.Region 138 | KeyPairNames string 139 | } 140 | 141 | // DeleteKeyPairs delete keypairs 142 | // 143 | // You can read doc at https://help.aliyun.com/document_detail/51772.html?spm=5176.doc51776.6.915.Qqcv2Q 144 | func (client *Client) DeleteKeyPairs(args *DeleteKeyPairsArgs) (err error) { 145 | response := common.Response{} 146 | err = client.Invoke("DeleteKeyPairs", args, &response) 147 | if err != nil { 148 | return err 149 | } 150 | return nil 151 | } 152 | 153 | 154 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/ecs/tags.go: -------------------------------------------------------------------------------- 1 | package ecs 2 | 3 | import "github.com/denverdino/aliyungo/common" 4 | 5 | type TagResourceType string 6 | 7 | const ( 8 | TagResourceImage = TagResourceType("image") 9 | TagResourceInstance = TagResourceType("instance") 10 | TagResourceSnapshot = TagResourceType("snapshot") 11 | TagResourceDisk = TagResourceType("disk") 12 | ) 13 | 14 | type AddTagsArgs struct { 15 | ResourceId string 16 | ResourceType TagResourceType //image, instance, snapshot or disk 17 | RegionId common.Region 18 | Tag map[string]string 19 | } 20 | 21 | type AddTagsResponse struct { 22 | common.Response 23 | } 24 | 25 | // AddTags Add tags to resource 26 | // 27 | // You can read doc at http://docs.aliyun.com/#/pub/ecs/open-api/tags&addtags 28 | func (client *Client) AddTags(args *AddTagsArgs) error { 29 | response := AddTagsResponse{} 30 | err := client.Invoke("AddTags", args, &response) 31 | return err 32 | } 33 | 34 | type RemoveTagsArgs struct { 35 | ResourceId string 36 | ResourceType TagResourceType //image, instance, snapshot or disk 37 | RegionId common.Region 38 | Tag map[string]string 39 | } 40 | 41 | type RemoveTagsResponse struct { 42 | common.Response 43 | } 44 | 45 | // RemoveTags remove tags to resource 46 | // 47 | // You can read doc at http://docs.aliyun.com/#/pub/ecs/open-api/tags&removetags 48 | func (client *Client) RemoveTags(args *RemoveTagsArgs) error { 49 | response := RemoveTagsResponse{} 50 | err := client.Invoke("RemoveTags", args, &response) 51 | return err 52 | } 53 | 54 | type ResourceItemType struct { 55 | ResourceId string 56 | ResourceType TagResourceType 57 | RegionId common.Region 58 | } 59 | 60 | type DescribeResourceByTagsArgs struct { 61 | ResourceType TagResourceType //image, instance, snapshot or disk 62 | RegionId common.Region 63 | Tag map[string]string 64 | common.Pagination 65 | } 66 | 67 | type DescribeResourceByTagsResponse struct { 68 | common.Response 69 | common.PaginationResult 70 | Resources struct { 71 | Resource []ResourceItemType 72 | } 73 | } 74 | 75 | // DescribeResourceByTags describe resource by tags 76 | // 77 | // You can read doc at http://docs.aliyun.com/#/pub/ecs/open-api/tags&describeresourcebytags 78 | func (client *Client) DescribeResourceByTags(args *DescribeResourceByTagsArgs) (resources []ResourceItemType, pagination *common.PaginationResult, err error) { 79 | response, err := client.DescribeResourceByTagsWithRaw(args) 80 | if err != nil { 81 | return nil, nil, err 82 | } 83 | return response.Resources.Resource, &response.PaginationResult, nil 84 | } 85 | 86 | func (client *Client) DescribeResourceByTagsWithRaw(args *DescribeResourceByTagsArgs) (response *DescribeResourceByTagsResponse, err error) { 87 | args.Validate() 88 | response = &DescribeResourceByTagsResponse{} 89 | err = client.Invoke("DescribeResourceByTags", args, response) 90 | if err != nil { 91 | return nil, err 92 | } 93 | return response, nil 94 | } 95 | 96 | type TagItemType struct { 97 | TagKey string 98 | TagValue string 99 | } 100 | 101 | type DescribeTagsArgs struct { 102 | RegionId common.Region 103 | ResourceType TagResourceType //image, instance, snapshot or disk 104 | ResourceId string 105 | Tag map[string]string 106 | common.Pagination 107 | } 108 | 109 | type DescribeTagsResponse struct { 110 | common.Response 111 | common.PaginationResult 112 | Tags struct { 113 | Tag []TagItemType 114 | } 115 | } 116 | 117 | // DescribeResourceByTags describe resource by tags 118 | // 119 | // You can read doc at http://docs.aliyun.com/#/pub/ecs/open-api/tags&describeresourcebytags 120 | func (client *Client) DescribeTags(args *DescribeTagsArgs) (tags []TagItemType, pagination *common.PaginationResult, err error) { 121 | args.Validate() 122 | response := DescribeTagsResponse{} 123 | err = client.Invoke("DescribeTags", args, &response) 124 | if err != nil { 125 | return nil, nil, err 126 | } 127 | return response.Tags.Tag, &response.PaginationResult, nil 128 | } 129 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/ecs/tags_test.go: -------------------------------------------------------------------------------- 1 | package ecs 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | var TestTags = map[string]string{ 8 | "test": "api", 9 | "gosdk": "1.0", 10 | } 11 | 12 | func TestAddTags(t *testing.T) { 13 | client := NewTestClient() 14 | 15 | instance, err := client.DescribeInstanceAttribute(TestInstanceId) 16 | if err != nil { 17 | t.Fatalf("Failed to DescribeInstanceAttribute for instance %s: %v", TestInstanceId, err) 18 | } 19 | 20 | args := AddTagsArgs{ 21 | RegionId: instance.RegionId, 22 | ResourceId: instance.InstanceId, 23 | ResourceType: TagResourceInstance, 24 | Tag: TestTags, 25 | } 26 | err = client.AddTags(&args) 27 | 28 | if err != nil { 29 | t.Errorf("Failed to AddTags for instance %s: %v", TestInstanceId, err) 30 | } 31 | 32 | } 33 | 34 | func TestDescribeResourceByTags(t *testing.T) { 35 | client := NewTestClient() 36 | 37 | instance, err := client.DescribeInstanceAttribute(TestInstanceId) 38 | if err != nil { 39 | t.Fatalf("Failed to DescribeInstanceAttribute for instance %s: %v", TestInstanceId, err) 40 | } 41 | 42 | args := DescribeResourceByTagsArgs{ 43 | RegionId: instance.RegionId, 44 | ResourceType: TagResourceInstance, 45 | Tag: TestTags, 46 | } 47 | result, _, err := client.DescribeResourceByTags(&args) 48 | 49 | if err != nil { 50 | t.Errorf("Failed to DescribeResourceByTags: %v", err) 51 | } else { 52 | t.Logf("result: %v", result) 53 | } 54 | } 55 | 56 | func TestDescribeTags(t *testing.T) { 57 | client := NewTestClient() 58 | 59 | instance, err := client.DescribeInstanceAttribute(TestInstanceId) 60 | if err != nil { 61 | t.Fatalf("Failed to DescribeInstanceAttribute for instance %s: %v", TestInstanceId, err) 62 | } 63 | 64 | args := DescribeTagsArgs{ 65 | RegionId: instance.RegionId, 66 | ResourceType: TagResourceInstance, 67 | } 68 | result, _, err := client.DescribeTags(&args) 69 | 70 | if err != nil { 71 | t.Errorf("Failed to DescribeTags: %v", err) 72 | } else { 73 | t.Logf("result: %v", result) 74 | } 75 | } 76 | 77 | func TestRemoveTags(t *testing.T) { 78 | 79 | client := NewTestClient() 80 | 81 | instance, err := client.DescribeInstanceAttribute(TestInstanceId) 82 | if err != nil { 83 | t.Fatalf("Failed to DescribeInstanceAttribute for instance %s: %v", TestInstanceId, err) 84 | } 85 | 86 | args := RemoveTagsArgs{ 87 | RegionId: instance.RegionId, 88 | ResourceId: instance.InstanceId, 89 | ResourceType: TagResourceInstance, 90 | Tag: TestTags, 91 | } 92 | err = client.RemoveTags(&args) 93 | 94 | if err != nil { 95 | t.Errorf("Failed to RemoveTags for instance %s: %v", TestInstanceId, err) 96 | } 97 | 98 | } 99 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/ecs/vpcs.go: -------------------------------------------------------------------------------- 1 | package ecs 2 | 3 | import ( 4 | "time" 5 | 6 | "github.com/denverdino/aliyungo/common" 7 | "github.com/denverdino/aliyungo/util" 8 | ) 9 | 10 | type CreateVpcArgs struct { 11 | RegionId common.Region 12 | CidrBlock string //192.168.0.0/16 or 172.16.0.0/16 (default) 13 | VpcName string 14 | Description string 15 | ClientToken string 16 | } 17 | 18 | type CreateVpcResponse struct { 19 | common.Response 20 | VpcId string 21 | VRouterId string 22 | RouteTableId string 23 | } 24 | 25 | // CreateVpc creates Virtual Private Cloud 26 | // 27 | // You can read doc at http://docs.aliyun.com/#/pub/ecs/open-api/vpc&createvpc 28 | func (client *Client) CreateVpc(args *CreateVpcArgs) (resp *CreateVpcResponse, err error) { 29 | response := CreateVpcResponse{} 30 | err = client.Invoke("CreateVpc", args, &response) 31 | if err != nil { 32 | return nil, err 33 | } 34 | return &response, err 35 | } 36 | 37 | type DeleteVpcArgs struct { 38 | VpcId string 39 | } 40 | 41 | type DeleteVpcResponse struct { 42 | common.Response 43 | } 44 | 45 | // DeleteVpc deletes Virtual Private Cloud 46 | // 47 | // You can read doc at http://docs.aliyun.com/#/pub/ecs/open-api/vpc&deletevpc 48 | func (client *Client) DeleteVpc(vpcId string) error { 49 | args := DeleteVpcArgs{ 50 | VpcId: vpcId, 51 | } 52 | response := DeleteVpcResponse{} 53 | return client.Invoke("DeleteVpc", &args, &response) 54 | } 55 | 56 | type VpcStatus string 57 | 58 | const ( 59 | VpcStatusPending = VpcStatus("Pending") 60 | VpcStatusAvailable = VpcStatus("Available") 61 | ) 62 | 63 | type DescribeVpcsArgs struct { 64 | VpcId string 65 | RegionId common.Region 66 | common.Pagination 67 | } 68 | 69 | // 70 | // You can read doc at http://docs.aliyun.com/#/pub/ecs/open-api/datatype&vpcsettype 71 | type VpcSetType struct { 72 | VpcId string 73 | RegionId common.Region 74 | Status VpcStatus // enum Pending | Available 75 | VpcName string 76 | VSwitchIds struct { 77 | VSwitchId []string 78 | } 79 | CidrBlock string 80 | VRouterId string 81 | Description string 82 | IsDefault bool 83 | CreationTime util.ISO6801Time 84 | } 85 | 86 | type DescribeVpcsResponse struct { 87 | common.Response 88 | common.PaginationResult 89 | Vpcs struct { 90 | Vpc []VpcSetType 91 | } 92 | } 93 | 94 | // DescribeInstanceStatus describes instance status 95 | // 96 | // You can read doc at http://docs.aliyun.com/#/pub/ecs/open-api/vpc&describevpcs 97 | func (client *Client) DescribeVpcs(args *DescribeVpcsArgs) (vpcs []VpcSetType, pagination *common.PaginationResult, err error) { 98 | response, err := client.DescribeVpcsWithRaw(args) 99 | if err != nil { 100 | return nil, nil, err 101 | } 102 | 103 | return response.Vpcs.Vpc, &response.PaginationResult, nil 104 | } 105 | 106 | func (client *Client) DescribeVpcsWithRaw(args *DescribeVpcsArgs) (response *DescribeVpcsResponse, err error) { 107 | args.Validate() 108 | response = &DescribeVpcsResponse{} 109 | 110 | err = client.Invoke("DescribeVpcs", args, response) 111 | if err != nil { 112 | return nil, err 113 | } 114 | 115 | return response, err 116 | } 117 | 118 | type ModifyVpcAttributeArgs struct { 119 | VpcId string 120 | VpcName string 121 | Description string 122 | } 123 | 124 | type ModifyVpcAttributeResponse struct { 125 | common.Response 126 | } 127 | 128 | // ModifyVpcAttribute modifies attribute of Virtual Private Cloud 129 | // 130 | // You can read doc at http://docs.aliyun.com/#/pub/ecs/open-api/vpc&modifyvpcattribute 131 | func (client *Client) ModifyVpcAttribute(args *ModifyVpcAttributeArgs) error { 132 | response := ModifyVpcAttributeResponse{} 133 | return client.Invoke("ModifyVpcAttribute", args, &response) 134 | } 135 | 136 | // WaitForInstance waits for instance to given status 137 | func (client *Client) WaitForVpcAvailable(regionId common.Region, vpcId string, timeout int) error { 138 | if timeout <= 0 { 139 | timeout = DefaultTimeout 140 | } 141 | args := DescribeVpcsArgs{ 142 | RegionId: regionId, 143 | VpcId: vpcId, 144 | } 145 | for { 146 | vpcs, _, err := client.DescribeVpcs(&args) 147 | if err != nil { 148 | return err 149 | } 150 | if len(vpcs) > 0 && vpcs[0].Status == VpcStatusAvailable { 151 | break 152 | } 153 | timeout = timeout - DefaultWaitForInterval 154 | if timeout <= 0 { 155 | return common.GetClientErrorFromString("Timeout") 156 | } 157 | time.Sleep(DefaultWaitForInterval * time.Second) 158 | } 159 | return nil 160 | } 161 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/ecs/vrouters.go: -------------------------------------------------------------------------------- 1 | package ecs 2 | 3 | import ( 4 | "github.com/denverdino/aliyungo/common" 5 | "github.com/denverdino/aliyungo/util" 6 | ) 7 | 8 | type DescribeVRoutersArgs struct { 9 | VRouterId string 10 | RegionId common.Region 11 | common.Pagination 12 | } 13 | 14 | // 15 | // You can read doc at http://docs.aliyun.com/#/pub/ecs/open-api/datatype&vroutersettype 16 | type VRouterSetType struct { 17 | VRouterId string 18 | RegionId common.Region 19 | VpcId string 20 | RouteTableIds struct { 21 | RouteTableId []string 22 | } 23 | VRouterName string 24 | Description string 25 | CreationTime util.ISO6801Time 26 | } 27 | 28 | type DescribeVRoutersResponse struct { 29 | common.Response 30 | common.PaginationResult 31 | VRouters struct { 32 | VRouter []VRouterSetType 33 | } 34 | } 35 | 36 | // DescribeVRouters describes Virtual Routers 37 | // 38 | // You can read doc at http://docs.aliyun.com/#/pub/ecs/open-api/vrouter&describevrouters 39 | func (client *Client) DescribeVRouters(args *DescribeVRoutersArgs) (vrouters []VRouterSetType, pagination *common.PaginationResult, err error) { 40 | response, err := client.DescribeVRoutersWithRaw(args) 41 | if err == nil { 42 | return response.VRouters.VRouter, &response.PaginationResult, nil 43 | } 44 | 45 | return nil, nil, err 46 | } 47 | 48 | func (client *Client) DescribeVRoutersWithRaw(args *DescribeVRoutersArgs) (response *DescribeVRoutersResponse, err error) { 49 | args.Validate() 50 | response = &DescribeVRoutersResponse{} 51 | 52 | err = client.Invoke("DescribeVRouters", args, response) 53 | 54 | if err == nil { 55 | return response, nil 56 | } 57 | 58 | return nil, err 59 | } 60 | 61 | type ModifyVRouterAttributeArgs struct { 62 | VRouterId string 63 | VRouterName string 64 | Description string 65 | } 66 | 67 | type ModifyVRouterAttributeResponse struct { 68 | common.Response 69 | } 70 | 71 | // ModifyVRouterAttribute modifies attribute of Virtual Router 72 | // 73 | // You can read doc at http://docs.aliyun.com/#/pub/ecs/open-api/vrouter&modifyvrouterattribute 74 | func (client *Client) ModifyVRouterAttribute(args *ModifyVRouterAttributeArgs) error { 75 | response := ModifyVRouterAttributeResponse{} 76 | return client.Invoke("ModifyVRouterAttribute", args, &response) 77 | } 78 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/ecs/vrouters_test.go: -------------------------------------------------------------------------------- 1 | package ecs 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/denverdino/aliyungo/common" 7 | ) 8 | 9 | func testVRouter(t *testing.T, client *Client, regionId common.Region, vpcId string, vrouterId string, instanceId string) { 10 | 11 | newName := "My_Aliyun_test_VRouter" 12 | 13 | modifyArgs := ModifyVRouterAttributeArgs{ 14 | VRouterId: vrouterId, 15 | VRouterName: newName, 16 | Description: newName, 17 | } 18 | 19 | err := client.ModifyVRouterAttribute(&modifyArgs) 20 | if err != nil { 21 | t.Errorf("Failed to modify VRouters: %v", err) 22 | } 23 | 24 | args := DescribeVRoutersArgs{ 25 | VRouterId: vrouterId, 26 | RegionId: regionId, 27 | } 28 | 29 | vrouters, _, err := client.DescribeVRouters(&args) 30 | if err != nil { 31 | t.Errorf("Failed to describe VRouters: %v", err) 32 | } 33 | t.Logf("VRouters: %++v", vrouters) 34 | if vrouters[0].VRouterName != newName { 35 | t.Errorf("Failed to modify VRouters with new name: %s", newName) 36 | } 37 | 38 | testRouteTable(t, client, regionId, vpcId, vrouterId, vrouters[0].RouteTableIds.RouteTableId[0], instanceId) 39 | 40 | } 41 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/ecs/vswitches.go: -------------------------------------------------------------------------------- 1 | package ecs 2 | 3 | import ( 4 | "time" 5 | 6 | "github.com/denverdino/aliyungo/common" 7 | "github.com/denverdino/aliyungo/util" 8 | ) 9 | 10 | type CreateVSwitchArgs struct { 11 | ZoneId string 12 | CidrBlock string 13 | VpcId string 14 | VSwitchName string 15 | Description string 16 | ClientToken string 17 | } 18 | 19 | type CreateVSwitchResponse struct { 20 | common.Response 21 | VSwitchId string 22 | } 23 | 24 | // CreateVSwitch creates Virtual Switch 25 | // 26 | // You can read doc at http://docs.aliyun.com/#/pub/ecs/open-api/vswitch&createvswitch 27 | func (client *Client) CreateVSwitch(args *CreateVSwitchArgs) (vswitchId string, err error) { 28 | response := CreateVSwitchResponse{} 29 | err = client.Invoke("CreateVSwitch", args, &response) 30 | if err != nil { 31 | return "", err 32 | } 33 | return response.VSwitchId, err 34 | } 35 | 36 | type DeleteVSwitchArgs struct { 37 | VSwitchId string 38 | } 39 | 40 | type DeleteVSwitchResponse struct { 41 | common.Response 42 | } 43 | 44 | // DeleteVSwitch deletes Virtual Switch 45 | // 46 | // You can read doc at http://docs.aliyun.com/#/pub/ecs/open-api/vswitch&deletevswitch 47 | func (client *Client) DeleteVSwitch(VSwitchId string) error { 48 | args := DeleteVSwitchArgs{ 49 | VSwitchId: VSwitchId, 50 | } 51 | response := DeleteVSwitchResponse{} 52 | return client.Invoke("DeleteVSwitch", &args, &response) 53 | } 54 | 55 | type DescribeVSwitchesArgs struct { 56 | RegionId common.Region 57 | VpcId string 58 | VSwitchId string 59 | ZoneId string 60 | common.Pagination 61 | } 62 | 63 | type VSwitchStatus string 64 | 65 | const ( 66 | VSwitchStatusPending = VSwitchStatus("Pending") 67 | VSwitchStatusAvailable = VSwitchStatus("Available") 68 | ) 69 | 70 | // 71 | // You can read doc at http://docs.aliyun.com/#/pub/ecs/open-api/datatype&vswitchsettype 72 | type VSwitchSetType struct { 73 | VSwitchId string 74 | VpcId string 75 | Status VSwitchStatus // enum Pending | Available 76 | CidrBlock string 77 | ZoneId string 78 | AvailableIpAddressCount int 79 | Description string 80 | VSwitchName string 81 | IsDefault bool 82 | CreationTime util.ISO6801Time 83 | } 84 | 85 | type DescribeVSwitchesResponse struct { 86 | common.Response 87 | common.PaginationResult 88 | VSwitches struct { 89 | VSwitch []VSwitchSetType 90 | } 91 | } 92 | 93 | // DescribeVSwitches describes Virtual Switches 94 | // 95 | // You can read doc at http://docs.aliyun.com/#/pub/ecs/open-api/vswitch&describevswitches 96 | func (client *Client) DescribeVSwitches(args *DescribeVSwitchesArgs) (vswitches []VSwitchSetType, pagination *common.PaginationResult, err error) { 97 | args.Validate() 98 | response, err := client.DescribeVSwitchesWithRaw(args) 99 | if err == nil { 100 | return response.VSwitches.VSwitch, &response.PaginationResult, nil 101 | } 102 | 103 | return nil, nil, err 104 | } 105 | 106 | func (client *Client) DescribeVSwitchesWithRaw(args *DescribeVSwitchesArgs) (response *DescribeVSwitchesResponse, err error) { 107 | args.Validate() 108 | response = &DescribeVSwitchesResponse{} 109 | 110 | err = client.Invoke("DescribeVSwitches", args, &response) 111 | 112 | if err == nil { 113 | return response, nil 114 | } 115 | 116 | return nil, err 117 | } 118 | 119 | type ModifyVSwitchAttributeArgs struct { 120 | VSwitchId string 121 | VSwitchName string 122 | Description string 123 | } 124 | 125 | type ModifyVSwitchAttributeResponse struct { 126 | common.Response 127 | } 128 | 129 | // ModifyVSwitchAttribute modifies attribute of Virtual Private Cloud 130 | // 131 | // You can read doc at http://docs.aliyun.com/#/pub/ecs/open-api/vswitch&modifyvswitchattribute 132 | func (client *Client) ModifyVSwitchAttribute(args *ModifyVSwitchAttributeArgs) error { 133 | response := ModifyVSwitchAttributeResponse{} 134 | return client.Invoke("ModifyVSwitchAttribute", args, &response) 135 | } 136 | 137 | // WaitForVSwitchAvailable waits for VSwitch to given status 138 | func (client *Client) WaitForVSwitchAvailable(vpcId string, vswitchId string, timeout int) error { 139 | if timeout <= 0 { 140 | timeout = DefaultTimeout 141 | } 142 | args := DescribeVSwitchesArgs{ 143 | VpcId: vpcId, 144 | VSwitchId: vswitchId, 145 | } 146 | for { 147 | vswitches, _, err := client.DescribeVSwitches(&args) 148 | if err != nil { 149 | return err 150 | } 151 | if len(vswitches) == 0 { 152 | return common.GetClientErrorFromString("Not found") 153 | } 154 | if vswitches[0].Status == VSwitchStatusAvailable { 155 | break 156 | } 157 | timeout = timeout - DefaultWaitForInterval 158 | if timeout <= 0 { 159 | return common.GetClientErrorFromString("Timeout") 160 | } 161 | time.Sleep(DefaultWaitForInterval * time.Second) 162 | } 163 | return nil 164 | } 165 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/ecs/vswitches_test.go: -------------------------------------------------------------------------------- 1 | package ecs 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/denverdino/aliyungo/common" 7 | ) 8 | 9 | func testCreateVSwitch(t *testing.T, client *Client, regionId common.Region, zoneId string, vpcId string, vrouterId string) (vSwitchId string, err error) { 10 | 11 | args := CreateVSwitchArgs{ 12 | ZoneId: zoneId, 13 | CidrBlock: "172.16.10.0/24", 14 | VpcId: vpcId, 15 | VSwitchName: "AliyunGo_test_vSwitch", 16 | Description: "AliyunGo test vSwitch", 17 | ClientToken: client.GenerateClientToken(), 18 | } 19 | 20 | vSwitchId, err = client.CreateVSwitch(&args) 21 | 22 | if err != nil { 23 | t.Errorf("Failed to create VSwitch: %v", err) 24 | return "", err 25 | } 26 | 27 | t.Logf("VSwitch is created successfully: %s", vSwitchId) 28 | 29 | err = client.WaitForVSwitchAvailable(vpcId, vSwitchId, 60) 30 | if err != nil { 31 | t.Errorf("Failed to wait VSwitch %s to available: %v", vSwitchId, err) 32 | } 33 | 34 | newName := args.VSwitchName + "_update" 35 | modifyArgs := ModifyVSwitchAttributeArgs{ 36 | VSwitchId: vSwitchId, 37 | VSwitchName: newName, 38 | Description: newName, 39 | } 40 | 41 | err = client.ModifyVSwitchAttribute(&modifyArgs) 42 | if err != nil { 43 | t.Errorf("Failed to modify VSwitch %s: %v", vSwitchId, err) 44 | } 45 | 46 | argsDescribe := DescribeVSwitchesArgs{ 47 | VpcId: vpcId, 48 | VSwitchId: vSwitchId, 49 | } 50 | 51 | vswitches, _, err := client.DescribeVSwitches(&argsDescribe) 52 | if err != nil { 53 | t.Errorf("Failed to describe VSwitch: %v", err) 54 | } 55 | 56 | if vswitches[0].VSwitchName != newName { 57 | t.Errorf("Failed to modify VSwitch with new name: %s", newName) 58 | } 59 | 60 | t.Logf("VSwitch is : %++v", vswitches) 61 | 62 | return vSwitchId, err 63 | } 64 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/ecs/zones.go: -------------------------------------------------------------------------------- 1 | package ecs 2 | 3 | import "github.com/denverdino/aliyungo/common" 4 | 5 | type ResourceType string 6 | 7 | const ( 8 | ResourceTypeInstance = ResourceType("Instance") 9 | ResourceTypeDisk = ResourceType("Disk") 10 | ResourceTypeVSwitch = ResourceType("VSwitch") 11 | ResourceTypeIOOptimizedInstance = ResourceType("IoOptimized") 12 | ) 13 | 14 | // The sub-item of the type AvailableResourcesType 15 | type SupportedResourceType string 16 | 17 | const ( 18 | SupportedInstanceType = SupportedResourceType("supportedInstanceType") 19 | SupportedInstanceTypeFamily = SupportedResourceType("supportedInstanceTypeFamily") 20 | SupportedInstanceGeneration = SupportedResourceType("supportedInstanceGeneration") 21 | SupportedSystemDiskCategory = SupportedResourceType("supportedSystemDiskCategory") 22 | SupportedDataDiskCategory = SupportedResourceType("supportedDataDiskCategory") 23 | SupportedNetworkCategory = SupportedResourceType("supportedNetworkCategory") 24 | 25 | ) 26 | // 27 | // You can read doc at https://help.aliyun.com/document_detail/25670.html?spm=5176.doc25640.2.1.J24zQt 28 | type ResourcesInfoType struct { 29 | ResourcesInfo []AvailableResourcesType 30 | } 31 | // Because the sub-item of AvailableResourcesType starts with supported and golang struct cann't refer them, this uses map to parse ResourcesInfo 32 | type AvailableResourcesType struct { 33 | IoOptimized bool 34 | NetworkTypes map[SupportedResourceType][]string 35 | InstanceGenerations map[SupportedResourceType][]string 36 | InstanceTypeFamilies map[SupportedResourceType][]string 37 | InstanceTypes map[SupportedResourceType][]string 38 | SystemDiskCategories map[SupportedResourceType][]DiskCategory 39 | DataDiskCategories map[SupportedResourceType][]DiskCategory 40 | } 41 | 42 | type DescribeZonesArgs struct { 43 | RegionId common.Region 44 | } 45 | 46 | // 47 | // You can read doc at http://docs.aliyun.com/#/pub/ecs/open-api/datatype&availableresourcecreationtype 48 | type AvailableResourceCreationType struct { 49 | ResourceTypes []ResourceType //enum for Instance, Disk, VSwitch 50 | } 51 | 52 | // 53 | // You can read doc at http://docs.aliyun.com/#/pub/ecs/open-api/datatype&availablediskcategoriestype 54 | type AvailableDiskCategoriesType struct { 55 | DiskCategories []DiskCategory //enum for cloud, ephemeral, ephemeral_ssd 56 | } 57 | 58 | type AvailableInstanceTypesType struct { 59 | InstanceTypes []string 60 | } 61 | 62 | // 63 | // You can read doc at http://docs.aliyun.com/#/pub/ecs/open-api/datatype&zonetype 64 | type ZoneType struct { 65 | ZoneId string 66 | LocalName string 67 | AvailableResources ResourcesInfoType 68 | AvailableInstanceTypes AvailableInstanceTypesType 69 | AvailableResourceCreation AvailableResourceCreationType 70 | AvailableDiskCategories AvailableDiskCategoriesType 71 | } 72 | 73 | type DescribeZonesResponse struct { 74 | common.Response 75 | Zones struct { 76 | Zone []ZoneType 77 | } 78 | } 79 | 80 | // DescribeZones describes zones 81 | func (client *Client) DescribeZones(regionId common.Region) (zones []ZoneType, err error) { 82 | response, err := client.DescribeZonesWithRaw(regionId) 83 | if err == nil { 84 | return response.Zones.Zone, nil 85 | } 86 | 87 | return []ZoneType{}, err 88 | } 89 | 90 | func (client *Client) DescribeZonesWithRaw(regionId common.Region) (response *DescribeZonesResponse, err error) { 91 | args := DescribeZonesArgs{ 92 | RegionId: regionId, 93 | } 94 | response = &DescribeZonesResponse{} 95 | 96 | err = client.Invoke("DescribeZones", &args, response) 97 | 98 | if err == nil { 99 | return response, nil 100 | } 101 | 102 | return nil, err 103 | } 104 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/location/client.go: -------------------------------------------------------------------------------- 1 | package location 2 | 3 | import ( 4 | "os" 5 | 6 | "github.com/denverdino/aliyungo/common" 7 | ) 8 | 9 | type Client struct { 10 | common.Client 11 | } 12 | 13 | const ( 14 | // LocationDefaultEndpoint is the default API endpoint of Location services 15 | LocationDefaultEndpoint = "https://location.aliyuncs.com" 16 | LocationAPIVersion = "2015-06-12" 17 | ) 18 | 19 | // NewClient creates a new instance of Location client 20 | func NewClient(accessKeyId, accessKeySecret string) *Client { 21 | endpoint := os.Getenv("LOCATION_ENDPOINT") 22 | if endpoint == "" { 23 | endpoint = LocationDefaultEndpoint 24 | } 25 | return NewClientWithEndpoint(endpoint, accessKeyId, accessKeySecret) 26 | } 27 | 28 | func NewClientWithEndpoint(endpoint string, accessKeyId, accessKeySecret string) *Client { 29 | client := &Client{} 30 | client.Init(endpoint, LocationAPIVersion, accessKeyId, accessKeySecret) 31 | return client 32 | } 33 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/location/endpoints.go: -------------------------------------------------------------------------------- 1 | package location 2 | 3 | import ( 4 | "github.com/denverdino/aliyungo/common" 5 | ) 6 | 7 | type DescribeEndpointArgs struct { 8 | Id common.Region 9 | ServiceCode string 10 | Type string 11 | } 12 | 13 | type EndpointItem struct { 14 | Protocols struct { 15 | Protocols []string 16 | } 17 | Type string 18 | Namespace string 19 | Id common.Region 20 | SerivceCode string 21 | Endpoint string 22 | } 23 | 24 | type DescribeEndpointResponse struct { 25 | common.Response 26 | EndpointItem 27 | } 28 | 29 | func (client *Client) DescribeEndpoint(args *DescribeEndpointArgs) (*DescribeEndpointResponse, error) { 30 | response := &DescribeEndpointResponse{} 31 | err := client.Invoke("DescribeEndpoint", args, response) 32 | if err != nil { 33 | return nil, err 34 | } 35 | return response, err 36 | } 37 | 38 | type DescribeEndpointsArgs struct { 39 | Id common.Region 40 | ServiceCode string 41 | Type string 42 | } 43 | 44 | type DescribeEndpointsResponse struct { 45 | common.Response 46 | Endpoints struct { 47 | Endpoint []EndpointItem 48 | } 49 | } 50 | 51 | func (client *Client) DescribeEndpoints(args *DescribeEndpointsArgs) (*DescribeEndpointsResponse, error) { 52 | response := &DescribeEndpointsResponse{} 53 | err := client.Invoke("DescribeEndpoints", args, response) 54 | if err != nil { 55 | return nil, err 56 | } 57 | return response, err 58 | } 59 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/location/regions.go: -------------------------------------------------------------------------------- 1 | package location 2 | 3 | import ( 4 | "github.com/denverdino/aliyungo/common" 5 | ) 6 | 7 | type DescribeRegionsArgs struct { 8 | Password string 9 | } 10 | 11 | type DescribeRegionsResponse struct { 12 | common.Response 13 | 14 | TotalCount int 15 | RegionIds struct { 16 | RegionIds []string 17 | } 18 | } 19 | 20 | func (client *Client) DescribeRegions(args *DescribeRegionsArgs) (*DescribeRegionsResponse, error) { 21 | response := &DescribeRegionsResponse{} 22 | err := client.Invoke("DescribeRegions", args, response) 23 | if err != nil { 24 | return nil, err 25 | } 26 | return response, err 27 | } 28 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/location/services.go: -------------------------------------------------------------------------------- 1 | package location 2 | 3 | import ( 4 | "github.com/denverdino/aliyungo/common" 5 | ) 6 | 7 | type DescribeServicesArgs struct { 8 | RegionId common.Region 9 | } 10 | 11 | type DescribeServicesResponse struct { 12 | common.Response 13 | 14 | TotalCount int 15 | Services struct { 16 | Services []string 17 | } 18 | } 19 | 20 | func (client *Client) DescribeServices(args *DescribeServicesArgs) (*DescribeServicesResponse, error) { 21 | response := &DescribeServicesResponse{} 22 | err := client.Invoke("DescribeServices", args, response) 23 | if err != nil { 24 | return nil, err 25 | } 26 | return response, err 27 | } 28 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/nas/CreateAccessRule.go: -------------------------------------------------------------------------------- 1 | package nas 2 | 3 | type CreateAccessRuleRequest struct { 4 | AccessGroupName string 5 | SourceCidrIp string 6 | Policy string 7 | SquashType string 8 | Priority string 9 | Version string 10 | RegionId string 11 | } 12 | 13 | type CreateAccessRuleResponse struct { 14 | Code string 15 | } 16 | 17 | func (client *Client) CreateAccessRule(args *CreateAccessRuleRequest) (resp CreateAccessRuleResponse, err error) { 18 | response := CreateAccessRuleResponse{} 19 | args.Version = VERSION 20 | args.Policy = DEFAULT_POLICY 21 | args.SquashType = DEFAULT_SQUASHTYPE 22 | args.Priority = DEFAULT_PRIORITY 23 | 24 | err = client.Invoke("CreateAccessRule", args, &response) 25 | return response, err 26 | } 27 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/nas/CreateFileSystem.go: -------------------------------------------------------------------------------- 1 | package nas 2 | 3 | type CreateFileSystemRequest struct { 4 | ZoneId string 5 | Version string 6 | RegionId string 7 | } 8 | 9 | type CreateFileSystemResponse struct { 10 | FileSystemName string 11 | RequestId string 12 | Code string 13 | } 14 | 15 | func (client *Client) CreateFileSystem(args *CreateFileSystemRequest) (resp CreateFileSystemResponse, err error) { 16 | response := CreateFileSystemResponse{} 17 | args.Version = VERSION 18 | 19 | err = client.Invoke("CreateFileSystem", args, &response) 20 | return response, err 21 | } 22 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/nas/CreateMountTarget.go: -------------------------------------------------------------------------------- 1 | package nas 2 | 3 | type CreateMountTargetRequest struct { 4 | FileSystemName string 5 | AccessGroupName string 6 | NetworkType string 7 | VpcId string 8 | VSwitchId string 9 | Version string 10 | RegionId string 11 | } 12 | 13 | type CreateMountTargetResponse struct { 14 | Code string 15 | } 16 | 17 | func (client *Client) CreateMountTarget(args *CreateMountTargetRequest) (resp CreateMountTargetResponse, err error) { 18 | response := CreateMountTargetResponse{} 19 | args.Version = VERSION 20 | 21 | err = client.Invoke("CreateMountTarget", args, &response) 22 | return response, err 23 | } 24 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/nas/DescribeAccessRules.go: -------------------------------------------------------------------------------- 1 | package nas 2 | 3 | type DescribeAccessRulesRequest struct { 4 | AccessGroupName string 5 | Version string 6 | RegionId string 7 | } 8 | 9 | type DescribeAccessRulesResponse struct { 10 | Rules []Rule 11 | Code string 12 | } 13 | 14 | type Rule struct { 15 | Priority string 16 | SourceCidrIp string 17 | SquashType string 18 | RuleId string 19 | Policy string 20 | } 21 | 22 | func (client *Client) DescribeAccessRules(args *DescribeAccessRulesRequest) (resp DescribeAccessRulesResponse, err error) { 23 | response := DescribeAccessRulesResponse{} 24 | args.Version = VERSION 25 | err = client.Invoke("DescribeAccessRules", args, &response) 26 | return response, err 27 | } 28 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/nas/DescribeFileSystems.go: -------------------------------------------------------------------------------- 1 | package nas 2 | 3 | type DescribeFileSystemsRequest struct { 4 | FileSystemName string 5 | Version string 6 | RegionId string 7 | } 8 | 9 | type DescribeFileSystemsResponse struct { 10 | FileSystems []FileSystem 11 | Code string 12 | } 13 | 14 | type FileSystem struct { 15 | CreateTime uint64 16 | MountTargetCount uint64 17 | PackageId string 18 | FileSystemName string 19 | FileSystemType string 20 | MeteredSize uint64 21 | FileSystemDesc string 22 | QuotaSize uint64 23 | ZoneId string 24 | } 25 | 26 | func (client *Client) DescribeFileSystems(args *DescribeFileSystemsRequest) (resp DescribeFileSystemsResponse, err error) { 27 | response := DescribeFileSystemsResponse{} 28 | args.Version = VERSION 29 | err = client.Invoke("DescribeFileSystems", args, &response) 30 | return response, err 31 | } 32 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/nas/DescribeMountTargets.go: -------------------------------------------------------------------------------- 1 | package nas 2 | 3 | type DescribeMountTargetsRequest struct { 4 | FileSystemName string 5 | Version string 6 | RegionId string 7 | } 8 | 9 | type DescribeMountTargetsResponse struct { 10 | MountTargets []MountTarget 11 | Code string 12 | } 13 | 14 | type MountTarget struct { 15 | AccessGroupName string 16 | MountTargetIp string 17 | NetworkType string 18 | Status string 19 | MountTargetId string 20 | VpcId string 21 | VSwitchId string 22 | DomainName string 23 | CloudInstId string 24 | } 25 | 26 | func (client *Client) DescribeMountTargets(args *DescribeMountTargetsRequest) (resp DescribeMountTargetsResponse, err error) { 27 | response := DescribeMountTargetsResponse{} 28 | args.Version = VERSION 29 | err = client.Invoke("DescribeMountTargets", args, &response) 30 | return response, err 31 | } 32 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/nas/client.go: -------------------------------------------------------------------------------- 1 | package nas 2 | 3 | import ( 4 | "github.com/denverdino/aliyungo/common" 5 | ) 6 | 7 | const ( 8 | VERSION = "2016-02-29" 9 | END_POINT = "https://nasservice-inner.aliyuncs.com" 10 | DEFAULT_POLICY = "readwrite" 11 | DEFAULT_SQUASHTYPE = "no_squash" 12 | DEFAULT_PRIORITY = "1" 13 | ) 14 | 15 | type Client struct { 16 | common.Client 17 | } 18 | 19 | // NewClient creates a new instance of NAS client 20 | func NewClient(accessKeyId, accessKeySecret string) *Client { 21 | client := &Client{} 22 | client.Init(END_POINT, VERSION, accessKeyId, accessKeySecret) 23 | return client 24 | } 25 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/ram/account.go: -------------------------------------------------------------------------------- 1 | package ram 2 | 3 | type UserRequest struct { 4 | User 5 | } 6 | 7 | type UserResponse struct { 8 | RamCommonResponse 9 | User User 10 | } 11 | 12 | type UpdateUserRequest struct { 13 | UserName string 14 | NewUserName string 15 | NewDisplayName string 16 | NewMobilePhone string 17 | NewEmail string 18 | NewComments string 19 | } 20 | 21 | type ListUserRequest struct { 22 | Marker string 23 | MaxItems int8 24 | } 25 | 26 | type ListUserResponse struct { 27 | RamCommonResponse 28 | IsTruncated bool 29 | Marker string 30 | Users struct { 31 | User []User 32 | } 33 | } 34 | 35 | func (client *RamClient) CreateUser(user UserRequest) (UserResponse, error) { 36 | var userResponse UserResponse 37 | err := client.Invoke("CreateUser", user, &userResponse) 38 | if err != nil { 39 | return UserResponse{}, err 40 | } 41 | return userResponse, nil 42 | } 43 | 44 | func (client *RamClient) GetUser(userQuery UserQueryRequest) (UserResponse, error) { 45 | var userResponse UserResponse 46 | err := client.Invoke("GetUser", userQuery, &userResponse) 47 | if err != nil { 48 | return UserResponse{}, nil 49 | } 50 | return userResponse, nil 51 | } 52 | 53 | func (client *RamClient) UpdateUser(newUser UpdateUserRequest) (UserResponse, error) { 54 | var userResponse UserResponse 55 | err := client.Invoke("UpdateUser", newUser, &userResponse) 56 | if err != nil { 57 | return UserResponse{}, err 58 | } 59 | return userResponse, nil 60 | } 61 | 62 | func (client *RamClient) DeleteUser(userQuery UserQueryRequest) (RamCommonResponse, error) { 63 | var commonResp RamCommonResponse 64 | err := client.Invoke("DeleteUser", userQuery, &commonResp) 65 | if err != nil { 66 | return RamCommonResponse{}, err 67 | } 68 | return commonResp, nil 69 | } 70 | 71 | func (client *RamClient) ListUsers(listParams ListUserRequest) (ListUserResponse, error) { 72 | var userList ListUserResponse 73 | err := client.Invoke("ListUsers", listParams, &userList) 74 | if err != nil { 75 | return ListUserResponse{}, err 76 | } 77 | return userList, nil 78 | } 79 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/ram/account_test.go: -------------------------------------------------------------------------------- 1 | package ram 2 | 3 | import ( 4 | "strconv" 5 | "testing" 6 | "time" 7 | ) 8 | 9 | var ( 10 | offset int64 = 100 11 | username = strconv.FormatInt(time.Now().Unix(), 10) 12 | user = UserRequest{ 13 | User: User{ 14 | UserName: username, 15 | DisplayName: "unit_test_account", 16 | MobilePhone: "13500000000", 17 | Email: "no-reply@alibaba-inc.com", 18 | Comments: "no any comments", 19 | }, 20 | } 21 | newUserName = strconv.FormatInt((time.Now().Unix() + offset), 10) 22 | NewUser = UpdateUserRequest{ 23 | UserName: username, 24 | NewUserName: newUserName, 25 | NewDisplayName: "unit_test_account_new", 26 | } 27 | listParams = ListUserRequest{} 28 | userQuery = UserQueryRequest{UserName: username} 29 | ) 30 | 31 | func TestCreateUser(t *testing.T) { 32 | client := NewTestClient() 33 | resp, err := client.CreateUser(user) 34 | if err != nil { 35 | t.Errorf("Failed to CreateUser %v", err) 36 | } 37 | t.Logf("pass CreateUser %v", resp) 38 | } 39 | 40 | func TestGetUser(t *testing.T) { 41 | client := NewTestClient() 42 | resp, err := client.GetUser(userQuery) 43 | if err != nil { 44 | t.Errorf("Failed to GetUser %v", err) 45 | } 46 | t.Logf("pass GetUser %v", resp) 47 | } 48 | 49 | func TestUpdateUsernewUser(t *testing.T) { 50 | client := NewTestClient() 51 | resp, err := client.UpdateUser(NewUser) 52 | if err != nil { 53 | t.Errorf("Failed to UpdateUser %v", err) 54 | } 55 | t.Logf("pass UpdateUser %v", resp) 56 | } 57 | 58 | func TestListUser(t *testing.T) { 59 | client := NewTestClient() 60 | resp, err := client.ListUsers(listParams) 61 | if err != nil { 62 | t.Errorf("Failed to ListUser %v", err) 63 | } 64 | t.Logf("pass ListUser %v", resp) 65 | } 66 | 67 | func TestDeleteUser(t *testing.T) { 68 | client := NewTestClient() 69 | userQuery.UserName = newUserName 70 | resp, err := client.DeleteUser(userQuery) 71 | if err != nil { 72 | t.Errorf("Failed to DeletUser %v", err) 73 | } 74 | t.Logf("pass DeletUser %v", resp) 75 | } 76 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/ram/ak.go: -------------------------------------------------------------------------------- 1 | package ram 2 | 3 | /* 4 | CreateAccessKey() 5 | UpdateAccessKey() 6 | DeleteAccessKey() 7 | ListAccessKeys() 8 | */ 9 | type State string 10 | 11 | type AccessKeyResponse struct { 12 | RamCommonResponse 13 | AccessKey AccessKey 14 | } 15 | 16 | type UpdateAccessKeyRequest struct { 17 | UserAccessKeyId string 18 | Status State 19 | UserName string 20 | } 21 | 22 | type AccessKeyListResponse struct { 23 | RamCommonResponse 24 | AccessKeys struct { 25 | AccessKey []AccessKey 26 | } 27 | } 28 | 29 | func (client *RamClient) CreateAccessKey(userQuery UserQueryRequest) (AccessKeyResponse, error) { 30 | var accesskeyResp AccessKeyResponse 31 | err := client.Invoke("CreateAccessKey", userQuery, &accesskeyResp) 32 | if err != nil { 33 | return AccessKeyResponse{}, err 34 | } 35 | return accesskeyResp, nil 36 | } 37 | 38 | func (client *RamClient) UpdateAccessKey(accessKeyRequest UpdateAccessKeyRequest) (RamCommonResponse, error) { 39 | var commonResp RamCommonResponse 40 | err := client.Invoke("UpdateAccessKey", accessKeyRequest, &commonResp) 41 | if err != nil { 42 | return RamCommonResponse{}, err 43 | } 44 | return commonResp, nil 45 | } 46 | 47 | func (client *RamClient) DeleteAccessKey(accessKeyRequest UpdateAccessKeyRequest) (RamCommonResponse, error) { 48 | var commonResp RamCommonResponse 49 | err := client.Invoke("DeleteAccessKey", accessKeyRequest, &commonResp) 50 | if err != nil { 51 | return RamCommonResponse{}, err 52 | } 53 | return commonResp, nil 54 | } 55 | 56 | func (client *RamClient) ListAccessKeys(userQuery UserQueryRequest) (AccessKeyListResponse, error) { 57 | var accessKeyListResp AccessKeyListResponse 58 | err := client.Invoke("ListAccessKeys", userQuery, &accessKeyListResp) 59 | if err != nil { 60 | return AccessKeyListResponse{}, err 61 | } 62 | return accessKeyListResp, nil 63 | } 64 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/ram/ak_test.go: -------------------------------------------------------------------------------- 1 | package ram 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | var ( 8 | ram_ak_username string 9 | accessKeyId string 10 | status State 11 | ) 12 | 13 | func TestCreateAccessKey(t *testing.T) { 14 | var ramUser User 15 | client := NewTestClient() 16 | listParams := ListUserRequest{} 17 | listUserResp, err := client.ListUsers(listParams) 18 | if err != nil { 19 | t.Errorf("Failed to list user %v", err) 20 | } 21 | if len(listUserResp.Users.User) == 0 { 22 | //TODO create user 23 | userResp, err := client.CreateUser(user) 24 | ramUser = userResp.User 25 | if err != nil { 26 | t.Errorf("Failed to create user %v", err) 27 | } 28 | } else { 29 | ramUser = listUserResp.Users.User[0] 30 | } 31 | //TODO 添加到公共变量中 32 | ram_ak_username = ramUser.UserName 33 | 34 | userQuery := UserQueryRequest{UserName: ram_ak_username} 35 | accessKeyResponse, err := client.CreateAccessKey(userQuery) 36 | //加入到公共变量中 37 | accessKeyId = accessKeyResponse.AccessKey.AccessKeyId 38 | status = accessKeyResponse.AccessKey.Status 39 | 40 | if err != nil { 41 | t.Errorf("Failed to create AccessKey %v", err) 42 | } 43 | t.Logf("pass create AccessKey %v", accessKeyResponse) 44 | } 45 | 46 | func TestUpdateAccessKey(t *testing.T) { 47 | client := NewTestClient() 48 | updateAccessKeyRequest := UpdateAccessKeyRequest{ 49 | UserAccessKeyId: accessKeyId, 50 | UserName: ram_ak_username, 51 | } 52 | if status == Active { 53 | updateAccessKeyRequest.Status = Inactive 54 | } else { 55 | updateAccessKeyRequest.Status = Active 56 | } 57 | 58 | accessKeyResponse, err := client.UpdateAccessKey(updateAccessKeyRequest) 59 | if err != nil { 60 | t.Errorf("Failed to UpdateAccessKey %v", err) 61 | } 62 | t.Logf("pass UpdateAccessKey %v", accessKeyResponse) 63 | } 64 | 65 | func TestListAccessKeys(t *testing.T) { 66 | client := NewTestClient() 67 | userQuery := UserQueryRequest{UserName: ram_ak_username} 68 | resp, err := client.ListAccessKeys(userQuery) 69 | if err != nil { 70 | t.Errorf("Failed to list ListAccessKeys %v", err) 71 | } 72 | t.Logf("pass ListAccessKeys %v", resp) 73 | } 74 | 75 | func TestDeleteAccessKey(t *testing.T) { 76 | client := NewTestClient() 77 | accessKeyRequest := UpdateAccessKeyRequest{ 78 | UserAccessKeyId: accessKeyId, 79 | UserName: ram_ak_username, 80 | } 81 | var commonResp RamCommonResponse 82 | commonResp, err := client.DeleteAccessKey(accessKeyRequest) 83 | if err != nil { 84 | t.Errorf("Failed to TestDeleteAccessKey %v", err) 85 | } 86 | t.Logf("pass DeleteAccessKey %v", commonResp) 87 | } 88 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/ram/api.go: -------------------------------------------------------------------------------- 1 | package ram 2 | 3 | /* 4 | ringtail 2016/1/19 5 | All RAM apis provided 6 | */ 7 | 8 | type RamClientInterface interface { 9 | //ram user 10 | CreateUser(user UserRequest) (UserResponse, error) 11 | GetUser(userQuery UserQueryRequest) (UserResponse, error) 12 | UpdateUser(newUser UpdateUserRequest) (UserResponse, error) 13 | DeleteUser(userQuery UserQueryRequest) (RamCommonResponse, error) 14 | ListUsers(listParams ListUserRequest) (ListUserResponse, error) 15 | 16 | //ram login profile 17 | CreateLoginProfile(req ProfileRequest) (ProfileResponse, error) 18 | GetLoginProfile(req UserQueryRequest) (ProfileResponse, error) 19 | DeleteLoginProfile(req UserQueryRequest) (RamCommonResponse, error) 20 | UpdateLoginProfile(req ProfileRequest) (ProfileResponse, error) 21 | 22 | //ram ak 23 | CreateAccessKey(userQuery UserQueryRequest) (AccessKeyResponse, error) 24 | UpdateAccessKey(accessKeyRequest UpdateAccessKeyRequest) (RamCommonResponse, error) 25 | DeleteAccessKey(accessKeyRequest UpdateAccessKeyRequest) (RamCommonResponse, error) 26 | ListAccessKeys(userQuery UserQueryRequest) (AccessKeyListResponse, error) 27 | 28 | //ram mfa 29 | CreateVirtualMFADevice(req MFARequest) (MFAResponse, error) 30 | ListVirtualMFADevices() (MFAListResponse, error) 31 | DeleteVirtualMFADevice(req MFADeleteRequest) (RamCommonResponse, error) 32 | BindMFADevice(req MFABindRequest) (RamCommonResponse, error) 33 | UnbindMFADevice(req UserQueryRequest) (MFAUserResponse, error) 34 | GetUserMFAInfo(req UserQueryRequest) (MFAUserResponse, error) 35 | 36 | //ram group 37 | CreateGroup(req GroupRequest) (GroupResponse, error) 38 | GetGroup(req GroupQueryRequest) (GroupResponse, error) 39 | UpdateGroup(req GroupUpdateRequest) (GroupResponse, error) 40 | ListGroup(req GroupListRequest) (GroupListResponse, error) 41 | DeleteGroup(req GroupQueryRequest) (RamCommonResponse, error) 42 | AddUserToGroup(req UserRelateGroupRequest) (RamCommonResponse, error) 43 | RemoveUserFromGroup(req UserRelateGroupRequest) (RamCommonResponse, error) 44 | ListGroupsForUser(req UserQueryRequest) (GroupListResponse, error) 45 | ListUsersForGroup(req GroupQueryRequest) (ListUserResponse, error) 46 | 47 | CreateRole(role RoleRequest) (RoleResponse, error) 48 | GetRole(roleQuery RoleQueryRequest) (RoleResponse, error) 49 | UpdateRole(newRole UpdateRoleRequest) (RoleResponse, error) 50 | ListRoles() (ListRoleResponse, error) 51 | DeleteRole(roleQuery RoleQueryRequest) (RamCommonResponse, error) 52 | 53 | //DONE policy 54 | CreatePolicy(policyReq PolicyRequest) (PolicyResponse, error) 55 | GetPolicy(policyReq PolicyRequest) (PolicyResponse, error) 56 | DeletePolicy(policyReq PolicyRequest) (RamCommonResponse, error) 57 | ListPolicies(policyQuery PolicyQueryRequest) (PolicyQueryResponse, error) 58 | ListPoliciesForUser(userQuery UserQueryRequest) (PolicyListResponse, error) 59 | 60 | //ram policy version 61 | CreatePolicyVersion(policyReq PolicyRequest) (PolicyVersionResponse, error) 62 | GetPolicyVersion(policyReq PolicyRequest) (PolicyVersionResponse, error) 63 | GetPolicyVersionNew(policyReq PolicyRequest) (PolicyVersionResponseNew, error) 64 | DeletePolicyVersion(policyReq PolicyRequest) (RamCommonResponse, error) 65 | ListPolicyVersions(policyReq PolicyRequest) (PolicyVersionResponse, error) 66 | ListPolicyVersionsNew(policyReq PolicyRequest) (PolicyVersionsResponse, error) 67 | AttachPolicyToUser(attachPolicyRequest AttachPolicyRequest) (RamCommonResponse, error) 68 | DetachPolicyFromUser(attachPolicyRequest AttachPolicyRequest) (RamCommonResponse, error) 69 | ListEntitiesForPolicy(policyReq PolicyRequest) (PolicyListEntitiesResponse, error) 70 | SetDefaultPolicyVersion(policyReq PolicyRequest) (RamCommonResponse, error) 71 | ListPoliciesForGroup(groupQuery GroupQueryRequest) (PolicyListResponse, error) 72 | AttachPolicyToGroup(attachPolicyRequest AttachPolicyToGroupRequest) (RamCommonResponse, error) 73 | DetachPolicyFromGroup(attachPolicyRequest AttachPolicyToGroupRequest) (RamCommonResponse, error) 74 | AttachPolicyToRole(attachPolicyRequest AttachPolicyToRoleRequest) (RamCommonResponse, error) 75 | DetachPolicyFromRole(attachPolicyRequest AttachPolicyToRoleRequest) (RamCommonResponse, error) 76 | ListPoliciesForRole(roleQuery RoleQueryRequest) (PolicyListResponse, error) 77 | 78 | //ram security 79 | SetAccountAlias(accountAlias AccountAliasRequest) (RamCommonResponse, error) 80 | GetAccountAlias() (AccountAliasResponse, error) 81 | ClearAccountAlias() (RamCommonResponse, error) 82 | SetPasswordPolicy(passwordPolicy PasswordPolicyRequest) (PasswordPolicyResponse, error) 83 | GetPasswordPolicy() (PasswordPolicyResponse, error) 84 | } 85 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/ram/client.go: -------------------------------------------------------------------------------- 1 | package ram 2 | 3 | import ( 4 | "os" 5 | 6 | "github.com/denverdino/aliyungo/common" 7 | ) 8 | 9 | const ( 10 | // RAMDefaultEndpoint is the default API endpoint of RAM services 11 | RAMDefaultEndpoint = "https://ram.aliyuncs.com" 12 | RAMAPIVersion = "2015-05-01" 13 | ) 14 | 15 | type RamClient struct { 16 | common.Client 17 | } 18 | 19 | func NewClient(accessKeyId string, accessKeySecret string) RamClientInterface { 20 | return NewClientWithSecurityToken(accessKeyId, accessKeySecret, "") 21 | } 22 | 23 | func NewClientWithSecurityToken(accessKeyId string, accessKeySecret string, securityToken string) RamClientInterface { 24 | endpoint := os.Getenv("RAM_ENDPOINT") 25 | if endpoint == "" { 26 | endpoint = RAMDefaultEndpoint 27 | } 28 | 29 | return NewClientWithEndpointAndSecurityToken(endpoint, accessKeyId, accessKeySecret, securityToken) 30 | } 31 | 32 | func NewClientWithEndpoint(endpoint string, accessKeyId string, accessKeySecret string) RamClientInterface { 33 | return NewClientWithEndpointAndSecurityToken(endpoint, accessKeyId, accessKeySecret, "") 34 | } 35 | 36 | func NewClientWithEndpointAndSecurityToken(endpoint string, accessKeyId string, accessKeySecret string, securityToken string) RamClientInterface { 37 | client := &RamClient{} 38 | client.WithEndpoint(endpoint). 39 | WithVersion(RAMAPIVersion). 40 | WithAccessKeyId(accessKeyId). 41 | WithAccessKeySecret(accessKeySecret). 42 | WithSecurityToken(securityToken). 43 | InitClient() 44 | return client 45 | } 46 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/ram/client_test.go: -------------------------------------------------------------------------------- 1 | package ram 2 | 3 | import ( 4 | "os" 5 | ) 6 | 7 | /* 8 | Set your AccessKeyId and AccessKeySecret in env 9 | simply use the command below 10 | AccessKeyId=YourAccessKeyId AccessKeySecret=YourAccessKeySecret go test 11 | */ 12 | var ( 13 | AccessKeyId = os.Getenv("AccessKeyId") 14 | AccessKeySecret = os.Getenv("AccessKeySecret") 15 | ) 16 | 17 | func NewTestClient() RamClientInterface { 18 | client := NewClient(AccessKeyId, AccessKeySecret) 19 | return client 20 | } 21 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/ram/error.go: -------------------------------------------------------------------------------- 1 | package ram 2 | 3 | //common errors 4 | var () 5 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/ram/group.go: -------------------------------------------------------------------------------- 1 | package ram 2 | 3 | type GroupRequest struct { 4 | Group 5 | } 6 | 7 | type GroupQueryRequest struct { 8 | GroupName string 9 | } 10 | 11 | type GroupUpdateRequest struct { 12 | GroupName string 13 | NewGroupName string 14 | NewComments string 15 | } 16 | 17 | type GroupListRequest struct { 18 | Marker string 19 | MaxItems int8 20 | } 21 | 22 | type UserRelateGroupRequest struct { 23 | UserName string 24 | GroupName string 25 | } 26 | 27 | type GroupResponse struct { 28 | RamCommonResponse 29 | Group Group 30 | } 31 | 32 | type GroupListResponse struct { 33 | RamCommonResponse 34 | IsTruncated bool 35 | Marker string 36 | Groups struct { 37 | Group []Group 38 | } 39 | } 40 | 41 | func (client *RamClient) CreateGroup(req GroupRequest) (GroupResponse, error) { 42 | var resp GroupResponse 43 | err := client.Invoke("CreateGroup", req, &resp) 44 | if err != nil { 45 | return GroupResponse{}, err 46 | } 47 | return resp, nil 48 | } 49 | 50 | func (client *RamClient) GetGroup(req GroupQueryRequest) (GroupResponse, error) { 51 | var resp GroupResponse 52 | err := client.Invoke("GetGroup", req, &resp) 53 | if err != nil { 54 | return GroupResponse{}, err 55 | } 56 | return resp, nil 57 | } 58 | 59 | func (client *RamClient) UpdateGroup(req GroupUpdateRequest) (GroupResponse, error) { 60 | var resp GroupResponse 61 | err := client.Invoke("UpdateGroup", req, &resp) 62 | if err != nil { 63 | return GroupResponse{}, err 64 | } 65 | return resp, nil 66 | } 67 | 68 | func (client *RamClient) ListGroup(req GroupListRequest) (GroupListResponse, error) { 69 | var resp GroupListResponse 70 | err := client.Invoke("ListGroups", req, &resp) 71 | if err != nil { 72 | return GroupListResponse{}, err 73 | } 74 | return resp, nil 75 | } 76 | 77 | func (client *RamClient) DeleteGroup(req GroupQueryRequest) (RamCommonResponse, error) { 78 | var resp RamCommonResponse 79 | err := client.Invoke("DeleteGroup", req, &resp) 80 | if err != nil { 81 | return RamCommonResponse{}, err 82 | } 83 | return resp, nil 84 | } 85 | 86 | func (client *RamClient) AddUserToGroup(req UserRelateGroupRequest) (RamCommonResponse, error) { 87 | var resp RamCommonResponse 88 | err := client.Invoke("AddUserToGroup", req, &resp) 89 | if err != nil { 90 | return RamCommonResponse{}, err 91 | } 92 | return resp, nil 93 | } 94 | 95 | func (client *RamClient) RemoveUserFromGroup(req UserRelateGroupRequest) (RamCommonResponse, error) { 96 | var resp RamCommonResponse 97 | err := client.Invoke("RemoveUserFromGroup", req, &resp) 98 | if err != nil { 99 | return RamCommonResponse{}, err 100 | } 101 | return resp, nil 102 | } 103 | 104 | func (client *RamClient) ListGroupsForUser(req UserQueryRequest) (GroupListResponse, error) { 105 | var resp GroupListResponse 106 | err := client.Invoke("ListGroupsForUser", req, &resp) 107 | if err != nil { 108 | return GroupListResponse{}, err 109 | } 110 | return resp, nil 111 | } 112 | 113 | func (client *RamClient) ListUsersForGroup(req GroupQueryRequest) (ListUserResponse, error) { 114 | var resp ListUserResponse 115 | err := client.Invoke("ListUsersForGroup", req, &resp) 116 | if err != nil { 117 | return ListUserResponse{}, err 118 | } 119 | return resp, nil 120 | } 121 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/ram/group_test.go: -------------------------------------------------------------------------------- 1 | package ram 2 | 3 | import ( 4 | "testing" 5 | "time" 6 | "strconv" 7 | ) 8 | 9 | var ( 10 | groupName = strconv.FormatInt(time.Now().Unix(), 10) 11 | group = GroupRequest{ 12 | Group: Group{ 13 | GroupName: groupName, 14 | Comments: "no any comments", 15 | }, 16 | } 17 | groupQuery = GroupQueryRequest{GroupName: groupName} 18 | newGroupName = strconv.FormatInt(time.Now().Unix()+100, 10) 19 | groupNew = GroupUpdateRequest{ 20 | GroupName: groupName, 21 | NewGroupName: newGroupName, 22 | NewComments: "no any comments new", 23 | } 24 | uName string 25 | ) 26 | 27 | func TestCreateGroup(t *testing.T) { 28 | client := NewTestClient() 29 | resp, err := client.CreateGroup(group) 30 | if err != nil { 31 | t.Errorf("Failed to CreateGroup %v", err) 32 | } 33 | t.Logf("pass CreateGroup %v", resp) 34 | } 35 | 36 | func TestGetGroup(t *testing.T) { 37 | client := NewTestClient() 38 | resp, err := client.GetGroup(groupQuery) 39 | if err != nil { 40 | t.Errorf("Failed to GetGroup %v", err) 41 | } 42 | t.Logf("pass GetGroup %v", resp) 43 | } 44 | 45 | func TestUpdateGroup(t *testing.T) { 46 | client := NewTestClient() 47 | resp, err := client.UpdateGroup(groupNew) 48 | if err != nil { 49 | t.Errorf("Failed to UpdateGroup %v", err) 50 | } 51 | t.Logf("pass UpdateGroup %v", resp) 52 | } 53 | 54 | func TestListGroup(t *testing.T) { 55 | client := NewTestClient() 56 | resp, err := client.ListGroup(GroupListRequest{}) 57 | if err != nil { 58 | t.Errorf("Failed to ListGroup %v", err) 59 | } 60 | t.Logf("pass ListGroup %v", resp) 61 | } 62 | 63 | func TestAddUserToGroup(t *testing.T) { 64 | client := NewTestClient() 65 | listParams := ListUserRequest{} 66 | resp, err := client.ListUsers(listParams) 67 | if err != nil { 68 | t.Errorf("Failed to ListUser %v", err) 69 | return 70 | } 71 | uName = resp.Users.User[0].UserName 72 | addUserToGroupReq := UserRelateGroupRequest{ 73 | UserName: uName, 74 | GroupName: newGroupName, 75 | } 76 | response, err := client.AddUserToGroup(addUserToGroupReq) 77 | if err != nil { 78 | t.Errorf("Failed to AddUserToGroup %v", err) 79 | } 80 | t.Logf("pass AddUserToGroup %v", response) 81 | } 82 | 83 | func TestRemoveUserFromGroup(t *testing.T) { 84 | client := NewTestClient() 85 | removeUserToGroupReq := UserRelateGroupRequest{ 86 | UserName: uName, 87 | GroupName: newGroupName, 88 | } 89 | response, err := client.RemoveUserFromGroup(removeUserToGroupReq) 90 | if err != nil { 91 | t.Errorf("Failed to RemoveUserFromGroup %v", err) 92 | } 93 | t.Logf("pass RemoveUserFromGroup %v", response) 94 | } 95 | 96 | func TestListGroupsForUser(t *testing.T) { 97 | client := NewTestClient() 98 | response, err := client.ListGroupsForUser(UserQueryRequest{UserName: uName}) 99 | if err != nil { 100 | t.Errorf("Failed to ListGroupsForUser %v", err) 101 | } 102 | t.Logf("pass ListGroupsForUser %v", response) 103 | } 104 | 105 | func TestListUsersForGroup(t *testing.T) { 106 | client := NewTestClient() 107 | groupQuery.GroupName = newGroupName 108 | response, err := client.ListUsersForGroup(groupQuery) 109 | if err != nil { 110 | t.Errorf("Failed to ListUsersForGroup %v", err) 111 | } 112 | t.Logf("pass ListUsersForGroup %v", response) 113 | } 114 | 115 | func TestDeleteGroup(t *testing.T) { 116 | client := NewTestClient() 117 | groupQuery.GroupName = newGroupName 118 | resp, err := client.DeleteGroup(groupQuery) 119 | if err != nil { 120 | t.Errorf("Failed to DeleteGroup %v", err) 121 | } 122 | t.Logf("pass DeleteGroup %v", resp) 123 | } 124 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/ram/mfa.go: -------------------------------------------------------------------------------- 1 | package ram 2 | 3 | type MFARequest struct { 4 | VirtualMFADeviceName string 5 | } 6 | 7 | type MFADeleteRequest struct { 8 | MFADevice 9 | } 10 | 11 | type MFABindRequest struct { 12 | SerialNumber string 13 | UserName string 14 | AuthenticationCode1 string 15 | AuthenticationCode2 string 16 | } 17 | 18 | type MFAResponse struct { 19 | RamCommonResponse 20 | VirtualMFADevice VirtualMFADevice 21 | } 22 | 23 | type MFAListResponse struct { 24 | RamCommonResponse 25 | VirtualMFADevices struct { 26 | VirtualMFADevice []VirtualMFADevice 27 | } 28 | } 29 | 30 | type MFAUserResponse struct { 31 | RamCommonResponse 32 | MFADevice MFADevice 33 | } 34 | 35 | func (client *RamClient) CreateVirtualMFADevice(req MFARequest) (MFAResponse, error) { 36 | var resp MFAResponse 37 | err := client.Invoke("CreateVirtualMFADevice", req, &resp) 38 | if err != nil { 39 | return MFAResponse{}, err 40 | } 41 | return resp, nil 42 | } 43 | 44 | func (client *RamClient) ListVirtualMFADevices() (MFAListResponse, error) { 45 | var resp MFAListResponse 46 | err := client.Invoke("ListVirtualMFADevices", struct{}{}, &resp) 47 | if err != nil { 48 | return MFAListResponse{}, err 49 | } 50 | return resp, nil 51 | } 52 | 53 | func (client *RamClient) DeleteVirtualMFADevice(req MFADeleteRequest) (RamCommonResponse, error) { 54 | var resp RamCommonResponse 55 | err := client.Invoke("DeleteVirtualMFADevice", req, &resp) 56 | if err != nil { 57 | return RamCommonResponse{}, err 58 | } 59 | return resp, nil 60 | } 61 | 62 | func (client *RamClient) BindMFADevice(req MFABindRequest) (RamCommonResponse, error) { 63 | var resp RamCommonResponse 64 | err := client.Invoke("BindMFADevice", req, &resp) 65 | if err != nil { 66 | return RamCommonResponse{}, err 67 | } 68 | return resp, nil 69 | } 70 | 71 | func (client *RamClient) UnbindMFADevice(req UserQueryRequest) (MFAUserResponse, error) { 72 | var resp MFAUserResponse 73 | err := client.Invoke("UnbindMFADevice", req, &resp) 74 | if err != nil { 75 | return MFAUserResponse{}, err 76 | } 77 | return resp, nil 78 | } 79 | 80 | func (client *RamClient) GetUserMFAInfo(req UserQueryRequest) (MFAUserResponse, error) { 81 | var resp MFAUserResponse 82 | err := client.Invoke("GetUserMFAInfo", req, &resp) 83 | if err != nil { 84 | return MFAUserResponse{}, err 85 | } 86 | return resp, nil 87 | } 88 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/ram/mfa_test.go: -------------------------------------------------------------------------------- 1 | package ram 2 | 3 | import ( 4 | "testing" 5 | "time" 6 | "strconv" 7 | ) 8 | 9 | var ( 10 | uname string 11 | serialNumber string 12 | mFADeviceName = strconv.FormatInt(time.Now().Unix(), 10) 13 | mFARequest = MFARequest{VirtualMFADeviceName: mFADeviceName} 14 | authenticationCode1 = "Hello" //depends on your device 15 | authenticationCode2 = "World" //depends on your device 16 | ) 17 | 18 | func TestCreateVirtualMFADevice(t *testing.T) { 19 | client := NewTestClient() 20 | resp, err := client.CreateVirtualMFADevice(mFARequest) 21 | if err != nil { 22 | t.Errorf("Failed to CreateVirtualMFADevice %v", err) 23 | } 24 | serialNumber = resp.VirtualMFADevice.SerialNumber 25 | t.Logf("pass CreateVirtualMFADevice %v", resp) 26 | } 27 | 28 | func TestListVirtualMFADevices(t *testing.T) { 29 | client := NewTestClient() 30 | resp, err := client.ListVirtualMFADevices() 31 | if err != nil { 32 | t.Errorf("Failed to ListVirtualMFADevices %v", err) 33 | } 34 | t.Logf("pass ListVirtualMFADevices %v", resp) 35 | } 36 | 37 | func TestBindMFADevice(t *testing.T) { 38 | client := NewTestClient() 39 | listParams := ListUserRequest{} 40 | resp, err := client.ListUsers(listParams) 41 | if err != nil { 42 | t.Errorf("Failed to ListUser %v", err) 43 | return 44 | } 45 | uname = resp.Users.User[0].UserName 46 | req := MFABindRequest{ 47 | SerialNumber: serialNumber, 48 | UserName: uname, 49 | AuthenticationCode1: authenticationCode1, 50 | AuthenticationCode2: authenticationCode2, 51 | } 52 | response, err := client.BindMFADevice(req) 53 | if err != nil { 54 | t.Errorf("Failed to BindMFADevice %v", err) 55 | } 56 | t.Logf("pass BindMFADevice %v", response) 57 | } 58 | 59 | func TestGetUserMFAInfo(t *testing.T) { 60 | client := NewTestClient() 61 | resp, err := client.GetUserMFAInfo(UserQueryRequest{UserName: uname}) 62 | if err != nil { 63 | t.Errorf("Failed to GetUserMFAInfo %v", err) 64 | } 65 | t.Logf("pass GetUserMFAInfo %v", resp) 66 | } 67 | 68 | func TestUnbindMFADevice(t *testing.T) { 69 | client := NewTestClient() 70 | response, err := client.UnbindMFADevice(UserQueryRequest{UserName: uname}) 71 | if err != nil { 72 | t.Errorf("Failed to UnbindMFADevice %v", err) 73 | } 74 | t.Logf("pass UnbindMFADevice %v", response) 75 | } 76 | 77 | func TestDeleteVirtualMFADevice(t *testing.T) { 78 | client := NewTestClient() 79 | resp, err := client.DeleteVirtualMFADevice(MFADeleteRequest{MFADevice: MFADevice{SerialNumber: serialNumber}}) 80 | if err != nil { 81 | t.Errorf("Failed to DeleteVirtualMFADevice %v", err) 82 | } 83 | t.Logf("pass DeleteVirtualMFADevice %v", resp) 84 | } 85 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/ram/profile.go: -------------------------------------------------------------------------------- 1 | package ram 2 | 3 | /* 4 | CreateLoginProfile() 5 | GetLoginProfile() 6 | DeleteLoginProfile() 7 | UpdateLoginProfile() 8 | */ 9 | 10 | type ProfileRequest struct { 11 | UserName string 12 | Password string 13 | PasswordResetRequired bool 14 | MFABindRequired bool 15 | } 16 | 17 | type ProfileResponse struct { 18 | RamCommonResponse 19 | LoginProfile LoginProfile 20 | } 21 | 22 | func (client *RamClient) CreateLoginProfile(req ProfileRequest) (ProfileResponse, error) { 23 | var resp ProfileResponse 24 | err := client.Invoke("CreateLoginProfile", req, &resp) 25 | if err != nil { 26 | return ProfileResponse{}, err 27 | } 28 | return resp, nil 29 | } 30 | 31 | func (client *RamClient) GetLoginProfile(req UserQueryRequest) (ProfileResponse, error) { 32 | var resp ProfileResponse 33 | err := client.Invoke("GetLoginProfile", req, &resp) 34 | if err != nil { 35 | return ProfileResponse{}, err 36 | } 37 | return resp, nil 38 | } 39 | 40 | func (client *RamClient) DeleteLoginProfile(req UserQueryRequest) (RamCommonResponse, error) { 41 | var resp RamCommonResponse 42 | err := client.Invoke("DeleteLoginProfile", req, &resp) 43 | if err != nil { 44 | return RamCommonResponse{}, err 45 | } 46 | return resp, nil 47 | } 48 | 49 | func (client *RamClient) UpdateLoginProfile(req ProfileRequest) (ProfileResponse, error) { 50 | var resp ProfileResponse 51 | err := client.Invoke("UpdateLoginProfile", req, &resp) 52 | if err != nil { 53 | return ProfileResponse{}, err 54 | } 55 | return resp, nil 56 | } 57 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/ram/profile_test.go: -------------------------------------------------------------------------------- 1 | package ram 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | var ( 8 | password = "hello&world" 9 | passwordNew = "hello&world&new" 10 | userName string 11 | ) 12 | 13 | func TestCreateLoginProfile(t *testing.T) { 14 | client := NewTestClient() 15 | listParams := ListUserRequest{} 16 | resp, err := client.ListUsers(listParams) 17 | if err != nil { 18 | t.Errorf("Failed to ListUser %v", err) 19 | return 20 | } 21 | userName = resp.Users.User[0].UserName 22 | profileRequest := ProfileRequest{ 23 | UserName: userName, 24 | Password: password, 25 | } 26 | response, err := client.CreateLoginProfile(profileRequest) 27 | if err != nil { 28 | t.Errorf("Failed to CreateLoginProfile %v", err) 29 | } 30 | t.Logf("pass CreateLoginProfile %v", response) 31 | } 32 | 33 | func TestGetLoginProfile(t *testing.T) { 34 | client := NewTestClient() 35 | resp, err := client.GetLoginProfile(UserQueryRequest{UserName: userName}) 36 | if err != nil { 37 | t.Errorf("Failed to GetLoginProfile %v", err) 38 | } 39 | t.Logf("pass GetLoginProfile %v", resp) 40 | } 41 | 42 | func TestUpdateLoginProfile(t *testing.T) { 43 | client := NewTestClient() 44 | profileRequest := ProfileRequest{ 45 | UserName: userName, 46 | Password: passwordNew, 47 | } 48 | resp, err := client.UpdateLoginProfile(profileRequest) 49 | if err != nil { 50 | t.Errorf("Failed to UpdateLoginProfile %v", err) 51 | } 52 | t.Logf("pass UpdateLoginProfile %v", resp) 53 | } 54 | 55 | func TestDeleteLoginProfile(t *testing.T) { 56 | client := NewTestClient() 57 | resp, err := client.DeleteLoginProfile(UserQueryRequest{UserName: userName}) 58 | if err != nil { 59 | t.Errorf("Failed to DeleteLoginProfile %v", err) 60 | } 61 | t.Logf("pass DeleteLoginProfile %v", resp) 62 | } 63 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/ram/role.go: -------------------------------------------------------------------------------- 1 | package ram 2 | 3 | type RoleRequest struct { 4 | RoleName string 5 | AssumeRolePolicyDocument string 6 | Description string 7 | } 8 | 9 | type RoleResponse struct { 10 | RamCommonResponse 11 | Role Role 12 | } 13 | 14 | type RoleQueryRequest struct { 15 | RoleName string 16 | } 17 | 18 | type UpdateRoleRequest struct { 19 | RoleName string 20 | NewAssumeRolePolicyDocument string 21 | } 22 | 23 | type ListRoleResponse struct { 24 | RamCommonResponse 25 | Roles struct { 26 | Role []Role 27 | } 28 | } 29 | 30 | func (client *RamClient) CreateRole(role RoleRequest) (RoleResponse, error) { 31 | var roleResponse RoleResponse 32 | err := client.Invoke("CreateRole", role, &roleResponse) 33 | if err != nil { 34 | return RoleResponse{}, err 35 | } 36 | return roleResponse, nil 37 | } 38 | 39 | func (client *RamClient) GetRole(roleQuery RoleQueryRequest) (RoleResponse, error) { 40 | var roleResponse RoleResponse 41 | err := client.Invoke("GetRole", roleQuery, &roleResponse) 42 | if err != nil { 43 | return RoleResponse{}, nil 44 | } 45 | return roleResponse, nil 46 | } 47 | 48 | func (client *RamClient) UpdateRole(newRole UpdateRoleRequest) (RoleResponse, error) { 49 | var roleResponse RoleResponse 50 | err := client.Invoke("UpdateRole", newRole, &roleResponse) 51 | if err != nil { 52 | return RoleResponse{}, err 53 | } 54 | return roleResponse, nil 55 | } 56 | 57 | func (client *RamClient) ListRoles() (ListRoleResponse, error) { 58 | var roleList ListRoleResponse 59 | err := client.Invoke("ListRoles", struct{}{}, &roleList) 60 | if err != nil { 61 | return ListRoleResponse{}, err 62 | } 63 | return roleList, nil 64 | } 65 | 66 | func (client *RamClient) DeleteRole(roleQuery RoleQueryRequest) (RamCommonResponse, error) { 67 | var commonResp RamCommonResponse 68 | err := client.Invoke("DeleteRole", roleQuery, &commonResp) 69 | if err != nil { 70 | return RamCommonResponse{}, err 71 | } 72 | return commonResp, nil 73 | } 74 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/ram/role_test.go: -------------------------------------------------------------------------------- 1 | package ram 2 | 3 | import ( 4 | "encoding/json" 5 | "os" 6 | "strconv" 7 | "testing" 8 | "time" 9 | ) 10 | 11 | /* 12 | Please also set account id in env so that roles could be created test 13 | AccessKeyId=YourAccessKeyId AccessKeySecret=YourAccessKeySecret AccountId=111111111 go test -v -run=Role 14 | */ 15 | var ( 16 | accountId = os.Getenv("AccountId") 17 | roleName = strconv.FormatInt(time.Now().Unix(), 10) 18 | 19 | princpal = AssumeRolePolicyPrincpal{RAM: []string{"acs:ram::" + accountId + ":root"}} 20 | 21 | policyDocument = AssumeRolePolicyDocument{ 22 | Statement: []AssumeRolePolicyItem{ 23 | AssumeRolePolicyItem{Action: "sts:AssumeRole", Effect: "Allow", Principal: princpal}, 24 | }, 25 | Version: "1"} 26 | 27 | newPolicyDocument = AssumeRolePolicyDocument{ 28 | Statement: []AssumeRolePolicyItem{ 29 | AssumeRolePolicyItem{Action: "sts:AssumeRole", Effect: "Deny", Principal: princpal}, 30 | }, 31 | Version: "1"} 32 | 33 | role = RoleRequest{ 34 | RoleName: roleName, 35 | AssumeRolePolicyDocument: getAssumeRolePolicyDocumentStr(), 36 | Description: "this is a role for unit test purpose", 37 | } 38 | 39 | updateRoleRequest = UpdateRoleRequest{ 40 | RoleName: roleName, 41 | NewAssumeRolePolicyDocument: getNewAssumeRolePolicyDocumentStr(), 42 | } 43 | 44 | roleQuery = RoleQueryRequest{RoleName: roleName} 45 | ) 46 | 47 | func getAssumeRolePolicyDocumentStr() string { 48 | b, _ := json.Marshal(policyDocument) 49 | return string(b) 50 | } 51 | 52 | func getNewAssumeRolePolicyDocumentStr() string { 53 | b, _ := json.Marshal(newPolicyDocument) 54 | return string(b) 55 | } 56 | 57 | func TestCreateRole(t *testing.T) { 58 | client := NewTestClient() 59 | resp, err := client.CreateRole(role) 60 | if err != nil { 61 | t.Errorf("Failed to CreateRole %v", err) 62 | } 63 | t.Logf("pass CreateRole %v", resp) 64 | } 65 | 66 | func TestGetRole(t *testing.T) { 67 | client := NewTestClient() 68 | resp, err := client.GetRole(roleQuery) 69 | if err != nil { 70 | t.Errorf("Failed to GetRole %v", err) 71 | } 72 | t.Logf("pass GetRole %v", resp) 73 | } 74 | 75 | func TestUpdateRole(t *testing.T) { 76 | client := NewTestClient() 77 | resp, err := client.UpdateRole(updateRoleRequest) 78 | if err != nil { 79 | t.Errorf("Failed to UpdateRole %v", err) 80 | } 81 | t.Logf("pass UpdateRole %v", resp) 82 | } 83 | 84 | func TestListRoles(t *testing.T) { 85 | client := NewTestClient() 86 | resp, err := client.ListRoles() 87 | if err != nil { 88 | t.Errorf("Failed to ListRoles %v", err) 89 | } 90 | t.Logf("pass ListRoles %v", resp) 91 | } 92 | 93 | func TestDeleteRole(t *testing.T) { 94 | client := NewTestClient() 95 | resp, err := client.DeleteRole(RoleQueryRequest{RoleName: roleName}) 96 | if err != nil { 97 | t.Errorf("Failed to DeleteRole %v", err) 98 | } 99 | t.Logf("pass DeleteRole %v", resp) 100 | } 101 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/ram/security.go: -------------------------------------------------------------------------------- 1 | package ram 2 | 3 | //TODO implement ram api about security 4 | /* 5 | SetAccountAlias() 6 | GetAccountAlias() 7 | ClearAccountAlias() 8 | SetPasswordPolicy() 9 | GetPasswordPolicy() 10 | */ 11 | type AccountAliasResponse struct { 12 | RamCommonResponse 13 | AccountAlias string 14 | } 15 | 16 | type PasswordPolicyResponse struct { 17 | RamCommonResponse 18 | PasswordPolicy 19 | } 20 | 21 | type PasswordPolicyRequest struct { 22 | PasswordPolicy 23 | } 24 | 25 | type AccountAliasRequest struct { 26 | AccountAlias string 27 | } 28 | 29 | func (client *RamClient) SetAccountAlias(accountalias AccountAliasRequest) (RamCommonResponse, error) { 30 | var resp RamCommonResponse 31 | err := client.Invoke("SetAccountAlias", accountalias, &resp) 32 | if err != nil { 33 | return RamCommonResponse{}, err 34 | } 35 | return resp, nil 36 | } 37 | 38 | func (client *RamClient) GetAccountAlias() (AccountAliasResponse, error) { 39 | var resp AccountAliasResponse 40 | err := client.Invoke("GetAccountAlias", struct{}{}, &resp) 41 | if err != nil { 42 | return AccountAliasResponse{}, err 43 | } 44 | return resp, nil 45 | } 46 | 47 | func (client *RamClient) ClearAccountAlias() (RamCommonResponse, error) { 48 | var resp RamCommonResponse 49 | err := client.Invoke("ClearAccountAlias", struct{}{}, &resp) 50 | if err != nil { 51 | return RamCommonResponse{}, err 52 | } 53 | return resp, nil 54 | } 55 | 56 | func (client *RamClient) SetPasswordPolicy(passwordPolicy PasswordPolicyRequest) (PasswordPolicyResponse, error) { 57 | var resp PasswordPolicyResponse 58 | err := client.Invoke("SetPasswordPolicy", passwordPolicy, &resp) 59 | if err != nil { 60 | return PasswordPolicyResponse{}, err 61 | } 62 | return resp, nil 63 | } 64 | 65 | func (client *RamClient) GetPasswordPolicy() (PasswordPolicyResponse, error) { 66 | var resp PasswordPolicyResponse 67 | err := client.Invoke("GetPasswordPolicy", struct{}{}, &resp) 68 | if err != nil { 69 | return PasswordPolicyResponse{}, err 70 | } 71 | return resp, nil 72 | } 73 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/ram/security_test.go: -------------------------------------------------------------------------------- 1 | package ram 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | var ( 8 | accountAliasRequest = AccountAliasRequest{AccountAlias: "hello"} 9 | passwordPolicy = PasswordPolicyRequest{ 10 | PasswordPolicy: PasswordPolicy{ 11 | MinimumPasswordLength: 10, 12 | RequireLowercaseCharacters: true, 13 | RequireUppercaseCharacters: true, 14 | RequireNumbers: true, 15 | RequireSymbols: true, 16 | }, 17 | } 18 | ) 19 | 20 | func TestSetAccountAlias(t *testing.T) { 21 | client := NewTestClient() 22 | resp, err := client.SetAccountAlias(accountAliasRequest) 23 | if err != nil { 24 | t.Errorf("Failed to SetAccountAlias %v", err) 25 | } 26 | t.Logf("pass SetAccountAlias %v", resp) 27 | } 28 | 29 | func TestGetAccountAlias(t *testing.T) { 30 | client := NewTestClient() 31 | resp, err := client.GetAccountAlias() 32 | if err != nil { 33 | t.Errorf("Failed to GetAccountAlias %v", err) 34 | } 35 | t.Logf("pass GetAccountAlias %v", resp) 36 | } 37 | 38 | func TestClearAccountAlias(t *testing.T) { 39 | client := NewTestClient() 40 | resp, err := client.ClearAccountAlias() 41 | if err != nil { 42 | t.Errorf("Failed to ClearAccountAlias %v", err) 43 | } 44 | t.Logf("pass ClearAccountAlias %v", resp) 45 | } 46 | 47 | func TestSetPasswordPolicy(t *testing.T) { 48 | client := NewTestClient() 49 | resp, err := client.SetPasswordPolicy(passwordPolicy) 50 | if err != nil { 51 | t.Errorf("Failed to pass SetPasswordPolicy %v", err) 52 | } 53 | t.Logf("pass SetPasswordPolicy %v", resp) 54 | } 55 | 56 | func TestGetPasswordPolicy(t *testing.T) { 57 | client := NewTestClient() 58 | resp, err := client.GetPasswordPolicy() 59 | if err != nil { 60 | t.Errorf("Failed to pass GetPasswordPolicy %v", err) 61 | } 62 | t.Logf("pass GetPasswordPolicy %v", resp) 63 | } 64 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/ram/types.go: -------------------------------------------------------------------------------- 1 | package ram 2 | 3 | import ( 4 | "github.com/denverdino/aliyungo/common" 5 | ) 6 | 7 | /* 8 | All common struct 9 | */ 10 | 11 | const ( 12 | Active State = "Active" 13 | Inactive State = "Inactive" 14 | ) 15 | 16 | /* 17 | AccountAlias 18 | 类型:String 19 | 必须:是 20 | 描述:指定云账号的别名, 长度限制为3-63个字符 21 | 限制:^[a-z0-9](([a-z0-9]|-(?!-))*[a-z0-9])?$ 22 | */ 23 | type AccountAlias string 24 | 25 | type UserQueryRequest struct { 26 | UserName string 27 | } 28 | 29 | type User struct { 30 | UserId string 31 | UserName string 32 | DisplayName string 33 | MobilePhone string 34 | Email string 35 | Comments string 36 | CreateDate string 37 | UpdateDate string 38 | LastLoginDate string 39 | } 40 | 41 | type LoginProfile struct { 42 | UserName string 43 | PasswordResetRequired bool 44 | MFABindRequired bool 45 | } 46 | 47 | type MFADevice struct { 48 | SerialNumber string 49 | } 50 | 51 | type VirtualMFADevice struct { 52 | SerialNumber string 53 | Base32StringSeed string 54 | QRCodePNG string 55 | ActivateDate string 56 | User User 57 | } 58 | 59 | type AccessKey struct { 60 | AccessKeyId string 61 | AccessKeySecret string 62 | Status State 63 | CreateDate string 64 | } 65 | 66 | type Group struct { 67 | GroupName string 68 | Comments string 69 | } 70 | 71 | type Role struct { 72 | RoleId string 73 | RoleName string 74 | Arn string 75 | Description string 76 | AssumeRolePolicyDocument string 77 | CreateDate string 78 | UpdateDate string 79 | } 80 | 81 | type Policy struct { 82 | PolicyName string 83 | PolicyType string 84 | Description string 85 | DefaultVersion string 86 | CreateDate string 87 | UpdateDate string 88 | AttachmentCount int64 89 | } 90 | 91 | type PolicyVersion struct { 92 | VersionId string 93 | IsDefaultVersion bool 94 | CreateDate string 95 | PolicyDocument string 96 | } 97 | 98 | type PolicyDocument struct { 99 | Statement []PolicyItem 100 | Version string 101 | } 102 | 103 | type PolicyItem struct { 104 | Action string 105 | Effect string 106 | Resource string 107 | } 108 | 109 | type AssumeRolePolicyDocument struct { 110 | Statement []AssumeRolePolicyItem 111 | Version string 112 | } 113 | 114 | type AssumeRolePolicyItem struct { 115 | Action string 116 | Effect string 117 | Principal AssumeRolePolicyPrincpal 118 | } 119 | 120 | type AssumeRolePolicyPrincpal struct { 121 | RAM []string 122 | } 123 | 124 | /* 125 | "PasswordPolicy": { 126 | "MinimumPasswordLength": 12, 127 | "RequireLowercaseCharacters": true, 128 | "RequireUppercaseCharacters": true, 129 | "RequireNumbers": true, 130 | "RequireSymbols": true 131 | } 132 | */ 133 | 134 | type PasswordPolicy struct { 135 | MinimumPasswordLength int8 136 | RequireLowercaseCharacters bool 137 | RequireUppercaseCharacters bool 138 | RequireNumbers bool 139 | RequireSymbols bool 140 | } 141 | 142 | type RamCommonResponse struct { 143 | common.Response 144 | } 145 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/util/attempt.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "time" 5 | ) 6 | 7 | // AttemptStrategy is reused from the goamz package 8 | 9 | // AttemptStrategy represents a strategy for waiting for an action 10 | // to complete successfully. This is an internal type used by the 11 | // implementation of other packages. 12 | type AttemptStrategy struct { 13 | Total time.Duration // total duration of attempt. 14 | Delay time.Duration // interval between each try in the burst. 15 | Min int // minimum number of retries; overrides Total 16 | } 17 | 18 | type Attempt struct { 19 | strategy AttemptStrategy 20 | last time.Time 21 | end time.Time 22 | force bool 23 | count int 24 | } 25 | 26 | // Start begins a new sequence of attempts for the given strategy. 27 | func (s AttemptStrategy) Start() *Attempt { 28 | now := time.Now() 29 | return &Attempt{ 30 | strategy: s, 31 | last: now, 32 | end: now.Add(s.Total), 33 | force: true, 34 | } 35 | } 36 | 37 | // Next waits until it is time to perform the next attempt or returns 38 | // false if it is time to stop trying. 39 | func (a *Attempt) Next() bool { 40 | now := time.Now() 41 | sleep := a.nextSleep(now) 42 | if !a.force && !now.Add(sleep).Before(a.end) && a.strategy.Min <= a.count { 43 | return false 44 | } 45 | a.force = false 46 | if sleep > 0 && a.count > 0 { 47 | time.Sleep(sleep) 48 | now = time.Now() 49 | } 50 | a.count++ 51 | a.last = now 52 | return true 53 | } 54 | 55 | func (a *Attempt) nextSleep(now time.Time) time.Duration { 56 | sleep := a.strategy.Delay - now.Sub(a.last) 57 | if sleep < 0 { 58 | return 0 59 | } 60 | return sleep 61 | } 62 | 63 | // HasNext returns whether another attempt will be made if the current 64 | // one fails. If it returns true, the following call to Next is 65 | // guaranteed to return true. 66 | func (a *Attempt) HasNext() bool { 67 | if a.force || a.strategy.Min > a.count { 68 | return true 69 | } 70 | now := time.Now() 71 | if now.Add(a.nextSleep(now)).Before(a.end) { 72 | a.force = true 73 | return true 74 | } 75 | return false 76 | } 77 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/util/attempt_test.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "testing" 5 | "time" 6 | ) 7 | 8 | func TestAttemptTiming(t *testing.T) { 9 | testAttempt := AttemptStrategy{ 10 | Total: 0.25e9, 11 | Delay: 0.1e9, 12 | } 13 | want := []time.Duration{0, 0.1e9, 0.2e9, 0.2e9} 14 | got := make([]time.Duration, 0, len(want)) // avoid allocation when testing timing 15 | t0 := time.Now() 16 | for a := testAttempt.Start(); a.Next(); { 17 | got = append(got, time.Now().Sub(t0)) 18 | } 19 | got = append(got, time.Now().Sub(t0)) 20 | if len(got) != len(want) { 21 | t.Fatalf("Failed!") 22 | } 23 | const margin = 0.01e9 24 | for i, got := range want { 25 | lo := want[i] - margin 26 | hi := want[i] + margin 27 | if got < lo || got > hi { 28 | t.Errorf("attempt %d want %g got %g", i, want[i].Seconds(), got.Seconds()) 29 | } 30 | } 31 | } 32 | 33 | func TestAttemptNextHasNext(t *testing.T) { 34 | a := AttemptStrategy{}.Start() 35 | if !a.Next() { 36 | t.Fatalf("Failed!") 37 | } 38 | if a.Next() { 39 | t.Fatalf("Failed!") 40 | } 41 | 42 | a = AttemptStrategy{}.Start() 43 | if !a.Next() { 44 | t.Fatalf("Failed!") 45 | } 46 | if a.HasNext() { 47 | t.Fatalf("Failed!") 48 | } 49 | if a.Next() { 50 | t.Fatalf("Failed!") 51 | } 52 | a = AttemptStrategy{Total: 2e8}.Start() 53 | 54 | if !a.Next() { 55 | t.Fatalf("Failed!") 56 | } 57 | if !a.HasNext() { 58 | t.Fatalf("Failed!") 59 | } 60 | time.Sleep(2e8) 61 | 62 | if !a.HasNext() { 63 | t.Fatalf("Failed!") 64 | } 65 | if !a.Next() { 66 | t.Fatalf("Failed!") 67 | } 68 | if a.Next() { 69 | t.Fatalf("Failed!") 70 | } 71 | 72 | a = AttemptStrategy{Total: 1e8, Min: 2}.Start() 73 | time.Sleep(1e8) 74 | 75 | if !a.Next() { 76 | t.Fatalf("Failed!") 77 | } 78 | if !a.HasNext() { 79 | t.Fatalf("Failed!") 80 | } 81 | if !a.Next() { 82 | t.Fatalf("Failed!") 83 | } 84 | if a.HasNext() { 85 | t.Fatalf("Failed!") 86 | } 87 | if a.Next() { 88 | t.Fatalf("Failed!") 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/util/encoding_test.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "testing" 5 | "time" 6 | ) 7 | 8 | type TestString string 9 | 10 | type SubStruct struct { 11 | A string 12 | B int 13 | } 14 | 15 | type MyStruct struct { 16 | SubStruct 17 | } 18 | 19 | type YourStruct struct { 20 | SubStruct SubStruct 21 | } 22 | 23 | func TestConvertToQueryValues2(t *testing.T) { 24 | 25 | result := ConvertToQueryValues(MyStruct{SubStruct: SubStruct{A: "A", B: 1}}).Encode() 26 | const expectedResult = "A=A&B=1" 27 | if result != expectedResult { 28 | // Sometimes result is not matched for the different orders 29 | t.Logf("Incorrect encoding: %s", result) 30 | } 31 | result2 := ConvertToQueryValues(YourStruct{SubStruct: SubStruct{A: "A2", B: 2}}).Encode() 32 | const expectedResult2 = "SubStruct.A=A2&SubStruct.B=2" 33 | if result2 != expectedResult2 { 34 | // Sometimes result is not matched for the different orders 35 | t.Logf("Incorrect encoding: %s", result2) 36 | } 37 | } 38 | 39 | type TestStruct struct { 40 | Format string 41 | Version string 42 | AccessKeyId string 43 | Timestamp time.Time 44 | Empty string 45 | IntValue int `ArgName:"int-value"` 46 | BoolPtr *bool `ArgName:"bool-ptr"` 47 | IntPtr *int `ArgName:"int-ptr"` 48 | StringArray []string `ArgName:"str-array"` 49 | StructArray []SubStruct 50 | SubStruct SubStruct 51 | test TestString 52 | tests []TestString 53 | Tag map[string]string 54 | } 55 | 56 | func TestConvertToQueryValues(t *testing.T) { 57 | boolValue := true 58 | request := TestStruct{ 59 | Format: "JSON", 60 | Version: "1.0", 61 | Timestamp: time.Date(2015, time.Month(5), 26, 1, 2, 3, 4, time.UTC), 62 | IntValue: 10, 63 | BoolPtr: &boolValue, 64 | StringArray: []string{"abc", "xyz"}, 65 | StructArray: []SubStruct{ 66 | SubStruct{A: "a", B: 1}, 67 | SubStruct{A: "x", B: 2}, 68 | }, 69 | SubStruct: SubStruct{A: "M", B: 0}, 70 | test: TestString("test"), 71 | tests: []TestString{TestString("test1"), TestString("test2")}, 72 | Tag: map[string]string{"abc": "xyz", "123": "456"}, 73 | } 74 | result := ConvertToQueryValues(&request).Encode() 75 | const expectedResult = "Format=JSON&StructArray.1.A=a&StructArray.1.B=1&StructArray.2.A=x&StructArray.2.B=2&SubStruct.A=M&Tag.1.Key=abc&Tag.1.Value=xyz&Tag.2.Key=123&Tag.2.Value=456&Timestamp=2015-05-26T01%3A02%3A03Z&Version=1.0&bool-ptr=true&int-value=10&str-array=%5B%22abc%22%2C%22xyz%22%5D&test=test&tests=%5B%22test1%22%2C%22test2%22%5D" 76 | if result != expectedResult { 77 | // Sometimes result is not matched for the different orders 78 | t.Logf("Incorrect encoding: %s", result) 79 | } 80 | 81 | } 82 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/util/iso6801.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "fmt" 5 | "strconv" 6 | "time" 7 | ) 8 | 9 | // GetISO8601TimeStamp gets timestamp string in ISO8601 format 10 | func GetISO8601TimeStamp(ts time.Time) string { 11 | t := ts.UTC() 12 | return fmt.Sprintf("%04d-%02d-%02dT%02d:%02d:%02dZ", t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second()) 13 | } 14 | 15 | const formatISO8601 = "2006-01-02T15:04:05Z" 16 | const jsonFormatISO8601 = `"` + formatISO8601 + `"` 17 | const formatISO8601withoutSeconds = "2006-01-02T15:04Z" 18 | const jsonFormatISO8601withoutSeconds = `"` + formatISO8601withoutSeconds + `"` 19 | 20 | // A ISO6801Time represents a time in ISO8601 format 21 | type ISO6801Time time.Time 22 | 23 | // New constructs a new iso8601.Time instance from an existing 24 | // time.Time instance. This causes the nanosecond field to be set to 25 | // 0, and its time zone set to a fixed zone with no offset from UTC 26 | // (but it is *not* UTC itself). 27 | func NewISO6801Time(t time.Time) ISO6801Time { 28 | return ISO6801Time(time.Date( 29 | t.Year(), 30 | t.Month(), 31 | t.Day(), 32 | t.Hour(), 33 | t.Minute(), 34 | t.Second(), 35 | 0, 36 | time.UTC, 37 | )) 38 | } 39 | 40 | // IsDefault checks if the time is default 41 | func (it *ISO6801Time) IsDefault() bool { 42 | return *it == ISO6801Time{} 43 | } 44 | 45 | // MarshalJSON serializes the ISO6801Time into JSON string 46 | func (it ISO6801Time) MarshalJSON() ([]byte, error) { 47 | return []byte(time.Time(it).Format(jsonFormatISO8601)), nil 48 | } 49 | 50 | // UnmarshalJSON deserializes the ISO6801Time from JSON string 51 | func (it *ISO6801Time) UnmarshalJSON(data []byte) error { 52 | str := string(data) 53 | 54 | if str == "\"\"" || len(data) == 0 { 55 | return nil 56 | } 57 | var t time.Time 58 | var err error 59 | if str[0] == '"' { 60 | t, err = time.ParseInLocation(jsonFormatISO8601, str, time.UTC) 61 | if err != nil { 62 | t, err = time.ParseInLocation(jsonFormatISO8601withoutSeconds, str, time.UTC) 63 | } 64 | } else { 65 | var i int64 66 | i, err = strconv.ParseInt(str, 10, 64) 67 | if err == nil { 68 | t = time.Unix(i/1000, i%1000) 69 | } 70 | } 71 | if err == nil { 72 | *it = ISO6801Time(t) 73 | } 74 | return err 75 | } 76 | 77 | // String returns the time in ISO6801Time format 78 | func (it ISO6801Time) String() string { 79 | return time.Time(it).Format(formatISO8601) 80 | } 81 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/util/iso6801_test.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "encoding/json" 5 | "testing" 6 | "time" 7 | ) 8 | 9 | func TestISO8601Time(t *testing.T) { 10 | now := NewISO6801Time(time.Now().UTC()) 11 | 12 | data, err := json.Marshal(now) 13 | if err != nil { 14 | t.Fatal(err) 15 | } 16 | 17 | _, err = time.Parse(`"`+formatISO8601+`"`, string(data)) 18 | if err != nil { 19 | t.Fatal(err) 20 | } 21 | 22 | var now2 ISO6801Time 23 | err = json.Unmarshal(data, &now2) 24 | if err != nil { 25 | t.Fatal(err) 26 | } 27 | 28 | if now != now2 { 29 | t.Errorf("Time %s does not equal expected %s", now2, now) 30 | } 31 | 32 | if now.String() != now2.String() { 33 | t.Fatalf("String format for %s does not equal expected %s", now2, now) 34 | } 35 | 36 | type TestTimeStruct struct { 37 | A int 38 | B *ISO6801Time 39 | } 40 | var testValue TestTimeStruct 41 | err = json.Unmarshal([]byte("{\"A\": 1, \"B\":\"\"}"), &testValue) 42 | if err != nil { 43 | t.Fatal(err) 44 | } 45 | t.Logf("%v", testValue) 46 | if !testValue.B.IsDefault() { 47 | t.Fatal("Invaid Unmarshal result for ISO6801Time from empty value") 48 | } 49 | t.Logf("ISO6801Time String(): %s", now2.String()) 50 | } 51 | 52 | func TestISO8601TimeWithoutSeconds(t *testing.T) { 53 | 54 | const dateStr = "\"2015-10-02T12:36Z\"" 55 | 56 | var date ISO6801Time 57 | 58 | err := json.Unmarshal([]byte(dateStr), &date) 59 | if err != nil { 60 | t.Fatal(err) 61 | } 62 | 63 | const dateStr2 = "\"2015-10-02T12:36:00Z\"" 64 | 65 | var date2 ISO6801Time 66 | 67 | err = json.Unmarshal([]byte(dateStr2), &date2) 68 | if err != nil { 69 | t.Fatal(err) 70 | } 71 | 72 | if date != date2 { 73 | t.Error("The two dates should be equal.") 74 | } 75 | 76 | } 77 | 78 | func TestISO8601TimeInt(t *testing.T) { 79 | 80 | const dateStr = "1405544146000" 81 | 82 | var date ISO6801Time 83 | 84 | err := json.Unmarshal([]byte(dateStr), &date) 85 | if err != nil { 86 | t.Fatal(err) 87 | } 88 | 89 | t.Logf("date: %s", date) 90 | 91 | } 92 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/util/signature.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "crypto/hmac" 5 | "crypto/sha1" 6 | "encoding/base64" 7 | "net/url" 8 | "strings" 9 | ) 10 | 11 | //CreateSignature creates signature for string following Aliyun rules 12 | func CreateSignature(stringToSignature, accessKeySecret string) string { 13 | // Crypto by HMAC-SHA1 14 | hmacSha1 := hmac.New(sha1.New, []byte(accessKeySecret)) 15 | hmacSha1.Write([]byte(stringToSignature)) 16 | sign := hmacSha1.Sum(nil) 17 | 18 | // Encode to Base64 19 | base64Sign := base64.StdEncoding.EncodeToString(sign) 20 | 21 | return base64Sign 22 | } 23 | 24 | func percentReplace(str string) string { 25 | str = strings.Replace(str, "+", "%20", -1) 26 | str = strings.Replace(str, "*", "%2A", -1) 27 | str = strings.Replace(str, "%7E", "~", -1) 28 | 29 | return str 30 | } 31 | 32 | // CreateSignatureForRequest creates signature for query string values 33 | func CreateSignatureForRequest(method string, values *url.Values, accessKeySecret string) string { 34 | 35 | canonicalizedQueryString := percentReplace(values.Encode()) 36 | 37 | stringToSign := method + "&%2F&" + url.QueryEscape(canonicalizedQueryString) 38 | 39 | return CreateSignature(stringToSign, accessKeySecret) 40 | } 41 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/util/signature_test.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestCreateSignature(t *testing.T) { 8 | 9 | str := "GET&%2F&AccessKeyId%3Dtestid%26Action%3DDescribeRegions%26Format%3DXML%26RegionId%3Dregion1%26SignatureMethod%3DHMAC-SHA1%26SignatureNonce%3DNwDAxvLU6tFE0DVb%26SignatureVersion%3D1.0%26TimeStamp%3D2012-12-26T10%253A33%253A56Z%26Version%3D2014-05-26" 10 | 11 | signature := CreateSignature(str, "testsecret") 12 | 13 | t.Log(signature) 14 | } 15 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/util/util.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "bytes" 5 | srand "crypto/rand" 6 | "encoding/binary" 7 | "math/rand" 8 | "net/http" 9 | "net/url" 10 | "sort" 11 | "time" 12 | ) 13 | 14 | const dictionary = "_0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" 15 | 16 | //CreateRandomString create random string 17 | func CreateRandomString() string { 18 | b := make([]byte, 32) 19 | l := len(dictionary) 20 | 21 | _, err := srand.Read(b) 22 | 23 | if err != nil { 24 | // fail back to insecure rand 25 | rand.Seed(time.Now().UnixNano()) 26 | for i := range b { 27 | b[i] = dictionary[rand.Int()%l] 28 | } 29 | } else { 30 | for i, v := range b { 31 | b[i] = dictionary[v%byte(l)] 32 | } 33 | } 34 | 35 | return string(b) 36 | } 37 | 38 | // Encode encodes the values into ``URL encoded'' form 39 | // ("acl&bar=baz&foo=quux") sorted by key. 40 | func Encode(v url.Values) string { 41 | if v == nil { 42 | return "" 43 | } 44 | var buf bytes.Buffer 45 | keys := make([]string, 0, len(v)) 46 | for k := range v { 47 | keys = append(keys, k) 48 | } 49 | sort.Strings(keys) 50 | for _, k := range keys { 51 | vs := v[k] 52 | prefix := url.QueryEscape(k) 53 | for _, v := range vs { 54 | if buf.Len() > 0 { 55 | buf.WriteByte('&') 56 | } 57 | buf.WriteString(prefix) 58 | if v != "" { 59 | buf.WriteString("=") 60 | buf.WriteString(url.QueryEscape(v)) 61 | } 62 | } 63 | } 64 | return buf.String() 65 | } 66 | 67 | func GetGMTime() string { 68 | return time.Now().UTC().Format(http.TimeFormat) 69 | } 70 | 71 | // 72 | 73 | func randUint32() uint32 { 74 | return randUint32Slice(1)[0] 75 | } 76 | 77 | func randUint32Slice(c int) []uint32 { 78 | b := make([]byte, c*4) 79 | 80 | _, err := srand.Read(b) 81 | 82 | if err != nil { 83 | // fail back to insecure rand 84 | rand.Seed(time.Now().UnixNano()) 85 | for i := range b { 86 | b[i] = byte(rand.Int()) 87 | } 88 | } 89 | 90 | n := make([]uint32, c) 91 | 92 | for i := range n { 93 | n[i] = binary.BigEndian.Uint32(b[i*4 : i*4+4]) 94 | } 95 | 96 | return n 97 | } 98 | 99 | func toByte(n uint32, st, ed byte) byte { 100 | return byte(n%uint32(ed-st+1) + uint32(st)) 101 | } 102 | 103 | func toDigit(n uint32) byte { 104 | return toByte(n, '0', '9') 105 | } 106 | 107 | func toLowerLetter(n uint32) byte { 108 | return toByte(n, 'a', 'z') 109 | } 110 | 111 | func toUpperLetter(n uint32) byte { 112 | return toByte(n, 'A', 'Z') 113 | } 114 | 115 | type convFunc func(uint32) byte 116 | 117 | var convFuncs = []convFunc{toDigit, toLowerLetter, toUpperLetter} 118 | 119 | // tools for generating a random ECS instance password 120 | // from 8 to 30 char MUST contain digit upper, case letter and upper case letter 121 | // http://docs.aliyun.com/#/pub/ecs/open-api/instance&createinstance 122 | func GenerateRandomECSPassword() string { 123 | 124 | // [8, 30] 125 | l := int(randUint32()%23 + 8) 126 | 127 | n := randUint32Slice(l) 128 | 129 | b := make([]byte, l) 130 | 131 | b[0] = toDigit(n[0]) 132 | b[1] = toLowerLetter(n[1]) 133 | b[2] = toUpperLetter(n[2]) 134 | 135 | for i := 3; i < l; i++ { 136 | b[i] = convFuncs[n[i]%3](n[i]) 137 | } 138 | 139 | s := make([]byte, l) 140 | perm := rand.Perm(l) 141 | for i, v := range perm { 142 | s[v] = b[i] 143 | } 144 | 145 | return string(s) 146 | 147 | } 148 | -------------------------------------------------------------------------------- /vendor/github.com/denverdino/aliyungo/util/util_test.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestCreateRandomString(t *testing.T) { 8 | for i := 0; i < 10; i++ { 9 | s := CreateRandomString() 10 | t.Logf("Generated Random String: %s", s) 11 | } 12 | } 13 | 14 | func TestGenerateRandomECSPassword(t *testing.T) { 15 | for i := 0; i < 10; i++ { 16 | s := GenerateRandomECSPassword() 17 | 18 | if len(s) < 8 || len(s) > 30 { 19 | t.Errorf("Generated ECS password [%v]: bad len", s) 20 | } 21 | 22 | hasDigit := false 23 | hasLower := false 24 | hasUpper := false 25 | 26 | for j := range s { 27 | 28 | switch { 29 | case '0' <= s[j] && s[j] <= '9': 30 | hasDigit = true 31 | case 'a' <= s[j] && s[j] <= 'z': 32 | hasLower = true 33 | case 'A' <= s[j] && s[j] <= 'Z': 34 | hasUpper = true 35 | } 36 | } 37 | 38 | if !hasDigit { 39 | t.Errorf("Generated ECS password [%v]: no digit", s) 40 | } 41 | 42 | if !hasLower { 43 | t.Errorf("Generated ECS password [%v]: no lower letter ", s) 44 | } 45 | 46 | if !hasUpper { 47 | t.Errorf("Generated ECS password [%v]: no upper letter", s) 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /vendor/github.com/nightlyone/lockfile/README.md: -------------------------------------------------------------------------------- 1 | lockfile 2 | ========= 3 | Handle locking via pid files. 4 | 5 | [![Build Status Unix][1]][2] 6 | [![Build status Windows][3]][4] 7 | 8 | [1]: https://secure.travis-ci.org/nightlyone/lockfile.png 9 | [2]: https://travis-ci.org/nightlyone/lockfile 10 | [3]: https://ci.appveyor.com/api/projects/status/7mojkmauj81uvp8u/branch/master?svg=true 11 | [4]: https://ci.appveyor.com/project/nightlyone/lockfile/branch/master 12 | 13 | 14 | 15 | install 16 | ------- 17 | Install [Go 1][5], either [from source][6] or [with a prepackaged binary][7]. 18 | For Windows suport, Go 1.4 or newer is required. 19 | 20 | Then run 21 | 22 | go get github.com/nightlyone/lockfile 23 | 24 | [5]: http://golang.org 25 | [6]: http://golang.org/doc/install/source 26 | [7]: http://golang.org/doc/install 27 | 28 | LICENSE 29 | ------- 30 | MIT 31 | 32 | documentation 33 | ------------- 34 | [package documentation at godoc.org](http://godoc.org/github.com/nightlyone/lockfile) 35 | 36 | install 37 | ------------------- 38 | go get github.com/nightlyone/lockfile 39 | 40 | 41 | contributing 42 | ============ 43 | 44 | Contributions are welcome. Please open an issue or send me a pull request for a dedicated branch. 45 | Make sure the git commit hooks show it works. 46 | 47 | git commit hooks 48 | ----------------------- 49 | enable commit hooks via 50 | 51 | cd .git ; rm -rf hooks; ln -s ../git-hooks hooks ; cd .. 52 | 53 | -------------------------------------------------------------------------------- /vendor/github.com/nightlyone/lockfile/lockfile_unix.go: -------------------------------------------------------------------------------- 1 | // +build darwin dragonfly freebsd linux nacl netbsd openbsd solaris aix 2 | 3 | package lockfile 4 | 5 | import ( 6 | "os" 7 | "syscall" 8 | ) 9 | 10 | func isRunning(pid int) (bool, error) { 11 | proc, err := os.FindProcess(pid) 12 | if err != nil { 13 | return false, err 14 | } 15 | 16 | if err := proc.Signal(syscall.Signal(0)); err != nil { 17 | return false, nil 18 | } 19 | return true, nil 20 | } 21 | -------------------------------------------------------------------------------- /vendor/github.com/nightlyone/lockfile/lockfile_windows.go: -------------------------------------------------------------------------------- 1 | package lockfile 2 | 3 | import ( 4 | "syscall" 5 | ) 6 | 7 | //For some reason these consts don't exist in syscall. 8 | const ( 9 | error_invalid_parameter = 87 10 | code_still_active = 259 11 | ) 12 | 13 | func isRunning(pid int) (bool, error) { 14 | procHnd, err := syscall.OpenProcess(syscall.PROCESS_QUERY_INFORMATION, true, uint32(pid)) 15 | if err != nil { 16 | if scerr, ok := err.(syscall.Errno); ok { 17 | if uintptr(scerr) == error_invalid_parameter { 18 | return false, nil 19 | } 20 | } 21 | } 22 | 23 | var code uint32 24 | err = syscall.GetExitCodeProcess(procHnd, &code) 25 | if err != nil { 26 | return false, err 27 | } 28 | 29 | return code == code_still_active, nil 30 | } 31 | -------------------------------------------------------------------------------- /vendor/github.com/sirupsen/logrus/LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2014 Simon Eskildsen 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /vendor/github.com/sirupsen/logrus/alt_exit.go: -------------------------------------------------------------------------------- 1 | package logrus 2 | 3 | // The following code was sourced and modified from the 4 | // https://bitbucket.org/tebeka/atexit package governed by the following license: 5 | // 6 | // Copyright (c) 2012 Miki Tebeka . 7 | // 8 | // Permission is hereby granted, free of charge, to any person obtaining a copy of 9 | // this software and associated documentation files (the "Software"), to deal in 10 | // the Software without restriction, including without limitation the rights to 11 | // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 12 | // the Software, and to permit persons to whom the Software is furnished to do so, 13 | // subject to the following conditions: 14 | // 15 | // The above copyright notice and this permission notice shall be included in all 16 | // copies or substantial portions of the Software. 17 | // 18 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 20 | // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 21 | // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 22 | // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 23 | // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 24 | 25 | import ( 26 | "fmt" 27 | "os" 28 | ) 29 | 30 | var handlers = []func(){} 31 | 32 | func runHandler(handler func()) { 33 | defer func() { 34 | if err := recover(); err != nil { 35 | fmt.Fprintln(os.Stderr, "Error: Logrus exit handler error:", err) 36 | } 37 | }() 38 | 39 | handler() 40 | } 41 | 42 | func runHandlers() { 43 | for _, handler := range handlers { 44 | runHandler(handler) 45 | } 46 | } 47 | 48 | // Exit runs all the Logrus atexit handlers and then terminates the program using os.Exit(code) 49 | func Exit(code int) { 50 | runHandlers() 51 | os.Exit(code) 52 | } 53 | 54 | // RegisterExitHandler adds a Logrus Exit handler, call logrus.Exit to invoke 55 | // all handlers. The handlers will also be invoked when any Fatal log entry is 56 | // made. 57 | // 58 | // This method is useful when a caller wishes to use logrus to log a fatal 59 | // message but also needs to gracefully shutdown. An example usecase could be 60 | // closing database connections, or sending a alert that the application is 61 | // closing. 62 | func RegisterExitHandler(handler func()) { 63 | handlers = append(handlers, handler) 64 | } 65 | -------------------------------------------------------------------------------- /vendor/github.com/sirupsen/logrus/doc.go: -------------------------------------------------------------------------------- 1 | /* 2 | Package logrus is a structured logger for Go, completely API compatible with the standard library logger. 3 | 4 | 5 | The simplest way to use Logrus is simply the package-level exported logger: 6 | 7 | package main 8 | 9 | import ( 10 | log "github.com/Sirupsen/logrus" 11 | ) 12 | 13 | func main() { 14 | log.WithFields(log.Fields{ 15 | "animal": "walrus", 16 | "number": 1, 17 | "size": 10, 18 | }).Info("A walrus appears") 19 | } 20 | 21 | Output: 22 | time="2015-09-07T08:48:33Z" level=info msg="A walrus appears" animal=walrus number=1 size=10 23 | 24 | For a full guide visit https://github.com/Sirupsen/logrus 25 | */ 26 | package logrus 27 | -------------------------------------------------------------------------------- /vendor/github.com/sirupsen/logrus/formatter.go: -------------------------------------------------------------------------------- 1 | package logrus 2 | 3 | import "time" 4 | 5 | const DefaultTimestampFormat = time.RFC3339 6 | 7 | // The Formatter interface is used to implement a custom Formatter. It takes an 8 | // `Entry`. It exposes all the fields, including the default ones: 9 | // 10 | // * `entry.Data["msg"]`. The message passed from Info, Warn, Error .. 11 | // * `entry.Data["time"]`. The timestamp. 12 | // * `entry.Data["level"]. The level the entry was logged at. 13 | // 14 | // Any additional fields added with `WithField` or `WithFields` are also in 15 | // `entry.Data`. Format is expected to return an array of bytes which are then 16 | // logged to `logger.Out`. 17 | type Formatter interface { 18 | Format(*Entry) ([]byte, error) 19 | } 20 | 21 | // This is to not silently overwrite `time`, `msg` and `level` fields when 22 | // dumping it. If this code wasn't there doing: 23 | // 24 | // logrus.WithField("level", 1).Info("hello") 25 | // 26 | // Would just silently drop the user provided level. Instead with this code 27 | // it'll logged as: 28 | // 29 | // {"level": "info", "fields.level": 1, "msg": "hello", "time": "..."} 30 | // 31 | // It's not exported because it's still using Data in an opinionated way. It's to 32 | // avoid code duplication between the two default formatters. 33 | func prefixFieldClashes(data Fields) { 34 | if t, ok := data["time"]; ok { 35 | data["fields.time"] = t 36 | } 37 | 38 | if m, ok := data["msg"]; ok { 39 | data["fields.msg"] = m 40 | } 41 | 42 | if l, ok := data["level"]; ok { 43 | data["fields.level"] = l 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /vendor/github.com/sirupsen/logrus/hooks.go: -------------------------------------------------------------------------------- 1 | package logrus 2 | 3 | // A hook to be fired when logging on the logging levels returned from 4 | // `Levels()` on your implementation of the interface. Note that this is not 5 | // fired in a goroutine or a channel with workers, you should handle such 6 | // functionality yourself if your call is non-blocking and you don't wish for 7 | // the logging calls for levels returned from `Levels()` to block. 8 | type Hook interface { 9 | Levels() []Level 10 | Fire(*Entry) error 11 | } 12 | 13 | // Internal type for storing the hooks on a logger instance. 14 | type LevelHooks map[Level][]Hook 15 | 16 | // Add a hook to an instance of logger. This is called with 17 | // `log.Hooks.Add(new(MyHook))` where `MyHook` implements the `Hook` interface. 18 | func (hooks LevelHooks) Add(hook Hook) { 19 | for _, level := range hook.Levels() { 20 | hooks[level] = append(hooks[level], hook) 21 | } 22 | } 23 | 24 | // Fire all the hooks for the passed level. Used by `entry.log` to fire 25 | // appropriate hooks for a log entry. 26 | func (hooks LevelHooks) Fire(level Level, entry *Entry) error { 27 | for _, hook := range hooks[level] { 28 | if err := hook.Fire(entry); err != nil { 29 | return err 30 | } 31 | } 32 | 33 | return nil 34 | } 35 | -------------------------------------------------------------------------------- /vendor/github.com/sirupsen/logrus/json_formatter.go: -------------------------------------------------------------------------------- 1 | package logrus 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | type JSONFormatter struct { 9 | // TimestampFormat sets the format used for marshaling timestamps. 10 | TimestampFormat string 11 | } 12 | 13 | func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) { 14 | data := make(Fields, len(entry.Data)+3) 15 | for k, v := range entry.Data { 16 | switch v := v.(type) { 17 | case error: 18 | // Otherwise errors are ignored by `encoding/json` 19 | // https://github.com/Sirupsen/logrus/issues/137 20 | data[k] = v.Error() 21 | default: 22 | data[k] = v 23 | } 24 | } 25 | prefixFieldClashes(data) 26 | 27 | timestampFormat := f.TimestampFormat 28 | if timestampFormat == "" { 29 | timestampFormat = DefaultTimestampFormat 30 | } 31 | 32 | data["time"] = entry.Time.Format(timestampFormat) 33 | data["msg"] = entry.Message 34 | data["level"] = entry.Level.String() 35 | 36 | serialized, err := json.Marshal(data) 37 | if err != nil { 38 | return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err) 39 | } 40 | return append(serialized, '\n'), nil 41 | } 42 | -------------------------------------------------------------------------------- /vendor/github.com/sirupsen/logrus/logrus.go: -------------------------------------------------------------------------------- 1 | package logrus 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "strings" 7 | ) 8 | 9 | // Fields type, used to pass to `WithFields`. 10 | type Fields map[string]interface{} 11 | 12 | // Level type 13 | type Level uint8 14 | 15 | // Convert the Level to a string. E.g. PanicLevel becomes "panic". 16 | func (level Level) String() string { 17 | switch level { 18 | case DebugLevel: 19 | return "debug" 20 | case InfoLevel: 21 | return "info" 22 | case WarnLevel: 23 | return "warning" 24 | case ErrorLevel: 25 | return "error" 26 | case FatalLevel: 27 | return "fatal" 28 | case PanicLevel: 29 | return "panic" 30 | } 31 | 32 | return "unknown" 33 | } 34 | 35 | // ParseLevel takes a string level and returns the Logrus log level constant. 36 | func ParseLevel(lvl string) (Level, error) { 37 | switch strings.ToLower(lvl) { 38 | case "panic": 39 | return PanicLevel, nil 40 | case "fatal": 41 | return FatalLevel, nil 42 | case "error": 43 | return ErrorLevel, nil 44 | case "warn", "warning": 45 | return WarnLevel, nil 46 | case "info": 47 | return InfoLevel, nil 48 | case "debug": 49 | return DebugLevel, nil 50 | } 51 | 52 | var l Level 53 | return l, fmt.Errorf("not a valid logrus Level: %q", lvl) 54 | } 55 | 56 | // A constant exposing all logging levels 57 | var AllLevels = []Level{ 58 | PanicLevel, 59 | FatalLevel, 60 | ErrorLevel, 61 | WarnLevel, 62 | InfoLevel, 63 | DebugLevel, 64 | } 65 | 66 | // These are the different logging levels. You can set the logging level to log 67 | // on your instance of logger, obtained with `logrus.New()`. 68 | const ( 69 | // PanicLevel level, highest level of severity. Logs and then calls panic with the 70 | // message passed to Debug, Info, ... 71 | PanicLevel Level = iota 72 | // FatalLevel level. Logs and then calls `os.Exit(1)`. It will exit even if the 73 | // logging level is set to Panic. 74 | FatalLevel 75 | // ErrorLevel level. Logs. Used for errors that should definitely be noted. 76 | // Commonly used for hooks to send errors to an error tracking service. 77 | ErrorLevel 78 | // WarnLevel level. Non-critical entries that deserve eyes. 79 | WarnLevel 80 | // InfoLevel level. General operational entries about what's going on inside the 81 | // application. 82 | InfoLevel 83 | // DebugLevel level. Usually only enabled when debugging. Very verbose logging. 84 | DebugLevel 85 | ) 86 | 87 | // Won't compile if StdLogger can't be realized by a log.Logger 88 | var ( 89 | _ StdLogger = &log.Logger{} 90 | _ StdLogger = &Entry{} 91 | _ StdLogger = &Logger{} 92 | ) 93 | 94 | // StdLogger is what your logrus-enabled library should take, that way 95 | // it'll accept a stdlib logger and a logrus logger. There's no standard 96 | // interface, this is the closest we get, unfortunately. 97 | type StdLogger interface { 98 | Print(...interface{}) 99 | Printf(string, ...interface{}) 100 | Println(...interface{}) 101 | 102 | Fatal(...interface{}) 103 | Fatalf(string, ...interface{}) 104 | Fatalln(...interface{}) 105 | 106 | Panic(...interface{}) 107 | Panicf(string, ...interface{}) 108 | Panicln(...interface{}) 109 | } 110 | 111 | // The FieldLogger interface generalizes the Entry and Logger types 112 | type FieldLogger interface { 113 | WithField(key string, value interface{}) *Entry 114 | WithFields(fields Fields) *Entry 115 | WithError(err error) *Entry 116 | 117 | Debugf(format string, args ...interface{}) 118 | Infof(format string, args ...interface{}) 119 | Printf(format string, args ...interface{}) 120 | Warnf(format string, args ...interface{}) 121 | Warningf(format string, args ...interface{}) 122 | Errorf(format string, args ...interface{}) 123 | Fatalf(format string, args ...interface{}) 124 | Panicf(format string, args ...interface{}) 125 | 126 | Debug(args ...interface{}) 127 | Info(args ...interface{}) 128 | Print(args ...interface{}) 129 | Warn(args ...interface{}) 130 | Warning(args ...interface{}) 131 | Error(args ...interface{}) 132 | Fatal(args ...interface{}) 133 | Panic(args ...interface{}) 134 | 135 | Debugln(args ...interface{}) 136 | Infoln(args ...interface{}) 137 | Println(args ...interface{}) 138 | Warnln(args ...interface{}) 139 | Warningln(args ...interface{}) 140 | Errorln(args ...interface{}) 141 | Fatalln(args ...interface{}) 142 | Panicln(args ...interface{}) 143 | } 144 | -------------------------------------------------------------------------------- /vendor/github.com/sirupsen/logrus/terminal_appengine.go: -------------------------------------------------------------------------------- 1 | // +build appengine 2 | 3 | package logrus 4 | 5 | // IsTerminal returns true if stderr's file descriptor is a terminal. 6 | func IsTerminal() bool { 7 | return true 8 | } 9 | -------------------------------------------------------------------------------- /vendor/github.com/sirupsen/logrus/terminal_bsd.go: -------------------------------------------------------------------------------- 1 | // +build darwin freebsd openbsd netbsd dragonfly 2 | // +build !appengine 3 | 4 | package logrus 5 | 6 | import "syscall" 7 | 8 | const ioctlReadTermios = syscall.TIOCGETA 9 | 10 | type Termios syscall.Termios 11 | -------------------------------------------------------------------------------- /vendor/github.com/sirupsen/logrus/terminal_linux.go: -------------------------------------------------------------------------------- 1 | // Based on ssh/terminal: 2 | // Copyright 2013 The Go Authors. All rights reserved. 3 | // Use of this source code is governed by a BSD-style 4 | // license that can be found in the LICENSE file. 5 | 6 | // +build !appengine 7 | 8 | package logrus 9 | 10 | import "syscall" 11 | 12 | const ioctlReadTermios = syscall.TCGETS 13 | 14 | type Termios syscall.Termios 15 | -------------------------------------------------------------------------------- /vendor/github.com/sirupsen/logrus/terminal_notwindows.go: -------------------------------------------------------------------------------- 1 | // Based on ssh/terminal: 2 | // Copyright 2011 The Go Authors. All rights reserved. 3 | // Use of this source code is governed by a BSD-style 4 | // license that can be found in the LICENSE file. 5 | 6 | // +build linux darwin freebsd openbsd netbsd dragonfly 7 | // +build !appengine 8 | 9 | package logrus 10 | 11 | import ( 12 | "syscall" 13 | "unsafe" 14 | ) 15 | 16 | // IsTerminal returns true if stderr's file descriptor is a terminal. 17 | func IsTerminal() bool { 18 | fd := syscall.Stderr 19 | var termios Termios 20 | _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), ioctlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0) 21 | return err == 0 22 | } 23 | -------------------------------------------------------------------------------- /vendor/github.com/sirupsen/logrus/terminal_solaris.go: -------------------------------------------------------------------------------- 1 | // +build solaris,!appengine 2 | 3 | package logrus 4 | 5 | import ( 6 | "os" 7 | 8 | "golang.org/x/sys/unix" 9 | ) 10 | 11 | // IsTerminal returns true if the given file descriptor is a terminal. 12 | func IsTerminal() bool { 13 | _, err := unix.IoctlGetTermios(int(os.Stdout.Fd()), unix.TCGETA) 14 | return err == nil 15 | } 16 | -------------------------------------------------------------------------------- /vendor/github.com/sirupsen/logrus/terminal_windows.go: -------------------------------------------------------------------------------- 1 | // Based on ssh/terminal: 2 | // Copyright 2011 The Go Authors. All rights reserved. 3 | // Use of this source code is governed by a BSD-style 4 | // license that can be found in the LICENSE file. 5 | 6 | // +build windows,!appengine 7 | 8 | package logrus 9 | 10 | import ( 11 | "syscall" 12 | "unsafe" 13 | ) 14 | 15 | var kernel32 = syscall.NewLazyDLL("kernel32.dll") 16 | 17 | var ( 18 | procGetConsoleMode = kernel32.NewProc("GetConsoleMode") 19 | ) 20 | 21 | // IsTerminal returns true if stderr's file descriptor is a terminal. 22 | func IsTerminal() bool { 23 | fd := syscall.Stderr 24 | var st uint32 25 | r, _, e := syscall.Syscall(procGetConsoleMode.Addr(), 2, uintptr(fd), uintptr(unsafe.Pointer(&st)), 0) 26 | return r != 0 && e == 0 27 | } 28 | -------------------------------------------------------------------------------- /vendor/github.com/sirupsen/logrus/text_formatter.go: -------------------------------------------------------------------------------- 1 | package logrus 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | "runtime" 7 | "sort" 8 | "strings" 9 | "time" 10 | ) 11 | 12 | const ( 13 | nocolor = 0 14 | red = 31 15 | green = 32 16 | yellow = 33 17 | blue = 34 18 | gray = 37 19 | ) 20 | 21 | var ( 22 | baseTimestamp time.Time 23 | isTerminal bool 24 | ) 25 | 26 | func init() { 27 | baseTimestamp = time.Now() 28 | isTerminal = IsTerminal() 29 | } 30 | 31 | func miniTS() int { 32 | return int(time.Since(baseTimestamp) / time.Second) 33 | } 34 | 35 | type TextFormatter struct { 36 | // Set to true to bypass checking for a TTY before outputting colors. 37 | ForceColors bool 38 | 39 | // Force disabling colors. 40 | DisableColors bool 41 | 42 | // Disable timestamp logging. useful when output is redirected to logging 43 | // system that already adds timestamps. 44 | DisableTimestamp bool 45 | 46 | // Enable logging the full timestamp when a TTY is attached instead of just 47 | // the time passed since beginning of execution. 48 | FullTimestamp bool 49 | 50 | // TimestampFormat to use for display when a full timestamp is printed 51 | TimestampFormat string 52 | 53 | // The fields are sorted by default for a consistent output. For applications 54 | // that log extremely frequently and don't use the JSON formatter this may not 55 | // be desired. 56 | DisableSorting bool 57 | } 58 | 59 | func (f *TextFormatter) Format(entry *Entry) ([]byte, error) { 60 | var b *bytes.Buffer 61 | var keys []string = make([]string, 0, len(entry.Data)) 62 | for k := range entry.Data { 63 | keys = append(keys, k) 64 | } 65 | 66 | if !f.DisableSorting { 67 | sort.Strings(keys) 68 | } 69 | if entry.Buffer != nil { 70 | b = entry.Buffer 71 | } else { 72 | b = &bytes.Buffer{} 73 | } 74 | 75 | prefixFieldClashes(entry.Data) 76 | 77 | isColorTerminal := isTerminal && (runtime.GOOS != "windows") 78 | isColored := (f.ForceColors || isColorTerminal) && !f.DisableColors 79 | 80 | timestampFormat := f.TimestampFormat 81 | if timestampFormat == "" { 82 | timestampFormat = DefaultTimestampFormat 83 | } 84 | if isColored { 85 | f.printColored(b, entry, keys, timestampFormat) 86 | } else { 87 | if !f.DisableTimestamp { 88 | f.appendKeyValue(b, "time", entry.Time.Format(timestampFormat)) 89 | } 90 | f.appendKeyValue(b, "level", entry.Level.String()) 91 | if entry.Message != "" { 92 | f.appendKeyValue(b, "msg", entry.Message) 93 | } 94 | for _, key := range keys { 95 | f.appendKeyValue(b, key, entry.Data[key]) 96 | } 97 | } 98 | 99 | b.WriteByte('\n') 100 | return b.Bytes(), nil 101 | } 102 | 103 | func (f *TextFormatter) printColored(b *bytes.Buffer, entry *Entry, keys []string, timestampFormat string) { 104 | var levelColor int 105 | switch entry.Level { 106 | case DebugLevel: 107 | levelColor = gray 108 | case WarnLevel: 109 | levelColor = yellow 110 | case ErrorLevel, FatalLevel, PanicLevel: 111 | levelColor = red 112 | default: 113 | levelColor = blue 114 | } 115 | 116 | levelText := strings.ToUpper(entry.Level.String())[0:4] 117 | 118 | if !f.FullTimestamp { 119 | fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%04d] %-44s ", levelColor, levelText, miniTS(), entry.Message) 120 | } else { 121 | fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%s] %-44s ", levelColor, levelText, entry.Time.Format(timestampFormat), entry.Message) 122 | } 123 | for _, k := range keys { 124 | v := entry.Data[k] 125 | fmt.Fprintf(b, " \x1b[%dm%s\x1b[0m=%+v", levelColor, k, v) 126 | } 127 | } 128 | 129 | func needsQuoting(text string) bool { 130 | for _, ch := range text { 131 | if !((ch >= 'a' && ch <= 'z') || 132 | (ch >= 'A' && ch <= 'Z') || 133 | (ch >= '0' && ch <= '9') || 134 | ch == '-' || ch == '.') { 135 | return true 136 | } 137 | } 138 | return false 139 | } 140 | 141 | func (f *TextFormatter) appendKeyValue(b *bytes.Buffer, key string, value interface{}) { 142 | 143 | b.WriteString(key) 144 | b.WriteByte('=') 145 | 146 | switch value := value.(type) { 147 | case string: 148 | if !needsQuoting(value) { 149 | b.WriteString(value) 150 | } else { 151 | fmt.Fprintf(b, "%q", value) 152 | } 153 | case error: 154 | errmsg := value.Error() 155 | if !needsQuoting(errmsg) { 156 | b.WriteString(errmsg) 157 | } else { 158 | fmt.Fprintf(b, "%q", value) 159 | } 160 | default: 161 | fmt.Fprint(b, value) 162 | } 163 | 164 | b.WriteByte(' ') 165 | } 166 | -------------------------------------------------------------------------------- /vendor/github.com/sirupsen/logrus/writer.go: -------------------------------------------------------------------------------- 1 | package logrus 2 | 3 | import ( 4 | "bufio" 5 | "io" 6 | "runtime" 7 | ) 8 | 9 | func (logger *Logger) Writer() *io.PipeWriter { 10 | return logger.WriterLevel(InfoLevel) 11 | } 12 | 13 | func (logger *Logger) WriterLevel(level Level) *io.PipeWriter { 14 | reader, writer := io.Pipe() 15 | 16 | var printFunc func(args ...interface{}) 17 | switch level { 18 | case DebugLevel: 19 | printFunc = logger.Debug 20 | case InfoLevel: 21 | printFunc = logger.Info 22 | case WarnLevel: 23 | printFunc = logger.Warn 24 | case ErrorLevel: 25 | printFunc = logger.Error 26 | case FatalLevel: 27 | printFunc = logger.Fatal 28 | case PanicLevel: 29 | printFunc = logger.Panic 30 | default: 31 | printFunc = logger.Print 32 | } 33 | 34 | go logger.writerScanner(reader, printFunc) 35 | runtime.SetFinalizer(writer, writerFinalizer) 36 | 37 | return writer 38 | } 39 | 40 | func (logger *Logger) writerScanner(reader *io.PipeReader, printFunc func(args ...interface{})) { 41 | scanner := bufio.NewScanner(reader) 42 | for scanner.Scan() { 43 | printFunc(scanner.Text()) 44 | } 45 | if err := scanner.Err(); err != nil { 46 | logger.Errorf("Error while reading from Writer: %s", err) 47 | } 48 | reader.Close() 49 | } 50 | 51 | func writerFinalizer(writer *io.PipeWriter) { 52 | writer.Close() 53 | } 54 | --------------------------------------------------------------------------------