diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2568ca3 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +.idea +.vscode +devenv +xdevenv +devenv +dist \ No newline at end of file diff --git a/.goreleaser.yml b/.goreleaser.yml new file mode 100644 index 0000000..070429c --- /dev/null +++ b/.goreleaser.yml @@ -0,0 +1,38 @@ +# This is an example goreleaser.yaml file with some sane defaults. +# Make sure to check the documentation at http://goreleaser.com +before: + hooks: + # You may remove this if you don't use go modules. + - go mod download + # you may remove this if you don't need go generate + - go generate ./... +builds: + - env: + - CGO_ENABLED=0 + goos: + - linux + - windows + - darwin + ignore: + - goos: windows + - goos: linux + goarch: 386 + - goos: darwin + goarch: 386 +archives: + - replacements: + darwin: Darwin + linux: Linux + windows: Windows + 386: i386 + amd64: x86_64 +checksum: + name_template: 'checksums.txt' +snapshot: + name_template: "{{ .Tag }}-next" +changelog: + sort: asc + filters: + exclude: + - '^docs:' + - '^test:' diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/Readme.MD b/Readme.MD new file mode 100644 index 0000000..b6b38ef --- /dev/null +++ b/Readme.MD @@ -0,0 +1,77 @@ +# Background + +Getting really tiresome to experiment `stuff` with multiple scripts. This is an attempt for one cli to rule them all + +Additionally it's is helping me learn how to write go command line interface using cobra (https://github.com/spf13/cobra) + +# Prerequisites + +## aws + +- [awsweb](https://github.com/glassechidna/awsweb) + +# How to add new commands + +`cobra add ` + +# Notes + +In order to use logger, make sure `startLog` is called first + +# Useful scripts + +remove images +``` +docker images --filter "reference=.dkr.ecr.ap-southeast-2.amazonaws.com/sample" --format "{{.ID}}"| %{ docker rmi $_ --force} +``` + +# Using + +## Deploy front proxy + +``` + devenv deploy --type front-proxy +``` + +## Deploy apps + +``` + devenv deploy appName --path +``` + +## Start environment + +``` + devenv start +``` + +## Stop environment + +``` + devenv stop +``` + +## Initialise environment + +``` + devenv init +``` + +## Tear down environment + +``` + devenv teardown +``` + +## Initialise configuration + +``` + devenv init config +``` + +## Ssh into ec2 instance + +``` + rm ~/.ssh/known_hosts + ssh -i ~/.ssh/ecs-instance-ap-southeast-2.pem ec2-user@ +``` \ No newline at end of file diff --git a/aws/app.yml b/aws/app.yml new file mode 100644 index 0000000..0844020 --- /dev/null +++ b/aws/app.yml @@ -0,0 +1,56 @@ +AWSTemplateFormatVersion: "2010-09-09" +Parameters: + AppName: + Type: String + Image: + Type: String + EcsClusterExportName: + Type: String + EnvironmentName: + Type: String + Default: devtest + Description: The name of the environment to add this service to +Resources: + CloudwatchLogsGroup: + Type: AWS::Logs::LogGroup + Properties: + LogGroupName: !Sub ${EnvironmentName}-${AppName} + RetentionInDays: 1 + TaskRole: + Type: AWS::IAM::Role + Properties: + AssumeRolePolicyDocument: + Statement: + - Effect: Allow + Principal: + Service: + - ecs-tasks.amazonaws.com + Action: + - sts:AssumeRole + Path: "/" + TaskDefinition: + Type: AWS::ECS::TaskDefinition + Properties: + TaskRoleArn: !GetAtt TaskRole.Arn + ContainerDefinitions: + - Name: !Ref AppName + Essential: true + Image: !Ref Image + Cpu: 128 + MemoryReservation: 512 + PortMappings: + - ContainerPort: 80 + LogConfiguration: + LogDriver: awslogs + Options: + awslogs-group: !Ref "CloudwatchLogsGroup" + awslogs-region: !Ref "AWS::Region" + awslogs-stream-prefix: !Ref AppName + Service: + Type: "AWS::ECS::Service" + Properties: + Cluster: + Fn::ImportValue: !Ref EcsClusterExportName + DesiredCount: 1 + TaskDefinition: !Ref TaskDefinition + ServiceName: !Ref AppName diff --git a/aws/ecr.yml b/aws/ecr.yml new file mode 100644 index 0000000..33f9b0f --- /dev/null +++ b/aws/ecr.yml @@ -0,0 +1,33 @@ +AWSTemplateFormatVersion: "2010-09-09" +Description: Creates ECR +Parameters: + RepositoryName: + Type: String +Resources: + Ecr: + Type: AWS::ECR::Repository + Properties: + RepositoryName: !Ref RepositoryName +Outputs: + ECRRepository: + Description: ECRepository + Value: + !Join [ + "/", + [ + !Join [ + ".", + [ + !Sub "${AWS::AccountId}", + "dkr", + "ecr", + !Sub "${AWS::Region}", + "amazonaws", + "com", + ], + ], + !Ref RepositoryName, + ], + ] + Export: + Name: !Ref "AWS::StackName" diff --git a/aws/ecsCluster.yml b/aws/ecsCluster.yml new file mode 100644 index 0000000..f795a8c --- /dev/null +++ b/aws/ecsCluster.yml @@ -0,0 +1,34 @@ +AWSTemplateFormatVersion: "2010-09-09" +Description: Ecs Cluster +Parameters: + ClusterName: + Type: String + Environment: + Type: String +Resources: + EcsCluster: + Type: AWS::ECS::Cluster + Properties: + ClusterName: !Ref ClusterName + Tags: + - Key: Environment + Value: !Ref Environment + EcsConfiguration: + Type: AWS::SSM::Parameter + Properties: + Name: !Join + - "/" + - - /allEnvs + - !Ref Environment + - infra/ecs + - name + Type: String + Description: ECS Cluster Name + Value: !Ref ClusterName + Tags: { Key: Environment, Value: !Ref Environment } +Outputs: + EcsCluster: + Description: The name of the AWS Region your template was launched in + Value: !Ref EcsCluster + Export: + Name: !Sub "${AWS::StackName}" diff --git a/aws/front-proxy/Dockerfile b/aws/front-proxy/Dockerfile new file mode 100644 index 0000000..5198f1f --- /dev/null +++ b/aws/front-proxy/Dockerfile @@ -0,0 +1,41 @@ +FROM python:alpine3.6 as builder +WORKDIR /build +RUN apk add --update \ + python-dev &&\ + pip install --upgrade pip && \ + pip install Jinja2 +RUN apk add curl +RUN apk del \ + python-dev \ + make && \ + rm -rf /var/cache/apk/* +RUN curl -fOL https://github.com/kahgeh/pscert/releases/download/v0.0.3/pscert_0.0.3_Linux_x86_64.tar.gz +RUN tar -xzf pscert_0.0.3_Linux_x86_64.tar.gz +ADD envoy-template.py . +ARG DOMAIN_NAME +ENV DOMAIN_NAME ${DOMAIN_NAME} +RUN python envoy-template.py + +FROM envoyproxy/envoy-alpine:v1.15-latest +ARG DOMAIN_EMAIL +ENV DOMAIN_EMAIL ${DOMAIN_EMAIL} +ARG DOMAIN_NAME +ENV DOMAIN_NAME ${DOMAIN_NAME} +ARG ENV_NAME +ENV ENV_NAME ${ENV_NAME} +ENV ENVOY_UID 0 +COPY --from=builder /build/envoy.yaml /etc/envoy +COPY --from=builder /build/pscert ./ +RUN chmod a+rw -R /etc/envoy +RUN chmod a+rw /etc/envoy/envoy.yaml +RUN chmod a+x ./pscert +ADD init-and-run.sh . +RUN chmod a+x ./init-and-run.sh +RUN mkdir -p /etc/letsencrypt/live +RUN chmod a+rw /etc/letsencrypt/live +RUN apk add --no-cache certbot +RUN apk add --no-cache curl +EXPOSE 80/tcp +EXPOSE 443/tcp +EXPOSE 9901/tcp +CMD ./init-and-run.sh diff --git a/aws/front-proxy/app.yml b/aws/front-proxy/app.yml new file mode 100644 index 0000000..7e4a9c1 --- /dev/null +++ b/aws/front-proxy/app.yml @@ -0,0 +1,102 @@ +AWSTemplateFormatVersion: "2010-09-09" +Parameters: + AppName: + Type: String + Default: front-proxy + Image: + Type: String + EcsClusterExportName: + Type: String + EnvironmentName: + Type: String + Default: devtest + Description: The name of the environment to add this service to + ParamStoreKeyArn: + Type: AWS::SSM::Parameter::Value +Resources: + CloudwatchLogsGroup: + Type: AWS::Logs::LogGroup + Properties: + LogGroupName: !Sub ${EnvironmentName}-${AppName} + RetentionInDays: 1 + TaskRole: + Type: AWS::IAM::Role + Properties: + AssumeRolePolicyDocument: + Statement: + - Effect: Allow + Principal: + Service: + - ecs-tasks.amazonaws.com + Action: + - sts:AssumeRole + Path: "/" + Policies: + - PolicyName: AllowGetParam + PolicyDocument: + Version: "2012-10-17" + Statement: + - Action: + - ssm:GetParametersByPath + - ssm:GetParameters + - ssm:GetParameter + Effect: Allow + Resource: + - !Sub arn:aws:ssm:${AWS::Region}:${AWS::AccountId}:parameter/allEnvs/${EnvironmentName}/ssl/* + - !Sub arn:aws:ssm:${AWS::Region}:${AWS::AccountId}:parameter/allEnvs/${EnvironmentName}/ssl + - PolicyName: AllowDecryptParam + PolicyDocument: + Version: "2012-10-17" + Statement: + - Action: kms:Decrypt + Effect: Allow + Resource: !Ref ParamStoreKeyArn + TaskDefinition: + Type: AWS::ECS::TaskDefinition + Properties: + TaskRoleArn: !GetAtt TaskRole.Arn + ContainerDefinitions: + - Name: !Ref AppName + Essential: 'true' + Image: !Ref Image + Cpu: 128 + MemoryReservation: 512 + LogConfiguration: + LogDriver: awslogs + Options: + awslogs-group: !Ref 'CloudwatchLogsGroup' + awslogs-region: !Ref 'AWS::Region' + awslogs-stream-prefix: !Sub "proxy" + PortMappings: + - ContainerPort: 80 + HostPort: 80 + - ContainerPort: 443 + HostPort: 443 + - ContainerPort: 9901 + HostPort: 9901 + Environment: + - Name: AWS_DEFAULT_REGION + Value: !Ref AWS::Region + - Name: AWS_REGION + Value: !Ref AWS::Region + Service: + Type: "AWS::ECS::Service" + Properties: + Cluster: + Fn::ImportValue: !Ref EcsClusterExportName + DesiredCount: 1 + TaskDefinition: !Ref TaskDefinition + ServiceName: !Ref AppName + Config: + Type: AWS::SSM::Parameter + Properties: + Name: !Join + - "/" + - - /allEnvs + - !Ref EnvironmentName + - apps + - !Ref AppName + - serviceArn + Type: String + Description: front proxy service arn + Value: !Ref Service diff --git a/aws/front-proxy/envoy-template.py b/aws/front-proxy/envoy-template.py new file mode 100644 index 0000000..2a4dc9b --- /dev/null +++ b/aws/front-proxy/envoy-template.py @@ -0,0 +1,129 @@ +from jinja2 import Template +import sys,os + +templateText=r""" +node: + cluster: test-cluster + id: test-id + +admin: + access_log_path: /dev/null + address: + socket_address: + address: 0.0.0.0 + port_value: 9901 + +dynamic_resources: + cds_config: + resource_api_version: V3 + api_config_source: + api_type: GRPC + transport_api_version: V3 + grpc_services: + - envoy_grpc: + cluster_name: xds_cluster + set_node_on_first_message_only: true +static_resources: + listeners: + - name: listener_http + address: + socket_address: { address: 0.0.0.0, port_value: 80 } + filter_chains: + - filters: + - name: envoy.filters.network.http_connection_manager + typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager + codec_type: AUTO + stat_prefix: ingress_http + route_config: + name: local_route + virtual_hosts: + - name: backend + domains: + - "{{DOMAIN_NAME}}" + routes: + - match: + prefix: "/" + redirect: + https_redirect: true + http_filters: + - name: envoy.filters.http.router + + - name: listener_https + address: + socket_address: { address: 0.0.0.0, port_value: 443 } + filter_chains: + - filters: + - name: envoy.filters.network.http_connection_manager + typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager + codec_type: AUTO + stat_prefix: ingress_http + rds: + config_source: + resource_api_version: V3 + api_config_source: + api_type: gRPC + transport_api_version: V3 + grpc_services: + - envoy_grpc: + cluster_name: xds_cluster + set_node_on_first_message_only: true + route_config_name: discovered_container_services + http_filters: + - name: envoy.filters.http.router + + transport_socket: + name: envoy.transport_sockets.tls + typed_config: + "@type": type.googleapis.com/envoy.extensions.transport_sockets.tls.v3.DownstreamTlsContext + common_tls_context: + tls_certificates: + - certificate_chain: + filename: "/etc/letsencrypt/live/{{DOMAIN_NAME}}/fullchain.pem" + private_key: + filename: "/etc/letsencrypt/live/{{DOMAIN_NAME}}/privkey.pem" + + clusters: + - connect_timeout: 1s + type: STATIC + load_assignment: + cluster_name: xds_cluster + endpoints: + - lb_endpoints: + - endpoint: + address: + socket_address: + address: REPlACE_HOSTADDRESS + port_value: 18000 + http2_protocol_options: {} + name: xds_cluster +layered_runtime: + layers: + - name: runtime-0 + rtds_layer: + rtds_config: + resource_api_version: V3 + api_config_source: + transport_api_version: V3 + api_type: GRPC + grpc_services: + envoy_grpc: + cluster_name: xds_cluster + name: runtime-0 +""" + +def render_template(templateText, templateTextFilePath): + template = Template(templateText) + for k, v in os.environ.items(): + template.globals[k]=v + currentAbsPath=os.path.abspath(templateTextFilePath) + path,filename=os.path.split(currentAbsPath) + renderedAbsPath = os.path.join(path, filename.replace("-template.py",".yaml")) + file =open(renderedAbsPath,"w") + print('content of {} : '.format(renderedAbsPath)) + content=template.render() + print(content) + file.write(content) + +render_template(templateText,__file__) \ No newline at end of file diff --git a/aws/front-proxy/init-and-run.sh b/aws/front-proxy/init-and-run.sh new file mode 100644 index 0000000..aa1ee8f --- /dev/null +++ b/aws/front-proxy/init-and-run.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env sh +set -e +./pscert save --domain-name $DOMAIN_NAME --domain-email $DOMAIN_EMAIL --key-id alias/aws/ssm --pstore-path /allEnvs/$ENV_NAME/ssl +hostAddress=$(curl http://169.254.169.254/latest/meta-data/local-ipv4) +sed -i "s/REPlACE_HOSTADDRESS/$hostAddress/g" /etc/envoy/envoy.yaml +envoy -c /etc/envoy/envoy.yaml \ No newline at end of file diff --git a/aws/publicIp.yml b/aws/publicIp.yml new file mode 100644 index 0000000..127a796 --- /dev/null +++ b/aws/publicIp.yml @@ -0,0 +1,25 @@ +AWSTemplateFormatVersion: "2010-09-09" +Parameters: + HostedZoneName: + Type: String + DomainName: + Type: String +Resources: + PublicIp: + Type: AWS::EC2::EIP + DnsRecord: + Type: AWS::Route53::RecordSetGroup + Properties: + HostedZoneName: !Ref HostedZoneName + RecordSets: + - Name: !Ref DomainName + Type: A + TTL: "900" + ResourceRecords: + - !Ref PublicIp +Outputs: + PublicIp: + Description: Public IP + Value: !Ref PublicIp + Export: + Name: PublicIp diff --git a/aws/spotFleet.yml b/aws/spotFleet.yml new file mode 100644 index 0000000..86cd8f9 --- /dev/null +++ b/aws/spotFleet.yml @@ -0,0 +1,239 @@ +AWSTemplateFormatVersion: "2010-09-09" +Description: Ecs Spot Fleet +Parameters: + ImageId: + Type: AWS::SSM::Parameter::Value + Default: /aws/service/ecs/optimized-ami/amazon-linux-2/recommended/image_id + EcsClusterName: + Type: String + KeyName: + Type: String + InstanceType: + Type: String + Default: m5ad.large + SpotPrice: + Type: String + Default: 0.10 + TargetCapacity: + Type: Number + Default: 0 + Environment: + Type: String + FleetType: + Type: String + DomainName: + Type: String +Resources: + CloudWatchLogsGroup: + Type: AWS::Logs::LogGroup + Properties: + RetentionInDays: 1 + LogGroupName: !Sub "${AWS::StackName}-lg" + InstanceSecurityGroup: + Type: AWS::EC2::SecurityGroup + Properties: + GroupDescription: Instance Security Group + VpcId: !ImportValue DevVpcId + SecurityGroupIngress: + - IpProtocol: tcp + FromPort: 1024 + ToPort: 61000 + CidrIp: 0.0.0.0/0 + - IpProtocol: tcp + FromPort: 22 + ToPort: 22 + CidrIp: 0.0.0.0/0 + - IpProtocol: tcp + FromPort: 80 + ToPort: 80 + CidrIp: 0.0.0.0/0 + - IpProtocol: tcp + FromPort: 443 + ToPort: 443 + CidrIp: 0.0.0.0/0 + InstanceProfile: + Properties: + Path: / + Roles: + - { Ref: InstanceRole } + Type: AWS::IAM::InstanceProfile + InstanceRole: + Properties: + AssumeRolePolicyDocument: + Statement: + - Action: ["sts:AssumeRole"] + Effect: Allow + Principal: + Service: [ec2.amazonaws.com] + Version: "2012-10-17" + ManagedPolicyArns: + - "arn:aws:iam::aws:policy/service-role/AmazonEC2ContainerServiceforEC2Role" + - !Sub "arn:${AWS::Partition}:iam::aws:policy/CloudWatchAgentServerPolicy" + Path: / + Policies: + - PolicyDocument: + Statement: + - Action: ec2:DescribeInstances + Effect: Allow + Resource: "*" + - Action: + [ + "ecr:DescribeRepositories", + "ecr:ListImages", + "ecr:InitiateLayerUpload", + "ecr:UploadLayerPart", + "ecr:CompleteLayerUpload", + "ecr:PutImage", + ] + Effect: Allow + Resource: + Fn::Join: + - "" + - - "arn:aws:ecr:" + - { Ref: "AWS::Region" } + - ":" + - { Ref: "AWS::AccountId" } + - :repository/* + Version: "2012-10-17" + PolicyName: ecs-custom-instance-policy + Type: AWS::IAM::Role + IamFleetRole: + Type: AWS::IAM::Role + Properties: + AssumeRolePolicyDocument: + Statement: + - Effect: Allow + Action: + - "sts:AssumeRole" + Principal: + Service: ["spotfleet.amazonaws.com"] + Path: "/" + ManagedPolicyArns: + ["arn:aws:iam::aws:policy/service-role/AmazonEC2SpotFleetTaggingRole"] + SpotFleet: + Type: AWS::EC2::SpotFleet + Properties: + SpotFleetRequestConfigData: + SpotPrice: !Ref SpotPrice + TargetCapacity: !Ref TargetCapacity + AllocationStrategy: lowestPrice + IamFleetRole: !GetAtt IamFleetRole.Arn + LaunchSpecifications: + - KeyName: !Ref KeyName + ImageId: !Ref ImageId + InstanceType: !Ref InstanceType + SubnetId: + Fn::Join: + - "," + - - !ImportValue DevSubnetAzAId + - !ImportValue DevSubnetAzBId + - !ImportValue DevSubnetAzCId + WeightedCapacity: 1 + IamInstanceProfile: { Arn: !GetAtt InstanceProfile.Arn } + SecurityGroups: + - { GroupId: !Ref InstanceSecurityGroup } + UserData: + Fn::Base64: !Sub | + #!/bin/bash -xe + yum install -y aws-cli + yum install -y amazon-cloudwatch-agent + + cat <<'EOF' >> /etc/ecs/ecs.config + ECS_CLUSTER=${EcsClusterName} + ECS_ENABLE_CONTAINER_METADATA=true + EOF + + curl -fOL https://github.com/kahgeh/whale-disco/releases/download/v0.0.3/whale-disco_0.0.3_Linux_x86_64.tar.gz + tar -xvf whale-disco_0.0.3_Linux_x86_64.tar.gz + cp whale-disco /usr/bin/ + chmod a+x /usr/bin/whale-disco + + rm whale-disco_0.0.3_Linux_x86_64.tar.gz + rm whale-disco + rm Readme.MD + + mkdir /var/log/whale-disco + cat <<'EOF' >> /lib/systemd/system/whale-disco.service + [Unit] + Description=Whale Disco - Docker Based Discovery + After=network.target + StartLimitIntervalSec=0 + [Service] + Type=simple + Restart=always + RestartSec=1 + User=root + StandardOutput=file:/var/log/whale-disco/logs.log + StandardError=file:/var/log/whale-disco/logs.log + ExecStart=/usr/bin/whale-disco -domain=${DomainName} + + [Install] + WantedBy=multi-user.target + EOF + + mkdir /cloudwatch + cat <<'EOF' >> /cloudwatch/config.json + { + "agent": { + "metrics_collection_interval": 60, + "logfile": "/opt/aws/amazon-cloudwatch-agent/logs/amazon-cloudwatch-agent.log" + }, + "logs": { + "logs_collected": { + "files": { + "collect_list": [ + { + "file_path": "/var/log/${AWS::StackName}/logs.log", + "log_group_name": "/${AWS::StackName}-lg/", + "log_stream_name": "whale-disco", + "timezone": "UTC" + } + ] + } + }, + "log_stream_name": "whale-disco", + "force_flush_interval" : 60 + } + } + EOF + + /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a fetch-config -m ec2 -c file:/cloudwatch/config.json -s + systemctl start whale-disco.service + SpotFleetConfiguration: + Type: AWS::SSM::Parameter + Properties: + Name: !Join + - "/" + - - /allEnvs + - !Ref Environment + - infra/spotfleet + - !Ref FleetType + Type: String + Description: !Sub "Spot fleet for ${FleetType} Instances" + Value: !Ref SpotFleet + Tags: { Key: Environment, Value: !Ref Environment } +Outputs: + AwsRegionName: + Description: The name of the AWS Region your template was launched in + Value: + Ref: AWS::Region + Export: + Name: !Sub "${AWS::StackName}-region" + CloudWatchLogsGroupName: + Description: Name of the CloudWatch Logs Group + Value: + Ref: CloudWatchLogsGroup + Export: + Name: !Sub "${AWS::StackName}-lg" + SpotFleetRequestId: + Description: The Spot fleet Request Id + Value: + Ref: SpotFleet + Export: + Name: !Sub "${AWS::StackName}-spotfleetrequest" + InstanceSecurityGroup: + Description: Instance security group + Value: + Ref: InstanceSecurityGroup + Export: + Name: !Sub "${AWS::StackName}-SecurityGroup" diff --git a/aws/vpc.yml b/aws/vpc.yml new file mode 100644 index 0000000..dad38ec --- /dev/null +++ b/aws/vpc.yml @@ -0,0 +1,119 @@ +AWSTemplateFormatVersion: "2010-09-09" +Resources: + DevVpc: + Type: AWS::EC2::VPC + Properties: + CidrBlock: 10.0.0.0/16 + EnableDnsSupport: true + EnableDnsHostnames: true + InstanceTenancy: default + Tags: + - Key: "Name" + Value: "DevVpc" + DevInternetGateway: + Type: "AWS::EC2::InternetGateway" + Properties: + Tags: + - Key: "Name" + Value: "DevInternetGateway" + DevSubnetAzA: + Type: AWS::EC2::Subnet + Properties: + CidrBlock: "10.0.2.0/24" + AvailabilityZone: !Select + - 0 + - Fn::GetAZs: !Ref "AWS::Region" + VpcId: !Ref DevVpc + MapPublicIpOnLaunch: true + DevSubnetAzB: + Type: AWS::EC2::Subnet + Properties: + CidrBlock: "10.0.3.0/24" + AvailabilityZone: !Select + - 1 + - Fn::GetAZs: !Ref "AWS::Region" + VpcId: !Ref DevVpc + MapPublicIpOnLaunch: true + DevSubnetAzC: + Type: AWS::EC2::Subnet + Properties: + CidrBlock: "10.0.4.0/24" + AvailabilityZone: !Select + - 2 + - Fn::GetAZs: !Ref "AWS::Region" + VpcId: !Ref DevVpc + MapPublicIpOnLaunch: true + DevRouteTable: + Type: AWS::EC2::RouteTable + Properties: + VpcId: !Ref DevVpc + DevInternetGatewayAttachment: + Type: "AWS::EC2::VPCGatewayAttachment" + Properties: + VpcId: !Ref DevVpc + InternetGatewayId: !Ref DevInternetGateway + DevVpcToInternetRoute: + Type: AWS::EC2::Route + Properties: + RouteTableId: !Ref DevRouteTable + DestinationCidrBlock: 0.0.0.0/0 + GatewayId: !Ref DevInternetGateway + DevSubnetAzARouteTableAssociation: + Type: AWS::EC2::SubnetRouteTableAssociation + Properties: + RouteTableId: !Ref DevRouteTable + SubnetId: !Ref DevSubnetAzA + DevSubnetAzBRouteTableAssociation: + Type: AWS::EC2::SubnetRouteTableAssociation + Properties: + RouteTableId: !Ref DevRouteTable + SubnetId: !Ref DevSubnetAzB + DevSubnetAzCRouteTableAssociation: + Type: AWS::EC2::SubnetRouteTableAssociation + Properties: + RouteTableId: !Ref DevRouteTable + SubnetId: !Ref DevSubnetAzC + DevDefaultSecurityGroup: + Type: AWS::EC2::SecurityGroup + Properties: + GroupDescription: "SSH and HTTP/S" + VpcId: !Ref DevVpc + SecurityGroupIngress: + - IpProtocol: tcp + FromPort: 22 + ToPort: 22 + CidrIp: 0.0.0.0/0 + - IpProtocol: tcp + FromPort: 80 + ToPort: 80 + CidrIp: 0.0.0.0/0 + - IpProtocol: tcp + FromPort: 443 + ToPort: 443 + CidrIp: 0.0.0.0/0 +Outputs: + DevVpcId: + Description: Vpc Id for Dev environment + Value: !Ref DevVpc + Export: + Name: DevVpcId + DevSubnetAzAId: + Description: Subnet for Dev environment + Value: !Ref DevSubnetAzA + Export: + Name: DevSubnetAzAId + DevSubnetAzBId: + Description: Subnet for Dev environment + Value: !Ref DevSubnetAzB + Export: + Name: DevSubnetAzBId + DevSubnetAzCId: + Description: Subnet for Dev environment + Value: !Ref DevSubnetAzC + Export: + Name: DevSubnetAzCId + DevDefaultSecurityGroup: + Description: Default security group for Dev environment + Value: !Ref DevDefaultSecurityGroup + Export: + Name: DevDefaultSecurityGroup diff --git a/cmd/deploy.go b/cmd/deploy.go new file mode 100644 index 0000000..ce68f96 --- /dev/null +++ b/cmd/deploy.go @@ -0,0 +1,103 @@ +/* +Copyright © 2020 NAME HERE + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +package cmd + +import ( + "fmt" + cmdTypes "github.com/kahgeh/devenv/cmd/types" + "github.com/kahgeh/devenv/provider/types" + "os" + "runtime/debug" + + "github.com/kahgeh/devenv/logger" + "github.com/spf13/cobra" + "github.com/spf13/viper" +) + +const ( + argPath cmdTypes.ArgName = "path" + argAppType cmdTypes.ArgName = "type" +) + +// deployCmd represents the deploy command +var deployCmd = &cobra.Command{ + Use: "deploy ", + Short: "deploy service", + Long: `deploy service +when + type is front-proxy, deploy will recreate the stack, also it will use http ports 80, 443`, + Run: deploy, +} + +func extractParameters(args []string) (appName string, appType types.AppType, path string, envName string, domainName string, domainEmail string, err error) { + appType = types.AppType(viper.GetString(string(argAppType))) + + if appType == types.FrontProxy { + appName = string(cmdTypes.KnownAppFrontProxy) + } else { + + if len(args) < 1 { + err = &cmdTypes.MissingArgument{ + ParameterName: "appName", + } + return + } + appName = args[0] + } + path = viper.GetString(string(argPath)) + envName = viper.GetString(string(cmdTypes.ArgEnvName)) + domainName = viper.GetString(string(cmdTypes.ArgDomainName)) + domainEmail = viper.GetString(string(cmdTypes.ArgDomainEmail)) + + return +} + +func deploy(_ *cobra.Command, args []string) { + startLog() + log := logger.New() + defer log.LogDone() + defer func() { + if err := recover(); err != nil { + log.Failf("%v", err) + log.Debugf("stacktrace : \n %v" + string(debug.Stack())) + } + }() + + appName, appType, path, envName, domainName, domainEmail, err := extractParameters(args) + if err != nil { + log.Fail(err.Error()) + } + + createSession().Deploy(&types.DeployParameters{ + AppType: appType, + AppName: appName, + Path: path, + DomainName: domainName, + DomainEmail: domainEmail, + EnvironmentName: envName, + }) +} + +func init() { + rootCmd.AddCommand(deployCmd) + deployCmd.PersistentFlags().String(string(argPath), ".", "--path ") + deployCmd.PersistentFlags().String(string(argAppType), "api", "--type [default is api - other options include front-proxy]") + err := viper.BindPFlags(deployCmd.PersistentFlags()) + if err != nil { + fmt.Printf("fail to bind command arguments\n %s", err.Error()) + os.Exit(logger.ExitFailureStatus) + } +} diff --git a/cmd/init.go b/cmd/init.go new file mode 100644 index 0000000..2fca3a8 --- /dev/null +++ b/cmd/init.go @@ -0,0 +1,107 @@ +/* +Copyright © 2020 NAME HERE + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +package cmd + +import ( + "fmt" + "github.com/kahgeh/devenv/fixed" + "github.com/kahgeh/devenv/logger" + "github.com/kahgeh/devenv/provider/types" + "github.com/kahgeh/devenv/utils" + "github.com/spf13/cobra" + "github.com/spf13/viper" + "runtime/debug" +) + +const ( + baseUrl string = "https://raw.githubusercontent.com/kahgeh/devenv/master" +) + +var cloudProviderFiles = map[string][]string{"aws": {"vpc.yml", "ecsCluster.yml", + "spotFleet.yml", "publicIp.yml", + "ecr.yml", "app.yml", "front-proxy/app.yml", "front-proxy/Dockerfile", "front-proxy/init-and-run.sh", "front-proxy/envoy-template.py"}} + +func initialiseConfig() { + log := logger.NewTaskLogger() + defer log.LogDone() + + configFolderPath := fixed.GetConfigFolderPath() + log.Infof("ensuring config folder '%s' exists...", configFolderPath) + err := utils.CreateFolderIfNotExist(configFolderPath) + if err != nil { + log.Debug(err.Error()) + log.Failf("fail to ensure %q exist", configFolderPath) + } + cloudProvider := "aws" + cloudProviderFolderPath := fmt.Sprintf("%v/%v", configFolderPath, cloudProvider) + log.Infof("ensuring provider config folder '%s' exists...", cloudProviderFolderPath) + err = utils.CreateFolderIfNotExist(cloudProviderFolderPath) + if err != nil { + log.Debug(err.Error()) + log.Failf("fail to ensure %q exist", cloudProviderFolderPath) + } + frontProxyFolderPath :=fmt.Sprintf("%v/front-proxy", cloudProviderFolderPath) + log.Infof("ensuring front proxy folder '%s' exists...", frontProxyFolderPath) + err = utils.CreateFolderIfNotExist(frontProxyFolderPath) + if err != nil { + log.Debug(err.Error()) + log.Failf("fail to ensure %q exist", frontProxyFolderPath) + } + + log.Info("downloading cloud provider files...") + for _, fileName := range cloudProviderFiles[cloudProvider] { + cloudProviderFilePath := fmt.Sprintf("%v/%v", cloudProvider, fileName) + download(baseUrl, fileName, cloudProviderFilePath) + } + log.Succeed() +} + +// initCmd represents the init command +var initCmd = &cobra.Command{ + Use: "init [config]", + Short: "initialises a vpc, spotfleet and an ecs cluster", + Long: `initialises infrastructure, does not cost to keep it`, + Run: initialise, +} + +func initialise(_ *cobra.Command, args []string) { + startLog() + log := logger.New() + defer log.LogDone() + defer func() { + if err := recover(); err != nil { + log.Failf("%v", err) + log.Debugf("stacktrace : \n %v" + string(debug.Stack())) + } + }() + + if len(args) == 1 && args[0] == "config" { + initialiseConfig() + return + } + domainName := viper.GetString("domain-name") + domainEmail := viper.GetString("domain-email") + envName := viper.GetString("env-name") + createSession().Initialise(&types.InitialisationParameters{ + DomainName: domainName, + DomainEmail: domainEmail, + EnvironmentName: envName, + }) +} + +func init() { + rootCmd.AddCommand(initCmd) +} diff --git a/cmd/root.go b/cmd/root.go new file mode 100644 index 0000000..7dc0b8a --- /dev/null +++ b/cmd/root.go @@ -0,0 +1,197 @@ +/* +Copyright © 2020 kahgeh + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +package cmd + +import ( + "bufio" + "fmt" + "github.com/kahgeh/devenv/cmd/types" + "github.com/kahgeh/devenv/utils" + "io" + "net/http" + "os" + + "github.com/kahgeh/devenv/fixed" + "github.com/kahgeh/devenv/logger" + "github.com/kahgeh/devenv/provider" + "github.com/spf13/cobra" + + "github.com/spf13/viper" +) + +var cfgFile string + +// rootCmd represents the base command when called without any subcommands +var rootCmd = &cobra.Command{ + Use: "devenv", + Short: "Tool to deploy apps to personal dev environments", + Long: ` + - init creates + - vpc + - spotfleet + - ecs cluster + - start + - spotfleet target instance count to 1 + - create public ip and attach to ecs instance + - schedule shutdown, spotfleet target instance count to 0 + - renews certificate + - front proxy + ecs discovery + - stop + - spotfleet set to 0, remove public ip, + - deploy + - httpapi (will start if not started and init if not available`, +} + +// Execute adds all child commands to the root command and sets flags appropriately. +// This is called by main.main(). It only needs to happen once to the rootCmd. +func Execute() { + if err := rootCmd.Execute(); err != nil { + fmt.Println(err) + os.Exit(1) + } +} + +var loglevelMap = map[string]logger.LogLevel{ + "info": logger.DetailedLogLevel, + "debug": logger.DebugLogLevel, +} + +func startLog() { + loglevelChoice := viper.GetString("loglevel") + var loglevel logger.LogLevel = logger.NormalLogLevel + if len(loglevelChoice) > 0 { + loglevel = loglevelMap[loglevelChoice] + } + logger.CreateLogger(loglevel) +} + +func download(baseUrl string, fileName string, outputPath string) bool { + log := logger.New() + defer log.LogDone() + sourceUrl := fmt.Sprintf("%s/aws/%s", baseUrl, fileName) + log.Debugf("url=%s", sourceUrl) + response, err := http.Get(sourceUrl) + if err != nil { + log.Failf("an error occured attempting to download %s", sourceUrl) + return false + } + defer utils.CloseReadCloser(response.Body, func(s string) { log.Debug(s) }) + configPath := fixed.GetConfigFolderPath() + filepath := fmt.Sprintf("%v/%v", configPath, outputPath) + // Create the file + out, err := os.Create(filepath) + if err != nil { + log.Failf("an error occured attempting to save %v \n %v", outputPath, err) + return false + } + defer utils.CloseReadCloser(out, func(s string) { log.Debug(s) }) + + // Write the body to file + _, err = io.Copy(out, response.Body) + log.Infof("downloaded %v", fileName) + return true +} + +func createSession() provider.Session { + log := logger.New() + defer log.LogDone() + providerName := provider.Aws + session, err := provider.NewSession(providerName) + if err != nil { + log.Failf("Cannot start provider(%v) session ", providerName) + return nil + } + return session +} + +// initConfig reads in config file and ENV variables if set. +func initConfig() { + cfgFilePath := cfgFile + if cfgFile != "" { + viper.SetConfigFile(cfgFile) + } else { + cfgFilePath = fmt.Sprintf("%s/config.yaml", fixed.GetConfigFolderPath()) + viper.SetConfigFile(cfgFilePath) + } + + viper.AutomaticEnv() + + if _, err := os.Stat(cfgFilePath); os.IsNotExist(err) { + reader := bufio.NewReader(os.Stdin) + fmt.Println("Provide the following details:") + fmt.Print("HostedZoneName: ") + hostedZoneName, consoleReadErr := reader.ReadString('\n') + if consoleReadErr != nil { + fmt.Println("failed to read user setting entries") + os.Exit(logger.ExitFailureStatus) + } + viper.Set("hosted-zone-name", hostedZoneName) + + fmt.Print("DomainName: ") + domainName, consoleReadErr := reader.ReadString('\n') + if consoleReadErr != nil { + fmt.Println("failed to read user setting entries") + os.Exit(logger.ExitFailureStatus) + } + viper.Set("domain-name", domainName) + + fmt.Print("DomainEmail: ") + domainEmail, consoleReadErr := reader.ReadString('\n') + if consoleReadErr != nil { + fmt.Println("failed to read user setting entries") + os.Exit(logger.ExitFailureStatus) + } + viper.Set("domain-email", domainEmail) + + fmt.Print("Environment name: ") + envName, consoleReadErr := reader.ReadString('\n') + if consoleReadErr != nil { + fmt.Println("failed to read user setting entries") + os.Exit(logger.ExitFailureStatus) + } + viper.Set("env-name", envName) + + err := viper.WriteConfigAs(cfgFilePath) + if err != nil { + fmt.Println(err.Error()) + } + } + + if err := viper.ReadInConfig(); err == nil { + fmt.Println("Using config file:", viper.ConfigFileUsed()) + } else { + fmt.Print(err.Error()) + } +} + +func init() { + + cobra.OnInitialize(initConfig) + + rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/config.yaml)") + rootCmd.PersistentFlags().String("loglevel", "", "info or debug") + rootCmd.PersistentFlags().String(string(types.ArgDomainName), "", "--domain-name ") + rootCmd.PersistentFlags().String(string(types.ArgDomainEmail), "", "--domain-email ") + rootCmd.PersistentFlags().String(string(types.ArgEnvName), "DevTest", "--env-name DevTest") + + rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") + err := viper.BindPFlags(rootCmd.PersistentFlags()) + if err != nil { + fmt.Printf("fail to bind arguments to command \n %s", err.Error()) + os.Exit(logger.ExitFailureStatus) + } + +} diff --git a/cmd/start.go b/cmd/start.go new file mode 100644 index 0000000..0ca007b --- /dev/null +++ b/cmd/start.go @@ -0,0 +1,72 @@ +/* +Copyright © 2020 NAME HERE + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +package cmd + +import ( + "fmt" + "github.com/kahgeh/devenv/provider/types" + "os" + "runtime/debug" + + "github.com/kahgeh/devenv/logger" + "github.com/spf13/cobra" + "github.com/spf13/viper" +) + +// startCmd represents the start command +var startCmd = &cobra.Command{ + Use: "start", + Short: "A brief description of your command", + Long: `A longer description that spans multiple lines and likely contains examples +and usage of using your command. For example: + +Cobra is a CLI library for Go that empowers applications. +This application is a tool to generate the needed files +to quickly create a Cobra application.`, + Run: start, +} + +func mapParameters(_ []string) *types.StartParameters { + return &types.StartParameters{ + HostedZoneName: viper.GetString("hosted-zone-name"), + DomainName: viper.GetString("domain-name"), + EnvironmentName: viper.GetString("env-name"), + } +} + +func start(_ *cobra.Command, args []string) { + startLog() + log := logger.New() + defer log.LogDone() + defer func() { + if err := recover(); err != nil { + log.Failf("%v", err) + log.Debugf("stacktrace : \n %v" + string(debug.Stack())) + } + }() + parameters := mapParameters(args) + createSession().Start(parameters) +} + +func init() { + rootCmd.AddCommand(startCmd) + startCmd.PersistentFlags().String("hosted-zone-name", "", "--hosted-zone-name xyz.com. , remember to include the period at the end") + err := viper.BindPFlags(deployCmd.PersistentFlags()) + if err != nil { + fmt.Printf("fail to bind command arguments\n %s", err.Error()) + os.Exit(logger.ExitFailureStatus) + } +} diff --git a/cmd/stop.go b/cmd/stop.go new file mode 100644 index 0000000..b87f8a2 --- /dev/null +++ b/cmd/stop.go @@ -0,0 +1,49 @@ +/* +Copyright © 2020 NAME HERE + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +package cmd + +import ( + "runtime/debug" + + "github.com/kahgeh/devenv/logger" + "github.com/spf13/cobra" +) + +// stopCmd represents the stop command +var stopCmd = &cobra.Command{ + Use: "stop", + Short: "remove instance and attached resource", + Long: `remove instance and attached resource`, + Run: stop, +} + +func stop(_ *cobra.Command, _ []string) { + startLog() + log := logger.New() + defer log.LogDone() + defer func() { + if err := recover(); err != nil { + log.Failf("%v", err) + log.Debugf("stacktrace : \n %v" + string(debug.Stack())) + } + }() + + createSession().Stop() +} +func init() { + rootCmd.AddCommand(stopCmd) + +} diff --git a/cmd/teardown.go b/cmd/teardown.go new file mode 100644 index 0000000..ff289a8 --- /dev/null +++ b/cmd/teardown.go @@ -0,0 +1,47 @@ +/* +Copyright © 2020 NAME HERE + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +package cmd + +import ( + "runtime/debug" + + "github.com/kahgeh/devenv/logger" + "github.com/spf13/cobra" +) + +// deInitCmd represents the reset command +var teardownCmd = &cobra.Command{ + Use: "teardown", + Short: "Tear down the environment", + Long: `Tear down the environment.`, + Run: tearDown, +} + +func tearDown(_ *cobra.Command, _ []string) { + startLog() + log := logger.New() + defer func() { + if err := recover(); err != nil { + log.Debug(err) + log.Debugf("stacktrace : \n %v" + string(debug.Stack())) + } + }() + createSession().Delete() +} + +func init() { + rootCmd.AddCommand(teardownCmd) +} diff --git a/cmd/types/types.go b/cmd/types/types.go new file mode 100644 index 0000000..d41069d --- /dev/null +++ b/cmd/types/types.go @@ -0,0 +1,25 @@ +package types + +import "fmt" + +type ArgName string + +const ( + ArgEnvName ArgName = "env-name" + ArgDomainName ArgName = "domain-name" + ArgDomainEmail ArgName = "domain-email" +) + +type KnownApp string + +const ( + KnownAppFrontProxy KnownApp = "front-proxy" +) + +type MissingArgument struct { + ParameterName string +} + +func (e *MissingArgument) Error() string { + return fmt.Sprintf("%q is required", e.ParameterName) +} diff --git a/fixed/fixed.go b/fixed/fixed.go new file mode 100644 index 0000000..fccf191 --- /dev/null +++ b/fixed/fixed.go @@ -0,0 +1,18 @@ +package fixed + +import ( + "fmt" + "os" + + "github.com/mitchellh/go-homedir" +) + +func GetConfigFolderPath() string { + home, err := homedir.Dir() + if err != nil { + fmt.Println(err) + os.Exit(1) + } + + return fmt.Sprintf("%v/.devenv", home) +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..78f76dc --- /dev/null +++ b/go.mod @@ -0,0 +1,26 @@ +module github.com/kahgeh/devenv + +go 1.15 + +require ( + github.com/Azure/go-ansiterm v0.0.0-20170929234023-d6e3b3328b78 // indirect + github.com/Microsoft/hcsshim v0.8.10 // indirect + github.com/aws/aws-sdk-go-v2 v0.24.0 + github.com/containerd/continuity v0.0.0-20200710164510-efbc4488d8fe // indirect + github.com/docker/distribution v2.7.1+incompatible // indirect + github.com/docker/docker v1.13.1 + github.com/docker/engine v17.12.0-ce-rc1.0.20200618181300-9dc6525e6118+incompatible + github.com/docker/go-connections v0.4.0 // indirect + github.com/docker/go-units v0.4.0 // indirect + github.com/mattn/go-runewidth v0.0.9 // indirect + github.com/mitchellh/go-homedir v1.1.0 + github.com/morikuni/aec v1.0.0 // indirect + github.com/opencontainers/go-digest v1.0.0 // indirect + github.com/opencontainers/image-spec v1.0.1 // indirect + github.com/opencontainers/runc v0.1.1 // indirect + github.com/spf13/cobra v1.0.0 + github.com/spf13/viper v1.7.1 + github.com/theckman/yacspin v0.8.0 + go.uber.org/zap v1.15.0 +) +replace github.com/docker/docker => github.com/docker/engine v17.12.0-ce-rc1.0.20190717161051-705d9623b7c1+incompatible \ No newline at end of file diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..3ad7dd1 --- /dev/null +++ b/go.sum @@ -0,0 +1,416 @@ +bazil.org/fuse v0.0.0-20160811212531-371fbbdaa898/go.mod h1:Xbm+BRKSBEpa4q4hTSxohYNQpsxXPbPry4JJWOB3LB8= +cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cloud.google.com/go v0.38.0/go.mod h1:990N+gfupTy94rShfmMCWGDn0LpTmnzTp2qbd1dvSRU= +cloud.google.com/go v0.44.1/go.mod h1:iSa0KzasP4Uvy3f1mN/7PiObzGgflwredwwASm/v6AU= +cloud.google.com/go v0.44.2/go.mod h1:60680Gw3Yr4ikxnPRS/oxxkBccT6SA1yMk63TGekxKY= +cloud.google.com/go v0.45.1/go.mod h1:RpBamKRgapWJb87xiFSdk4g1CME7QZg3uwTez+TSTjc= +cloud.google.com/go v0.46.3/go.mod h1:a6bKKbmY7er1mI7TEI4lsAkts/mkhTSZK8w33B4RAg0= +cloud.google.com/go/bigquery v1.0.1/go.mod h1:i/xbL2UlR5RvWAURpBYZTtm/cXjCha9lbfbpx4poX+o= +cloud.google.com/go/datastore v1.0.0/go.mod h1:LXYbyblFSglQ5pkeyhO+Qmw7ukd3C+pD7TKLgZqpHYE= +cloud.google.com/go/firestore v1.1.0/go.mod h1:ulACoGHTpvq5r8rxGJ4ddJZBZqakUQqClKRT5SZwBmk= +cloud.google.com/go/pubsub v1.0.1/go.mod h1:R0Gpsv3s54REJCy4fxDixWD93lHJMoZTyQ2kNxGRt3I= +cloud.google.com/go/storage v1.0.0/go.mod h1:IhtSnM/ZTZV8YYJWCY8RULGVqBDmpoyjwiyrjsg+URw= +dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= +github.com/Azure/go-ansiterm v0.0.0-20170929234023-d6e3b3328b78/go.mod h1:LmzpDX56iTiv29bbRTIsUNlaFfuhWRQBWjQdVyAevI8= +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= +github.com/Microsoft/go-winio v0.4.15-0.20200908182639-5b44b70ab3ab/go.mod h1:tTuCMEN+UleMWgg9dVx4Hu52b1bJo+59jBh3ajtinzw= +github.com/Microsoft/hcsshim v0.8.10/go.mod h1:g5uw8EV2mAlzqe94tfNBNdr89fnbD/n3HV0OhsddkmM= +github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU= +github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= +github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= +github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o= +github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= +github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY= +github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= +github.com/aws/aws-sdk-go-v2 v0.24.0 h1:R0lL0krk9EyTI1vmO1ycoeceGZotSzCKO51LbPGq3rU= +github.com/aws/aws-sdk-go-v2 v0.24.0/go.mod h1:2LhT7UgHOXK3UXONKI5OMgIyoQL6zTAw/jwIeX6yqzw= +github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= +github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= +github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= +github.com/bketelsen/crypt v0.0.3-0.20200106085610-5cbc8cc4026c/go.mod h1:MKsuJmJgSg28kpZDP6UIiPt0e0Oz0kqKNGyRaWEPv84= +github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc= +github.com/cilium/ebpf v0.0.0-20200110133405-4032b1d8aae3/go.mod h1:MA5e5Lr8slmEg9bt0VpxxWqJlO4iwu3FBdHUzV7wQVg= +github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/containerd/cgroups v0.0.0-20200531161412-0dbf7f05ba59/go.mod h1:pA0z1pT8KYB3TCXK/ocprsh7MAkoW8bZVzPdih9snmM= +github.com/containerd/console v0.0.0-20180822173158-c12b1e7919c1/go.mod h1:Tj/on1eG8kiEhd0+fhSDzsPAFESxzBBvdyEgyryXffw= +github.com/containerd/containerd v1.3.2/go.mod h1:bC6axHOhabU15QhwfG7w5PipXdVtMXFTttgp+kVtyUA= +github.com/containerd/continuity v0.0.0-20190426062206-aaeac12a7ffc/go.mod h1:GL3xCUCBDV3CZiTSEKksMWbLE66hEyuu9qyDOOqM47Y= +github.com/containerd/continuity v0.0.0-20200710164510-efbc4488d8fe h1:PEmIrUvwG9Yyv+0WKZqjXfSFDeZjs/q15g0m08BYS9k= +github.com/containerd/continuity v0.0.0-20200710164510-efbc4488d8fe/go.mod h1:cECdGN1O8G9bgKTlLhuPJimka6Xb/Gg7vYzCTNVxhvo= +github.com/containerd/fifo v0.0.0-20190226154929-a9fb20d87448/go.mod h1:ODA38xgv3Kuk8dQz2ZQXpnv/UZZUHUCL7pnLehbXgQI= +github.com/containerd/go-runc v0.0.0-20180907222934-5a6d9f37cfa3/go.mod h1:IV7qH3hrUgRmyYrtgEeGWJfWbgcHL9CSRruz2Vqcph0= +github.com/containerd/ttrpc v0.0.0-20190828154514-0e0f228740de/go.mod h1:PvCDdDGpgqzQIzDW1TphrGLssLDZp2GuS+X5DkEJB8o= +github.com/containerd/typeurl v0.0.0-20180627222232-a93fcdb778cd/go.mod h1:Cm3kwCdlkCfMSHURc+r6fwoGH6/F1hH3S4sg0rLFWPc= +github.com/coreos/bbolt v1.3.2/go.mod h1:iRUV2dpdMOn7Bo10OQBFzIJO9kkE559Wcmn+qkEiiKk= +github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= +github.com/coreos/etcd v3.3.13+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= +github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= +github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= +github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= +github.com/coreos/go-systemd/v22 v22.0.0/go.mod h1:xO0FLkIi5MaZafQlIrOotqXZ90ih+1atmu1JpKERPPk= +github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= +github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= +github.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= +github.com/dgryski/go-sip13 v0.0.0-20181026042036-e10d5fee7954/go.mod h1:vAd38F8PWV+bWy6jNmig1y/TA+kYO4g3RSRF0IAv0no= +github.com/docker/distribution v2.7.1+incompatible h1:a5mlkVzth6W5A4fOsS3D2EO5BUmsJpcB+cRlLU7cSug= +github.com/docker/distribution v2.7.1+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w= +github.com/docker/engine v17.12.0-ce-rc1.0.20190717161051-705d9623b7c1+incompatible h1:4Pnn+RsurVEiBbmqlRtzh77HLMiP4NaaqRHOOK4aPj8= +github.com/docker/engine v17.12.0-ce-rc1.0.20190717161051-705d9623b7c1+incompatible/go.mod h1:3CPr2caMgTHxxIAZgEMd3uLYPDlRvPqCpyeRf6ncPcY= +github.com/docker/engine v17.12.0-ce-rc1.0.20200618181300-9dc6525e6118+incompatible/go.mod h1:3CPr2caMgTHxxIAZgEMd3uLYPDlRvPqCpyeRf6ncPcY= +github.com/docker/go-connections v0.4.0 h1:El9xVISelRB7BuFusrZozjnkIM5YnzCViNKohAFqRJQ= +github.com/docker/go-connections v0.4.0/go.mod h1:Gbd7IOopHjR8Iph03tsViu4nIes5XhDvyHbTtUxmeec= +github.com/docker/go-units v0.4.0 h1:3uh0PgVws3nIA0Q+MwDC8yjEPf9zjRfZZWXZYDct3Tw= +github.com/docker/go-units v0.4.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= +github.com/dustin/go-humanize v0.0.0-20171111073723-bb3d318650d4/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= +github.com/fatih/color v1.7.0 h1:DkWD4oS2D8LGGgTQ6IvwJJXSL5Vp2ffcQg58nFV38Ys= +github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= +github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I= +github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= +github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= +github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= +github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= +github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= +github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= +github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= +github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= +github.com/godbus/dbus/v5 v5.0.3/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= +github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= +github.com/gogo/protobuf v1.2.1/go.mod h1:hp+jE20tsWTFYpLwKvXlhS1hjn+gTNwPg2I6zVXpSg4= +github.com/gogo/protobuf v1.3.1 h1:DqDEcV5aeaTmdFBePNpYsp3FlcVH/2ISVVM9Qf8PSls= +github.com/gogo/protobuf v1.3.1/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/groupcache v0.0.0-20190129154638-5b532d6fd5ef/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/mock v1.3.1/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.2 h1:6nsPYzhq5kReh6QImI3k5qWzO4PEbvbIW2cwSfR/6xs= +github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= +github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= +github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= +github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= +github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= +github.com/google/pprof v0.0.0-20190515194954-54271f7e092f/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= +github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= +github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= +github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= +github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= +github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= +github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +github.com/grpc-ecosystem/go-grpc-middleware v1.0.0/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs= +github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk= +github.com/grpc-ecosystem/grpc-gateway v1.9.0/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= +github.com/hashicorp/consul/api v1.1.0/go.mod h1:VmuI/Lkw1nC05EYQWNKwWGbkg+FbDBtguAZLlVdkD9Q= +github.com/hashicorp/consul/sdk v0.1.1/go.mod h1:VKf9jXwCTEY1QZP2MOLRhb5i/I/ssyNV1vwHyQBF0x8= +github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= +github.com/hashicorp/go-cleanhttp v0.5.1/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= +github.com/hashicorp/go-immutable-radix v1.0.0/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60= +github.com/hashicorp/go-msgpack v0.5.3/go.mod h1:ahLV/dePpqEmjfWmKiqvPkv/twdG7iPBM1vqhUKIvfM= +github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk= +github.com/hashicorp/go-rootcerts v1.0.0/go.mod h1:K6zTfqpRlCUIjkwsN4Z+hiSfzSTQa6eBIzfwKfwNnHU= +github.com/hashicorp/go-sockaddr v1.0.0/go.mod h1:7Xibr9yA9JjQq1JpNB2Vw7kxv8xerXegt+ozgdvDeDU= +github.com/hashicorp/go-syslog v1.0.0/go.mod h1:qPfqrKkXGihmCqbJM2mZgkZGvKG1dFdvsLplgctolz4= +github.com/hashicorp/go-uuid v1.0.0/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= +github.com/hashicorp/go-uuid v1.0.1/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= +github.com/hashicorp/go.net v0.0.1/go.mod h1:hjKkEWcCURg++eb33jQU7oqQcI9XDCnUzHA0oac0k90= +github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= +github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= +github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= +github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= +github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO+LraFDTW64= +github.com/hashicorp/mdns v1.0.0/go.mod h1:tL+uN++7HEJ6SQLQ2/p+z2pH24WQKWjBPkE0mNTz8vQ= +github.com/hashicorp/memberlist v0.1.3/go.mod h1:ajVTdAv/9Im8oMAAj5G31PhhMCZJV2pPBoIllUwCN7I= +github.com/hashicorp/serf v0.8.2/go.mod h1:6hOLApaqBFA1NXqRQAsxw9QxuDEvNxSQRwA/JwenrHc= +github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= +github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= +github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af h1:pmfjZENx5imkbgOkpRUYLnmbU7UEFbjtDA2hxJ1ichM= +github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= +github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo= +github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= +github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= +github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= +github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= +github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvWXihfKN4Q= +github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00= +github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= +github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= +github.com/magiconair/properties v1.8.1 h1:ZC2Vc7/ZFkGmsVC9KvOjumD+G5lXy2RtTKyzRKO2BQ4= +github.com/magiconair/properties v1.8.1/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= +github.com/mattn/go-colorable v0.0.9 h1:UVL0vNpWh04HeJXV0KLcaT7r06gOH2l4OW6ddYRUIY4= +github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= +github.com/mattn/go-isatty v0.0.3 h1:ns/ykhmWi7G9O+8a448SecJU3nSMBXJfqQkl0upE1jI= +github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= +github.com/mattn/go-runewidth v0.0.9 h1:Lm995f3rfxdpd6TSmuVCHVb/QhupuXlYr8sCI/QdE+0= +github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= +github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= +github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg= +github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc= +github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= +github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= +github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= +github.com/mitchellh/go-testing-interface v1.0.0/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI= +github.com/mitchellh/gox v0.4.0/go.mod h1:Sd9lOJ0+aimLBi73mGofS1ycjY8lL3uZM3JPS42BGNg= +github.com/mitchellh/iochan v1.0.0/go.mod h1:JwYml1nuB7xOzsp52dPpHFffvOCDupsG0QubkSMEySY= +github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= +github.com/mitchellh/mapstructure v1.1.2 h1:fmNYVwqnSfB9mZU6OS2O6GsXM+wcskZDuKQzvN1EDeE= +github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/morikuni/aec v1.0.0 h1:nP9CBfwrvYnBRgY6qfDQkygYDmYwOilePFkwzv4dU8A= +github.com/morikuni/aec v1.0.0/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc= +github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= +github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U= +github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.10.1/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/gomega v1.7.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= +github.com/opencontainers/go-digest v0.0.0-20180430190053-c9281466c8b2/go.mod h1:cMLVZDEM3+U2I4VmLI6N8jQYUd2OVphdqWwCJHrFt2s= +github.com/opencontainers/go-digest v1.0.0-rc1/go.mod h1:cMLVZDEM3+U2I4VmLI6N8jQYUd2OVphdqWwCJHrFt2s= +github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U= +github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= +github.com/opencontainers/image-spec v1.0.1 h1:JMemWkRwHx4Zj+fVxWoMCFm/8sYGGrUVojFA6h/TRcI= +github.com/opencontainers/image-spec v1.0.1/go.mod h1:BtxoFyWECRxE4U/7sNtV5W15zMzWCbyJoFRP3s7yZA0= +github.com/opencontainers/runc v0.0.0-20190115041553-12f6a991201f/go.mod h1:qT5XzbpPznkRYVz/mWwUaVBUv2rmF59PVA73FjuZG0U= +github.com/opencontainers/runc v0.1.1 h1:GlxAyO6x8rfZYN9Tt0Kti5a/cP41iuiO2yYT0IJGY8Y= +github.com/opencontainers/runc v0.1.1/go.mod h1:qT5XzbpPznkRYVz/mWwUaVBUv2rmF59PVA73FjuZG0U= +github.com/opencontainers/runtime-spec v1.0.2/go.mod h1:jwyrGlmzljRJv/Fgzds9SsS/C5hL+LL3ko9hs6T5lQ0= +github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= +github.com/pelletier/go-toml v1.2.0 h1:T5zMGML61Wp+FlcbWjRDT7yAxhJNAiPPLOFECq181zc= +github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= +github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/errors v0.8.1-0.20171018195549-f15c970de5b7/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI= +github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= +github.com/prometheus/client_golang v0.9.3/go.mod h1:/TN21ttK/J9q6uSwhBd54HahCDft0ttaMvbicHlPoso= +github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= +github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/common v0.0.0-20181113130724-41aa239b4cce/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro= +github.com/prometheus/common v0.4.0/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= +github.com/prometheus/procfs v0.0.0-20180125133057-cb4147076ac7/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= +github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= +github.com/prometheus/procfs v0.0.0-20190507164030-5867b95ac084/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= +github.com/prometheus/tsdb v0.7.1/go.mod h1:qhTCs0VvXwvX/y3TZrWD7rabWM+ijKTux40TwIPHuXU= +github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg= +github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= +github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= +github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= +github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= +github.com/sirupsen/logrus v1.0.4-0.20170822132746-89742aefa4b2/go.mod h1:pMByvHTf9Beacp5x1UXfOR9xyW/9antXMhjMPG0dEzc= +github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= +github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMBDgk/93Q= +github.com/sirupsen/logrus v1.4.2 h1:SPIRibHv4MatM3XXNO2BJeFLZwZ2LvZgfQ5+UNI2im4= +github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= +github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= +github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= +github.com/soheilhy/cmux v0.1.4/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4kGIyLM= +github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= +github.com/spf13/afero v1.1.2 h1:m8/z1t7/fwjysjQRYbP0RD+bUIF/8tJwPdEZsI83ACI= +github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= +github.com/spf13/cast v1.3.0 h1:oget//CVOEoFewqQxwr0Ej5yjygnqGkvggSE/gB35Q8= +github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= +github.com/spf13/cobra v0.0.2-0.20171109065643-2da4a54c5cee/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ= +github.com/spf13/cobra v1.0.0 h1:6m/oheQuQ13N9ks4hubMG6BnvwOeaJrqSPLahSnczz8= +github.com/spf13/cobra v1.0.0/go.mod h1:/6GTrnGXV9HjY+aR4k0oJ5tcvakLuG6EuKReYlHNrgE= +github.com/spf13/jwalterweatherman v1.0.0 h1:XHEdyB+EcvlqZamSM4ZOMGlc93t6AcsBEu9Gc1vn7yk= +github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= +github.com/spf13/pflag v1.0.1-0.20171106142849-4c012f6dcd95/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= +github.com/spf13/pflag v1.0.3 h1:zPAT6CGy6wXeQ7NtTnaTerfKOsV6V6F8agHXFiazDkg= +github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= +github.com/spf13/viper v1.4.0/go.mod h1:PTJ7Z/lr49W6bUbkmS1V3by4uWynFiR9p7+dSq/yZzE= +github.com/spf13/viper v1.7.1 h1:pM5oEahlgWv/WnHXpgbKz7iLIxRf65tye2Ci+XFK5sk= +github.com/spf13/viper v1.7.1/go.mod h1:8WkrPz2fc9jxqZNCJI/76HCieCp4Q8HaLFoCha5qpdg= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/subosito/gotenv v1.2.0 h1:Slr1R9HxAlEKefgq5jn9U+DnETlIUa6HfgEzj0g5d7s= +github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw= +github.com/theckman/yacspin v0.8.0 h1:9LA2kUol1/+eH5m/ptlbYCrnCEfLCaX4Xn+5tK/AprI= +github.com/theckman/yacspin v0.8.0/go.mod h1:K1H1naXCpDytqETpvmlxWzAq8BbOMy3Wrd0iy0ZNzRI= +github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= +github.com/ugorji/go v1.1.4/go.mod h1:uQMGLiO92mf5W77hV/PUCpI3pbzQx3CRekS0kk+RGrc= +github.com/urfave/cli v1.22.2/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0= +github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= +github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q= +go.etcd.io/bbolt v1.3.2/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= +go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= +go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= +go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= +go.uber.org/atomic v1.6.0 h1:Ezj3JGmsOnG1MoRWQkPBsKLe9DwWD9QeXzTRzzldNVk= +go.uber.org/atomic v1.6.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= +go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0= +go.uber.org/multierr v1.5.0 h1:KCa4XfM8CWFCpxXRGok+Q0SS/0XBhMDbHHGABQLvD2A= +go.uber.org/multierr v1.5.0/go.mod h1:FeouvMocqHpRaaGuG9EjoKcStLC43Zu/fmqdUMPcKYU= +go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9Ejo0C68/HhF8uaILCdgjnY+goOA= +go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= +go.uber.org/zap v1.15.0 h1:ZZCA22JRF2gQE5FoNmhmrf7jeJJ2uhqDUNRYKm8dvmM= +go.uber.org/zap v1.15.0/go.mod h1:Mb2vm2krFEG5DV0W9qcHBYFtp/Wku1cvYaqPsS/WYfc= +golang.org/x/crypto v0.0.0-20171113213409-9f005a07e0d3/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20181029021203-45a5f77698d3/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= +golang.org/x/exp v0.0.0-20190829153037-c13cbed26979/go.mod h1:86+5VVa7VpoJ4kLfm080zCjGlMRFzhUhsZKEZO7MGek= +golang.org/x/exp v0.0.0-20191030013958-a1ab85dbe136/go.mod h1:JXzH8nQsPlswgeRAPE3MuO9GYsAcnJvJ4vnMwN/5qkY= +golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= +golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= +golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= +golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190409202823-959b441ac422/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190909230951-414d861bb4ac/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE= +golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o= +golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= +golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181023162649-9b4f9f5ad519/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181201002055-351d144fa1fc/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181220203305-927f97764cc3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190501004415-9ce7a6920f09/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190522155817-f3200d17e092/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= +golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20191004110552-13f9640d40b9/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200202094626-16171245cfb2 h1:CCH4IOTTfewWjGOlSp+zGcjutRKlBEZQ6wTn8ozI/nI= +golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58 h1:8gQV6CLnAEikrhgkHFbMAEhagSSnXWGV915qUMm9mrU= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181026203630-95b1ffbd15a5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181107165924-66b7b1311ac8/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191022100944-742c48ecaeb7/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200120151820-655fe14d7479 h1:LhLiKguPgZL+Tglay4GhVtfF0kb8cvOJ0dHTCBO8YNI= +golang.org/x/sys v0.0.0-20200120151820-655fe14d7479/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs= +golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= +golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190506145303-2d16b83fe98c/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190606124116-d0a3d012864b/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20190628153133-6cdbf07be9d0/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20190816200558-6889da9d5479/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20190911174233-4f2ddba30aff/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191012152004-8de300cfc20a/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191029041327-9cc4af7d6b2c/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191112195655-aa38f8e97acc/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE= +google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E3M= +google.golang.org/api v0.8.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= +google.golang.org/api v0.9.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= +google.golang.org/api v0.13.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= +google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/appengine v1.6.1/go.mod h1:i06prIuMbXzDqacNJfV5OdTW448YApPu5ww/cMBSeb0= +google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190418145605-e7d98fc518a7/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190502173448-54afdca5d873/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190801165951-fa694d86fc64/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/genproto v0.0.0-20190911173649-1774047e7e51/go.mod h1:IbNlFCBrqXvoKpeg0TB2l7cyZUmoaFKYIwrEpbDKLA8= +google.golang.org/genproto v0.0.0-20191108220845-16a3f7862a1a h1:Ob5/580gVHBJZgXnff1cZDbG+xLtMVE5mDRTe+nIsX4= +google.golang.org/genproto v0.0.0-20191108220845-16a3f7862a1a/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= +google.golang.org/grpc v1.21.0/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= +google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= +google.golang.org/grpc v1.23.1 h1:q4XQuHFC6I28BKZpo6IYyb3mNO+l7lSOxRuYTCiDfXk= +google.golang.org/grpc v1.23.1/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +gopkg.in/airbrake/gobrake.v2 v2.0.9/go.mod h1:/h5ZAUhDkGaJfjzjKLSjv6zCL6O0LLBxU4K+aSYdM/U= +gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= +gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= +gopkg.in/gemnasium/logrus-airbrake-hook.v2 v2.1.2/go.mod h1:Xk6kEKp8OKb+X14hQBKWaSkCsqBpgog8nAV2xsGOxlo= +gopkg.in/ini.v1 v1.51.0 h1:AQvPpx3LzTDM0AjnIRlVFwFFGC+npRopjZxLJj6gdno= +gopkg.in/ini.v1 v1.51.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= +gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= +gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74= +gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gotest.tools v2.2.0+incompatible/go.mod h1:DsYFclhRJ6vuDpmuTbkuFWG+y2sxOXAzmJt81HFBacw= +honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= +rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8= diff --git a/lang/lang.go b/lang/lang.go new file mode 100644 index 0000000..a9156bc --- /dev/null +++ b/lang/lang.go @@ -0,0 +1,44 @@ +package lang + +import ( + "fmt" + "regexp" + "strings" +) + +// ToSentence splits up camel cased function names +func ToSentence(name string) []string { + re := regexp.MustCompile(`(([^A-Z]+)|([A-Z]{2})|([A-Z][^A-Z]+))`) + return re.FindAllString(name, -1) +} + +func eToIng(verb string) string { + return fmt.Sprintf("%sing", strings.TrimSuffix(verb, "e")) + +} + +func eToEd(verb string) string { + if strings.HasSuffix(verb, "e") { + return fmt.Sprintf("%sd", verb) + } + return fmt.Sprintf("%sed", verb) +} + +func ToPresentParticiple(words []string) string { + if len(words) > 1 { + return fmt.Sprintf("%s %s", eToIng(words[0]), strings.Join(words[1:], " ")) + } + + return eToIng(words[0]) +} + +func VerbToPastTense(verb string) string { + if verb == "build" { + return "built" + } + return eToEd(verb) +} + +func ToPastTensePhrase(words []string) string { + return fmt.Sprintf("%s %s", VerbToPastTense(words[0]), strings.Join(words[1:], " ")) +} diff --git a/logger/logger.go b/logger/logger.go new file mode 100644 index 0000000..0a01adb --- /dev/null +++ b/logger/logger.go @@ -0,0 +1,340 @@ +package logger + +import ( + "fmt" + "os" + "runtime" + "strings" + "time" + + "github.com/kahgeh/devenv/lang" + "github.com/theckman/yacspin" + "go.uber.org/zap" + "go.uber.org/zap/zapcore" +) + +type LogLevel uint8 + +const ( + NormalLogLevel = 1 + DetailedLogLevel = 2 + DebugLogLevel = 3 +) + +const ExitFailureStatus = 3 + +type loggerState struct { + defaultLogger *Spinner + detailedLoggerBase *zap.Logger + detailedLogger *zap.SugaredLogger + names []string + level LogLevel +} + +var state *loggerState + +func newConsoleEncoderConfig(callerKey string) zapcore.EncoderConfig { + return zapcore.EncoderConfig{ + // Keys can be anything except the empty string. + TimeKey: zapcore.OmitKey, + LevelKey: zapcore.OmitKey, + NameKey: "N", + CallerKey: callerKey, + MessageKey: "M", + StacktraceKey: "S", + LineEnding: zapcore.DefaultLineEnding, + EncodeLevel: zapcore.CapitalLevelEncoder, + EncodeTime: zapcore.ISO8601TimeEncoder, + EncodeDuration: zapcore.StringDurationEncoder, + EncodeCaller: zapcore.ShortCallerEncoder, + } +} + +// newConsoleConfig is a reasonable console logging configuration. +// Logging is enabled at DebugLevel and above. +// +// It enables console mode (which makes DPanicLevel logs panic), uses a +// console encoder, writes to standard error, and disables sampling. +// Stacktraces are automatically included on logs of WarnLevel and above. +func newConsoleConfig(level zapcore.Level, callerKey string) zap.Config { + return zap.Config{ + Level: zap.NewAtomicLevelAt(level), + Development: true, + Encoding: "console", + EncoderConfig: newConsoleEncoderConfig(callerKey), + OutputPaths: []string{"stderr"}, + ErrorOutputPaths: []string{"stderr"}, + } +} + +func NewSpinner() *yacspin.Spinner { + cfg := yacspin.Config{ + Frequency: 100 * time.Millisecond, + CharSet: yacspin.CharSets[37], + Suffix: "", + SuffixAutoColon: true, + StopCharacter: "✓", + StopFailCharacter: "✗", + StopColors: []string{"fgGreen"}, + StopFailColors: []string{"fgRed"}, + } + + spinner, _ := yacspin.New(cfg) + return spinner +} + +func GetCallerFunctionName() string { + // Skip GetCallerFunctionName and the function to get the caller of + fullFuncName := getFrame(2).Function + parts := strings.Split(fullFuncName, "/") + parts = strings.Split(parts[len(parts)-1], ".") + return parts[len(parts)-1] +} + +func getFrame(skipFrames int) runtime.Frame { + targetFrameIndex := skipFrames + 2 + programCounters := make([]uintptr, targetFrameIndex+2) + n := runtime.Callers(0, programCounters) + + frame := runtime.Frame{Function: "unknown"} + if n > 0 { + frames := runtime.CallersFrames(programCounters[:n]) + for more, frameIndex := true, 0; more && frameIndex <= targetFrameIndex; frameIndex++ { + var frameCandidate runtime.Frame + frameCandidate, more = frames.Next() + if frameIndex == targetFrameIndex { + frame = frameCandidate + } + } + } + + return frame +} + +func CreateLogger(level LogLevel) { + if level == DetailedLogLevel { + detailedLoggerBase, _ := newConsoleConfig(zapcore.InfoLevel, zapcore.OmitKey).Build() + state = &loggerState{ + detailedLoggerBase: detailedLoggerBase, + detailedLogger: detailedLoggerBase.WithOptions(zap.AddCallerSkip(1)).Sugar(), + defaultLogger: nil, + level: level, + } + return + } + + if level == DebugLogLevel { + detailedLoggerBase, _ := newConsoleConfig(zapcore.DebugLevel, "caller").Build() + state = &loggerState{ + detailedLoggerBase: detailedLoggerBase, + detailedLogger: detailedLoggerBase.WithOptions(zap.AddCallerSkip(1)).Sugar(), + defaultLogger: nil, + level: level, + } + return + } + + if level == NormalLogLevel { + spinner := &Spinner{ + logStream: make(chan string), + newComponent: make(chan *yacspin.Spinner), + } + state = &loggerState{ + level: level, + defaultLogger: spinner, + detailedLoggerBase: nil, + detailedLogger: nil, + } + go spinner.run() + return + } +} + +func Sync() { + if state.level > NormalLogLevel { + state.detailedLoggerBase.Sync() + state.detailedLogger.Sync() + } +} + +type Logger struct { + defaultLogger *Spinner + detailedLogger *zap.SugaredLogger + level LogLevel + LogDone func() +} + +func toLower(words []string) []string { + var lowerCasedWords []string + for _, word := range words { + lowerCasedWords = append(lowerCasedWords, strings.ToLower(word)) + } + return lowerCasedWords +} + +func getName() string { + fullName := strings.Join(state.names, ".") + if len(fullName) > 20 && len(state.names) > 1 { + lastName := state.names[len(state.names)-1] + placeHolders := strings.Repeat(".", len(state.names)-1) + fullName = fmt.Sprintf("%s%s", placeHolders, lastName) + } + padding := "" + columnWidth := 20 + if len(fullName) < columnWidth { + padding = strings.Repeat(" ", columnWidth-len(fullName)) + } + return fmt.Sprintf("[%s]%s", fullName, padding) +} + +func NewTaskLogger() *Logger { + funcName := GetCallerFunctionName() + words := toLower(lang.ToSentence(funcName)) + opName := lang.ToPresentParticiple(words) + state.names = append(state.names, funcName) + if state.level == NormalLogLevel { + spinnerComponent := NewSpinner() + failMessage := fmt.Sprintf("Failed to %s", strings.Join(words, " ")) + successMessage := fmt.Sprintf("Successfully %s", lang.ToPastTensePhrase(words)) + spinnerComponent.Message(opName) + spinnerComponent.StopMessage(successMessage) + spinnerComponent.StopFailMessage(failMessage) + state.defaultLogger.newComponent <- spinnerComponent + return &Logger{ + defaultLogger: state.defaultLogger, + LogDone: func() { + removeFuncName() + }, + } + } + + detailedLogger := state.detailedLogger.Named(getName()) + if state.level == DebugLogLevel { + detailedLogger.Debug(opName) + } + return &Logger{ + level: state.level, + detailedLogger: detailedLogger, + LogDone: func() { + if state.level == DebugLogLevel { + detailedLogger.Debugf("done %s", opName) + } + removeFuncName() + }, + } +} + +func New() *Logger { + funcName := GetCallerFunctionName() + words := lang.ToSentence(funcName) + opName := lang.ToPresentParticiple(words) + state.names = append(state.names, funcName) + if state.level == NormalLogLevel { + return &Logger{ + defaultLogger: state.defaultLogger, + LogDone: func() { + removeFuncName() + }, + } + } + detailedLogger := state.detailedLogger.Named(getName()) + if state.level == DebugLogLevel { + detailedLogger.Debugf("%s", opName) + } + return &Logger{ + level: state.level, + detailedLogger: detailedLogger, + defaultLogger: state.defaultLogger, + LogDone: func() { + if state.level == DebugLogLevel { + detailedLogger.Debugf("done %s", opName) + } + removeFuncName() + }, + } +} + +func removeFuncName() { + if len(state.names) > 0 { + state.names = state.names[:len(state.names)-1] + } +} + +func (logger *Logger) Infof(template string, args ...interface{}) { + if logger.defaultLogger != nil { + logger.defaultLogger.update(fmt.Sprintf(template, args...)) + return + } + logger.detailedLogger.Infof(template, args...) +} + +func (logger *Logger) Info(args ...interface{}) { + if logger.defaultLogger != nil { + logger.defaultLogger.update(fmt.Sprintf("%v", args...)) + return + } + + logger.detailedLogger.Info(args...) +} + +func (logger *Logger) Debugf(template string, args ...interface{}) { + if logger.defaultLogger != nil { + return + } + logger.detailedLogger.Debugf(template, args...) +} + +func (logger *Logger) Debug(args ...interface{}) { + if logger.defaultLogger != nil { + return + } + + logger.detailedLogger.Debug(args...) +} + +func (logger *Logger) DebugFunc(log func(), mustExecute func()) { + + if logger.defaultLogger != nil { + mustExecute() + return + } + + log() +} + +func (logger *Logger) Fail(args ...interface{}) { + if state.defaultLogger != nil { + state.defaultLogger.failed(fmt.Sprintf("%v", args...)) + os.Exit(ExitFailureStatus) + return + } + logger.detailedLogger.Error(args...) + os.Exit(ExitFailureStatus) +} + +func (logger *Logger) Failf(template string, args ...interface{}) { + if state.defaultLogger != nil { + state.defaultLogger.failed(fmt.Sprintf(template, args...)) + os.Exit(ExitFailureStatus) + return + } + logger.detailedLogger.Errorf(template, args) + os.Exit(ExitFailureStatus) +} + +func (logger *Logger) Succeed() { + if logger.defaultLogger != nil { + state.defaultLogger.succeed() + } +} + +func (logger *Logger) Succeedf(template string, args ...interface{}) { + if logger.defaultLogger != nil { + message := fmt.Sprintf(template, args...) + state.defaultLogger.update(message) + state.defaultLogger.succeed() + return + } + + logger.detailedLogger.Infof(template, args...) +} diff --git a/logger/spinner.go b/logger/spinner.go new file mode 100644 index 0000000..dda078e --- /dev/null +++ b/logger/spinner.go @@ -0,0 +1,71 @@ +package logger + +import ( + "time" + + "github.com/kahgeh/devenv/utils/ctx" + "github.com/theckman/yacspin" +) + +type Spinner struct { + logStream chan string + newComponent chan *yacspin.Spinner +} + +const ( + SucceedCompletionStatus = "[succeed]" + FailedCompletionStatus = "[failed]" +) + +type CompletionStatus string + +func slowDownForReading() { + time.Sleep(2 * time.Second) +} +func (spinner *Spinner) run() { + var component *yacspin.Spinner + for { + select { + case newComponent := <-spinner.newComponent: + component = newComponent + component.Start() + case message := <-spinner.logStream: + switch message { + case "[succeed]": + if component != nil { + component.Stop() + } + component = nil + case "[failed]": + if component != nil { + component.StopFail() + } + component = nil + default: + if component == nil { + panic("ensure a started spinner is available") + } + component.Message(message) + slowDownForReading() + } + case <-ctx.GetContext().Done(): + if component != nil { + component.StopFail() + } + return + } + } +} + +func (spinner *Spinner) update(message string) { + spinner.logStream <- message +} + +func (spinner *Spinner) failed(message string) { + spinner.logStream <- message + spinner.logStream <- FailedCompletionStatus +} + +func (spinner *Spinner) succeed() { + spinner.logStream <- SucceedCompletionStatus +} diff --git a/main.go b/main.go new file mode 100644 index 0000000..7d172c3 --- /dev/null +++ b/main.go @@ -0,0 +1,29 @@ +/* +Copyright © 2020 kahgeh + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +package main + +import ( + "github.com/kahgeh/devenv/cmd" + "github.com/kahgeh/devenv/logger" + "github.com/kahgeh/devenv/utils/ctx" +) + +func main() { + defer logger.Sync() + defer ctx.CleanUp() + go ctx.WaitOnCtrlCSignalOrCompletion() + cmd.Execute() +} diff --git a/provider/aws/aws_session.go b/provider/aws/aws_session.go new file mode 100644 index 0000000..8d375df --- /dev/null +++ b/provider/aws/aws_session.go @@ -0,0 +1,55 @@ +package aws + +import ( + "fmt" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/aws/external" +) + +type Template string + +const ( + TemplateParamStoreKeyPath Template = "/allEnvs/%s/pstoreKey" +) + +type Session struct { + config aws.Config +} + +type Config struct { + VpcStackName string + EcsSpotFleetStackName string + EcsClusterStackName string + PublicIPStackName string + EcsClusterName string + EcsSpotFleetPurpose string + KeyPairName string + HostedZoneName string +} + +var awsComputeConfig = Config{ + VpcStackName: "DevTest", + EcsSpotFleetStackName: "GeneralPurposeEcs", + EcsClusterStackName: "DevTestEcsCluster", + PublicIPStackName: "DevTestPublicIp", + EcsClusterName: "DevTest", + EcsSpotFleetPurpose: "gp", +} + +func CreateAwsSession() (*Session, error) { + cfg, err := external.LoadDefaultAWSConfig() + if err != nil { + panic("unable to load SDK config, " + err.Error()) + } + session := &Session{config: cfg} + awsComputeConfig.KeyPairName = session.GetKeyPairName() + return session, nil +} + +func (session *Session) GetKeyPairName() string { + return fmt.Sprintf("ecs-instance-%v", *&session.config.Region) +} + +func (session *Session) GetComputeConfig() Config { + return awsComputeConfig +} diff --git a/provider/aws/changeset.go b/provider/aws/changeset.go new file mode 100644 index 0000000..a1b5adb --- /dev/null +++ b/provider/aws/changeset.go @@ -0,0 +1,138 @@ +package aws + +import ( + "fmt" + "strings" + "time" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/cloudformation" + "github.com/kahgeh/devenv/logger" + "github.com/kahgeh/devenv/utils/ctx" +) + +var ChangeSetCompletionStatuses = []cloudformation.ChangeSetStatus{ + cloudformation.ChangeSetStatusDeleteComplete, + cloudformation.ChangeSetStatusCreateComplete, + cloudformation.ChangeSetStatusFailed, +} + +type ChangeSet struct { + name string + id string + stack Stack + details *cloudformation.DescribeChangeSetResponse +} + +func containStatus(status cloudformation.ChangeSetStatus, statuses []cloudformation.ChangeSetStatus) bool { + for _, statusItem := range statuses { + if statusItem == status { + return true + } + } + return false + +} + +func waitForChangesetCompletion(poll func() (bool, *cloudformation.DescribeChangeSetResponse), result chan *cloudformation.DescribeChangeSetResponse) { + ticker := time.NewTicker(2 * time.Second) + defer func() { ticker.Stop() }() + for { + select { + case <-ctx.GetContext().Done(): + result <- nil + return + case <-ticker.C: + if end, details := poll(); end { + result <- details + return + } + } + } +} + +func (changeset *ChangeSet) WaitTillExecutable() *ChangeSet { + log := logger.New() + defer log.LogDone() + if changeset == nil { + return nil + } + // todo - switch to waiter + resultChannel := make(chan *cloudformation.DescribeChangeSetResponse) + go waitForChangesetCompletion(func() (bool, *cloudformation.DescribeChangeSetResponse) { + description := changeset.Describe() + return containStatus(description.Status, ChangeSetCompletionStatuses), description + }, resultChannel) + result := <-resultChannel + if result == nil { + return nil + } + + if result.Status == cloudformation.ChangeSetStatusFailed { + log.Failf("Fail to create changeset %s", changeset.name) + return nil + } + + return &ChangeSet{ + stack: changeset.stack, + id: changeset.id, + details: result, + } +} + +func (changeset *ChangeSet) Describe() *cloudformation.DescribeChangeSetResponse { + stackName := changeset.stack.name + api := changeset.stack.api + request := api.DescribeChangeSetRequest(&cloudformation.DescribeChangeSetInput{ + StackName: &stackName, + ChangeSetName: aws.String(changeset.name), + }) + response, err := request.Send(ctx.GetContext()) + if err != nil { + return nil + } + return response +} + +func (changeset *ChangeSet) String() string { + if changeset == nil { + return "" + } + stackName := changeset.stack.name + return fmt.Sprintf("change set id=%v name=%v of stack %v", changeset.id, changeset.name, stackName) +} + +func getChangesSummary(changes []cloudformation.Change) string { + var sb strings.Builder + for _, change := range changes { + sb.WriteString(fmt.Sprintf("%s %s\n", string(change.ResourceChange.Action), + *change.ResourceChange.LogicalResourceId)) + } + return sb.String() +} + +func (changeset *ChangeSet) SendExecuteRequest() *string { + log := logger.New() + defer log.LogDone() + if changeset == nil { + return nil + } + stackName := changeset.stack.name + api := changeset.stack.api + token := fmt.Sprintf("%s-%v", stackName, time.Now().UnixNano()) + changeSummary := getChangesSummary(changeset.details.Changes) + log.Debugf("Changes :\n%s", changeSummary) + + request := api.ExecuteChangeSetRequest(&cloudformation.ExecuteChangeSetInput{ + ChangeSetName: &changeset.id, + ClientRequestToken: &token, + }) + + _, err := request.Send(ctx.GetContext()) + if err != nil { + log.Infof("error executeChange- %s", err) + return nil + } + + return &token +} diff --git a/provider/aws/deploy.go b/provider/aws/deploy.go new file mode 100644 index 0000000..b40cf58 --- /dev/null +++ b/provider/aws/deploy.go @@ -0,0 +1,358 @@ +package aws + +import ( + "encoding/base64" + "encoding/json" + "fmt" + ecs2 "github.com/aws/aws-sdk-go-v2/service/ecs" + cmdTypes "github.com/kahgeh/devenv/cmd/types" + provideTypes "github.com/kahgeh/devenv/provider/types" + "github.com/kahgeh/devenv/utils" + "io/ioutil" + "os" + "strings" + "time" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/cloudformation" + "github.com/aws/aws-sdk-go-v2/service/ecr" + "github.com/docker/docker/api/types" + whale "github.com/docker/docker/client" + "github.com/docker/docker/pkg/archive" + "github.com/docker/docker/pkg/jsonmessage" + "github.com/docker/docker/pkg/term" + "github.com/kahgeh/devenv/logger" + "github.com/kahgeh/devenv/utils/ctx" +) + +func generateID() string { + s := fmt.Sprintf("%v", time.Now().UnixNano()) + return s +} + +func getAuthToken(authResponse *ecr.GetAuthorizationTokenResponse) string { + authInfoBytes, _ := base64.StdEncoding.DecodeString(*authResponse.AuthorizationData[0].AuthorizationToken) + authInfo := strings.Split(string(authInfoBytes), ":") + auth := struct { + Username string + Password string + }{ + Username: authInfo[0], + Password: authInfo[1], + } + + authBytes, _ := json.Marshal(auth) + return base64.StdEncoding.EncodeToString(authBytes) +} + +func buildImage(context string, appName string, id string, buildArgs map[string]*string) *string { + log := logger.NewTaskLogger() + defer log.LogDone() + client, err := whale.NewClientWithOpts() + if err != nil { + log.Fail("cannot access docker") + return nil + } + + buildCtx, _ := archive.TarWithOptions(context, &archive.TarOptions{}) + tag := fmt.Sprintf("%s:%s", appName, id) + response, err := client.ImageBuild(ctx.GetContext(), + buildCtx, + types.ImageBuildOptions{ + Tags: []string{tag}, + BuildArgs: buildArgs, + NoCache: true, + }) + + if err != nil { + log.Debug(err.Error()) + log.Fail("build failed") + return nil + } + + defer utils.CloseReadCloser(response.Body, func(s string) { log.Debug(s) }) + log.DebugFunc(func() { + termFd, isTerm := term.GetFdInfo(os.Stderr) + err := jsonmessage.DisplayJSONMessagesStream(response.Body, os.Stderr, termFd, isTerm, nil) + if err != nil { + log.Debug(err.Error()) + } + }, func() { + _, err := ioutil.ReadAll(response.Body) + if err != nil { + log.Fail(err.Error()) + } + }) + log.Succeed() + return &tag +} + +func getEcrStackName(appName string) string { + return fmt.Sprintf("ecr-%s", appName) +} + +func (session *Session) createRepository(appName string) *string { + log := logger.NewTaskLogger() + defer log.LogDone() + stackName := getEcrStackName(appName) + cfnClient := cloudformation.New(session.config) + stack := &Stack{name: stackName, api: cfnClient} + stackDescription, err := stack.Describe() + if stackDescription != nil { + log.Succeed() + return stackDescription.Outputs[0].OutputValue + } + + err = stack.Create("ecr.yml", []cloudformation.Parameter{ + { + ParameterKey: aws.String("RepositoryName"), + ParameterValue: aws.String(appName), + }, + }) + if err != nil { + log.Fail("fail to create repository") + } + + repository := session.getStackOutputValue(stackName, stackName) + log.Succeed() + return repository +} + +func (session *Session) uploadImage(source *string, repo *string, tag string) { + log := logger.NewTaskLogger() + defer log.LogDone() + client, err := whale.NewClientWithOpts() + if err != nil { + log.Fail("cannot access docker") + return + } + target := fmt.Sprintf("%s:%s", *repo, tag) + log.Info("tagging image with repo prefix...") + err = client.ImageTag(ctx.GetContext(), *source, target) + if err != nil { + log.Debug(err.Error()) + log.Fail("Fail to tag image") + return + } + err = client.ImageTag(ctx.GetContext(), *source, *repo) + if err != nil { + log.Debug(err.Error()) + log.Fail("Fail to tag image with latest") + return + } + + log.Info("pushing image to repository...") + svc := ecr.New(session.config) + request := svc.GetAuthorizationTokenRequest(&ecr.GetAuthorizationTokenInput{}) + authResponse, err := request.Send(ctx.GetContext()) + authToken := getAuthToken(authResponse) + response, err := client.ImagePush( + ctx.GetContext(), + target, + types.ImagePushOptions{ + RegistryAuth: authToken, + }) + + response, err = client.ImagePush( + ctx.GetContext(), + *repo, + types.ImagePushOptions{ + RegistryAuth: authToken, + }) + + if err != nil { + log.Debug(err.Error()) + log.Fail("fail to push to registry") + return + } + + if response == nil { + log.Fail("fail to push to registry, no response") + return + } + + defer utils.CloseReadCloser(response, func(s string) { log.Debug(s) }) + log.DebugFunc(func() { + termFd, isTerm := term.GetFdInfo(os.Stderr) + err := jsonmessage.DisplayJSONMessagesStream(response, os.Stderr, termFd, isTerm, nil) + if err != nil { + log.Debug(err.Error()) + log.Fail("fail to push image to repository") + } + }, func() { + _, err := ioutil.ReadAll(response) + if err != nil { + log.Debug(err.Error()) + log.Fail("fail to push image to repository") + } + }) + log.Succeed() +} + +func (session *Session) deployFrontProxy(image string, envName string) { + log := logger.NewTaskLogger() + defer log.LogDone() + config := session.GetComputeConfig() + ecsClusterExportName := config.EcsClusterStackName + appName := string(cmdTypes.KnownAppFrontProxy) + paramStoreKeyPath := fmt.Sprintf(string(TemplateParamStoreKeyPath), envName) + log.Infof("image=%s envName%s", image, envName) + + stackName := fmt.Sprintf("app-%s", appName) + parameters := []cloudformation.Parameter{ + { + ParameterKey: aws.String("AppName"), + ParameterValue: aws.String(appName), + }, + { + ParameterKey: aws.String("Image"), + ParameterValue: aws.String(image), + }, + { + ParameterKey: aws.String("EcsClusterExportName"), + ParameterValue: aws.String(ecsClusterExportName), + }, + { + ParameterKey: aws.String("EnvironmentName"), + ParameterValue: aws.String(envName), + }, + { + ParameterKey: aws.String("ParamStoreKeyArn"), + ParameterValue: aws.String(paramStoreKeyPath), + }, + } + templateFileName := "front-proxy/app.yml" + cfnClient := cloudformation.New(session.config) + stack := &Stack{name: stackName, api: cfnClient} + stackDescription, err := stack.Describe() + if stackDescription != nil { + ssmSession := session.NewSsmSession() + log.Info("getting app details...") + cluster, err := ssmSession.GetParamterValue(fmt.Sprintf("/allEnvs/%s/infra/ecs/name", envName)) + if err != nil { + log.Debug(err.Error()) + log.Fail("fail to get cluster name details") + return + } + + serviceArn, err := ssmSession.GetParamterValue(fmt.Sprintf("/allEnvs/%s/apps/%s/serviceArn", envName, appName)) + if err != nil { + log.Debug(err.Error()) + log.Fail("fail to get service details") + return + } + + log.Info("removing app...") + api := ecs2.New(session.config) + req := api.UpdateServiceRequest(&ecs2.UpdateServiceInput{ + Cluster: cluster, + Service: serviceArn, + DesiredCount: aws.Int64(0), + }) + _, err = req.Send(ctx.GetContext()) + if err != nil { + log.Debug(err.Error()) + log.Fail("fail to remove app first") + return + } + log.Info("waiting app to be removed...") + err = api.WaitUntilServicesStable(ctx.GetContext(), &ecs2.DescribeServicesInput{ + Cluster: cluster, + Services: []string{*serviceArn}, + }) + if err != nil { + log.Debug(err.Error()) + log.Fail("waiting for app to be removed failed") + return + } + log.Info("updating app...") + err = stack.Update(templateFileName, parameters) + } else { + log.Info("creating app...") + err = stack.Create(templateFileName, parameters) + } + if err != nil { + log.Debug(err.Error()) + log.Failf("fail to deploy %s", appName) + } + + log.Succeed() +} + +func (session *Session) deployApp(appName string, image string, envName string) { + log := logger.NewTaskLogger() + defer log.LogDone() + config := session.GetComputeConfig() + ecsClusterExportName := config.EcsClusterStackName + + log.Info("getting app details...") + + stackName := fmt.Sprintf("app-%s", appName) + parameters := []cloudformation.Parameter{ + { + ParameterKey: aws.String("AppName"), + ParameterValue: aws.String(appName), + }, + { + ParameterKey: aws.String("Image"), + ParameterValue: aws.String(image), + }, + { + ParameterKey: aws.String("EcsClusterExportName"), + ParameterValue: aws.String(ecsClusterExportName), + }, + { + ParameterKey: aws.String("EnvironmentName"), + ParameterValue: aws.String(envName), + }, + } + templateFileName := "app.yml" + cfnClient := cloudformation.New(session.config) + stack := &Stack{name: stackName, api: cfnClient} + stackDescription, err := stack.Describe() + if stackDescription != nil { + log.Info("updating app...") + err = stack.Update(templateFileName, parameters) + } else { + log.Info("creating app...") + err = stack.Create(templateFileName, parameters) + } + if err != nil { + log.Debug(err.Error()) + log.Failf("fail to deploy %s", appName) + } + + log.Succeed() +} + +// Deploy builds, publish image and deploy service +func (session *Session) Deploy(parameters *provideTypes.DeployParameters) { + appType := parameters.AppType + appName := parameters.AppName + path := parameters.Path + domainName := parameters.DomainName + domainEmail := parameters.DomainEmail + envName := parameters.EnvironmentName + + id := generateID() + if appType == provideTypes.FrontProxy { + appName = string(cmdTypes.KnownAppFrontProxy) + frontProxyPath := getFrontProxyPath() + tag := buildImage(frontProxyPath, appName, id, map[string]*string{ + "DOMAIN_NAME": &domainName, + "DOMAIN_EMAIL": &domainEmail, + "ENV_NAME": &envName, + }) + repository := session.createRepository(appName) + session.uploadImage(tag, repository, id) + imageId := fmt.Sprintf("%s:%s", *repository, id) + session.deployFrontProxy(imageId, envName) + return + } + + tag := buildImage(path, appName, id, map[string]*string{}) + repository := session.createRepository(appName) + session.uploadImage(tag, repository, id) + imageId := fmt.Sprintf("%s:%s", *repository, id) + session.deployApp(appName, imageId, envName) +} diff --git a/provider/aws/ecs.go b/provider/aws/ecs.go new file mode 100644 index 0000000..44488c2 --- /dev/null +++ b/provider/aws/ecs.go @@ -0,0 +1,24 @@ +package aws + +import ( + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/ecs" + "github.com/kahgeh/devenv/utils/ctx" +) + +func (session *Session) DescribeService(serviceArn string, clusterName string) (*ecs.DescribeServicesResponse, error) { + svc := ecs.New(session.config) + input := &ecs.DescribeServicesInput{ + Services: []string{ + serviceArn, + }, + Cluster: aws.String(clusterName), + } + + req := svc.DescribeServicesRequest(input) + result, err := req.Send(ctx.GetContext()) + if err != nil { + return nil, err + } + return result, nil +} diff --git a/provider/aws/errors/noResponse.go b/provider/aws/errors/noResponse.go new file mode 100644 index 0000000..a801ca3 --- /dev/null +++ b/provider/aws/errors/noResponse.go @@ -0,0 +1,9 @@ +package errors + +type NoResponse struct { + Message string +} + +func (e *NoResponse) Error() string { + return e.Message +} diff --git a/provider/aws/init.go b/provider/aws/init.go new file mode 100644 index 0000000..fd8cc52 --- /dev/null +++ b/provider/aws/init.go @@ -0,0 +1,229 @@ +package aws + +import ( + "fmt" + "github.com/aws/aws-sdk-go-v2/service/kms" + "github.com/aws/aws-sdk-go-v2/service/ssm" + "github.com/kahgeh/devenv/provider/types" + "io/ioutil" + "os" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/aws/awserr" + "github.com/aws/aws-sdk-go-v2/service/cloudformation" + "github.com/aws/aws-sdk-go-v2/service/ec2" + "github.com/kahgeh/devenv/fixed" + "github.com/kahgeh/devenv/logger" + "github.com/kahgeh/devenv/utils" + "github.com/kahgeh/devenv/utils/ctx" + "github.com/mitchellh/go-homedir" +) + +func getSshFolderPath() string { + home, err := homedir.Dir() + if err != nil { + fmt.Println(err) + os.Exit(1) + } + return fmt.Sprintf("%v/.ssh", home) +} + +func getFrontProxyPath() string { + configFolderPath := fixed.GetConfigFolderPath() + return fmt.Sprintf("%s/aws/%s", configFolderPath, "front-proxy") +} + +func getCfnTemplateContent(cfnFileName string) (string, error) { + configFolderPath := fixed.GetConfigFolderPath() + cfnTemplatePath := fmt.Sprintf("%s/aws/%s", configFolderPath, cfnFileName) + content, err := ioutil.ReadFile(cfnTemplatePath) + if err != nil { + return "", err + } + limit := 51200 + if len(content) > limit { + return "", fmt.Errorf("template %s is over the %v limit", cfnTemplatePath, limit) + } + return string(content), nil +} + +func (session *Session) createKeyPair() { + log := logger.NewTaskLogger() + defer log.LogDone() + + keyPairName := session.GetKeyPairName() + request := ec2.New(session.config).CreateKeyPairRequest(&ec2.CreateKeyPairInput{ + KeyName: aws.String(keyPairName), + }) + result, err := request.Send(ctx.GetContext()) + + sshFolderPath := getSshFolderPath() + sshPrivateKeyFilePath := fmt.Sprintf("%s/%s.pem", sshFolderPath, keyPairName) + if aerr, ok := err.(awserr.Error); ok { + if aerr.Code() == "InvalidKeyPair.Duplicate" { + if _, err := os.Stat(sshPrivateKeyFilePath); os.IsNotExist(err) { + log.Failf("Key pair %q already exists, but '.pem' does not exist", keyPairName, sshPrivateKeyFilePath) + return + } + log.Succeedf("Key pair %q already exists", keyPairName) + return + } + log.Debug(aerr.Message()) + log.Fail(aerr.Code()) + return + } + if result == nil { + log.Fail("no response from creating key pair request") + return + } + keyPair := result + log.Debugf("Created key pair %q %s\n%s\n", + *keyPair.KeyName, *keyPair.KeyFingerprint, + *keyPair.KeyMaterial) + + log.Info("saving private key to ssh folder...") + err = utils.CreateFolderIfNotExist(sshFolderPath) + if err != nil { + log.Failf("fail to ensure %q exist", sshFolderPath) + return + } + + err = ioutil.WriteFile(sshPrivateKeyFilePath, []byte(*keyPair.KeyMaterial), 0600) + if err != nil { + log.Failf("Failed saving private key to %s", sshPrivateKeyFilePath) + return + } + log.Succeedf("Saved private key to %s", sshPrivateKeyFilePath) +} + +func (session *Session) createVpc() { + log := logger.NewTaskLogger() + defer log.LogDone() + + config := session.GetComputeConfig() + stackName := config.VpcStackName + + cfnClient := cloudformation.New(session.config) + stack := &Stack{name: stackName, api: cfnClient} + err := stack.Create("vpc.yml", []cloudformation.Parameter{}) + if err != nil { + log.Fail("fail to create vpc") + } + log.Succeed() +} + +func (session *Session) createEcsSpotFleet(envName string, domainName string) { + log := logger.NewTaskLogger() + defer log.LogDone() + + config := session.GetComputeConfig() + stackName := config.EcsSpotFleetStackName + clusterName := config.EcsClusterName + keyPairName := config.KeyPairName + purpose := config.EcsSpotFleetPurpose + + cfnClient := cloudformation.New(session.config) + stack := &Stack{name: stackName, api: cfnClient} + err := stack.Create("spotFleet.yml", []cloudformation.Parameter{ + { + ParameterKey: aws.String("EcsClusterName"), + ParameterValue: aws.String(clusterName), + }, + { + ParameterKey: aws.String("KeyName"), + ParameterValue: aws.String(keyPairName), + }, + { + ParameterKey: aws.String("Environment"), + ParameterValue: aws.String(envName), + }, + { + ParameterKey: aws.String("FleetType"), + ParameterValue: aws.String(purpose), + }, + { + ParameterKey: aws.String("DomainName"), + ParameterValue: aws.String(domainName), + }, + }) + if err != nil { + log.Fail("fail to create spot fleet") + } + log.Succeed() +} + +func (session *Session) createEcsCluster(envName string) { + log := logger.NewTaskLogger() + defer log.LogDone() + + config := session.GetComputeConfig() + stackName := config.EcsClusterStackName + clusterName := config.EcsClusterName + + cfnClient := cloudformation.New(session.config) + stack := &Stack{name: stackName, api: cfnClient} + err := stack.Create("ecsCluster.yml", []cloudformation.Parameter{ + { + ParameterKey: aws.String("ClusterName"), + ParameterValue: aws.String(clusterName), + }, + { + ParameterKey: aws.String("Environment"), + ParameterValue: aws.String(envName), + }, + }) + if err != nil { + log.Fail("fail to create ecs cluster") + } + log.Succeed() +} + +func (session *Session) savePstoreKey(keyName string, path string) { + log := logger.NewTaskLogger() + defer log.LogDone() + + apiKms := kms.New(session.config) + describeKeyRequest := apiKms.DescribeKeyRequest(&kms.DescribeKeyInput{ + KeyId: aws.String(keyName), + }) + + keyDescription, err := describeKeyRequest.Send(ctx.GetContext()) + if err != nil { + log.Debug(err.Error()) + log.Failf("fail to get %q key arn", keyName) + return + } + + keyArn := keyDescription.DescribeKeyOutput.KeyMetadata.Arn + + apiSsm := ssm.New(session.config) + putParamRequest := apiSsm.PutParameterRequest(&ssm.PutParameterInput{ + Value: keyArn, + Name: aws.String(path), + Type: ssm.ParameterTypeString, + Overwrite: aws.Bool(true), + }) + + putParamResponse, err := putParamRequest.Send(ctx.GetContext()) + if err != nil { + log.Debug(err.Error()) + log.Fail("fail to save aws/ssm key arn to parameter store") + return + } + + log.Debug(putParamResponse.PutParameterOutput.String()) + log.Succeed() +} + +func (session *Session) Initialise(parameters *types.InitialisationParameters) { + log := logger.New() + defer log.LogDone() + envName := parameters.EnvironmentName + domainName := parameters.DomainName + session.createKeyPair() + session.createVpc() + session.createEcsCluster(envName) + session.createEcsSpotFleet(envName, domainName) + pstoreKeyPath := fmt.Sprintf(string(TemplateParamStoreKeyPath), envName) + session.savePstoreKey("alias/aws/ssm", pstoreKeyPath) +} diff --git a/provider/aws/ssm.go b/provider/aws/ssm.go new file mode 100644 index 0000000..039340c --- /dev/null +++ b/provider/aws/ssm.go @@ -0,0 +1,44 @@ +package aws + +import ( + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/aws/external" + "github.com/aws/aws-sdk-go-v2/service/ssm" + "github.com/kahgeh/devenv/utils/ctx" +) + +type SsmSession struct { + api *ssm.Client +} + +func NewSession() (*Session, error) { + cfg, err := external.LoadDefaultAWSConfig() + if err != nil { + panic("unable to load SDK config, " + err.Error()) + } + session := &Session{config: cfg} + return session, nil +} + +func (session *Session) NewSsmSession() *SsmSession { + api := ssm.New(session.config) + return &SsmSession{ + api: api, + } +} + +func (session *SsmSession) GetParamterValue(name string) (value *string, err error) { + api := session.api + + request := api.GetParameterRequest(&ssm.GetParameterInput{ + Name: aws.String(name), + WithDecryption: aws.Bool(true), + }) + response, err := request.Send(ctx.GetContext()) + if err != nil { + value = nil + return + } + value = response.GetParameterOutput.Parameter.Value + return +} diff --git a/provider/aws/stack.go b/provider/aws/stack.go new file mode 100644 index 0000000..9e96e5b --- /dev/null +++ b/provider/aws/stack.go @@ -0,0 +1,257 @@ +package aws + +import ( + "fmt" + "github.com/kahgeh/devenv/provider/aws/errors" + "strings" + "time" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/aws/awserr" + "github.com/aws/aws-sdk-go-v2/service/cloudformation" + "github.com/kahgeh/devenv/logger" + "github.com/kahgeh/devenv/utils/ctx" +) + +type StackUpdateCompletion string + +type Stack struct { + api *cloudformation.Client + name string + details *cloudformation.Stack +} + +func NewStack(name string, awsSession *Session) *Stack { + return &Stack{ + api: cloudformation.New(awsSession.config), + name: name, + } +} + +// CreateChangeSet create a changeset +func (stack *Stack) CreateChangeSet(name string, changesetType cloudformation.ChangeSetType, templateBody string, parameters []cloudformation.Parameter) *ChangeSet { + log := logger.New() + if stack == nil { + return nil + } + stackName := stack.name + token := fmt.Sprintf("%s-%v", stackName, time.Now().UnixNano()) + + request := stack.api.CreateChangeSetRequest(&cloudformation.CreateChangeSetInput{ + StackName: aws.String(stackName), + Capabilities: []cloudformation.Capability{"CAPABILITY_IAM", "CAPABILITY_NAMED_IAM", "CAPABILITY_AUTO_EXPAND"}, + TemplateBody: &templateBody, + ChangeSetType: changesetType, + ChangeSetName: aws.String(name), + ClientToken: aws.String(token), + Parameters: parameters, + }) + + response, err := request.Send(ctx.GetContext()) + if err != nil { + log.Debug(err.Error()) + log.Fail("error creating change set request") + return nil + } + description, err := stack.Describe() + if err != nil { + log.Fail("unable to get description of stack '%s'", stackName) + return nil + } + log.Infof("created changeset, name=%q", name) + + return &ChangeSet{ + id: *response.Id, + name: name, + stack: Stack{ + api: stack.api, + name: stackName, + details: description, + }, + } +} + +// Delete remove stack, waits for completion +func (stack *Stack) Delete() *string { + log := logger.New() + if stack == nil { + return nil + } + stackName := stack.name + token := fmt.Sprintf("%s-%v", stackName, time.Now().UnixNano()) + api := stack.api + request := api.DeleteStackRequest(&cloudformation.DeleteStackInput{ + StackName: aws.String(stackName), + ClientRequestToken: aws.String(token), + }) + _, err := request.Send(ctx.GetContext()) + if err != nil { + log.Info(err) + if awsErr, ok := err.(awserr.Error); ok { + log.Info(awsErr.Code()) + log.Debug(awsErr.Error()) + log.Debug(awsErr.Message()) + } + + return &token + } + err = api.WaitUntilStackDeleteComplete(ctx.GetContext(), + &cloudformation.DescribeStacksInput{ + StackName: aws.String(stackName), + }) + if err != nil { + log.Debug(err.Error()) + log.Fail("fail to wait for stack deletion to complete") + return nil + } + return &token +} + +func (stack *Stack) Describe() (description *cloudformation.Stack, err error) { + request := stack.api.DescribeStacksRequest(&cloudformation.DescribeStacksInput{ + StackName: aws.String(stack.name), + }) + response, err := request.Send(ctx.GetContext()) + if err != nil { + if awsErr, ok := err.(awserr.Error); ok { + if awsErr.Code() == "ValidationError" && + strings.Contains(awsErr.Message(), "does not exist") { + return nil, nil + } + } else { + return nil, err + } + } + if response == nil { + return nil, &errors.NoResponse{Message: "empty response from describe stack"} + } + + return &response.Stacks[0], nil +} + +// GetEvents retrieves the events for a specific operation +func (stack *Stack) GetEvents(opToken string) (events []cloudformation.StackEvent, err error) { + request := stack.api.DescribeStackEventsRequest(&cloudformation.DescribeStackEventsInput{ + StackName: aws.String(stack.name), + }) + response, err := request.Send(ctx.GetContext()) + if err != nil { + if awsErr, ok := err.(awserr.Error); ok { + if awsErr.Code() == "ValidationError" && + strings.Contains(awsErr.Message(), "does not exist") { + return nil, nil + } + } + return nil, err + } + for _, event := range response.StackEvents { + if event.ClientRequestToken != nil && + *event.ClientRequestToken == opToken { + events = append(events, event) + } + } + + return events, nil +} + +func getNameFromStackFileName(actionName string,stackFileName string) string{ + return fmt.Sprintf("%s-%s", actionName, strings.Replace( + strings.TrimRight(stackFileName, ".yml"), + "/", "-", -1)) +} + +// Create creates stack, reports success if successfully create as well as if it already exist +// This function waits for completion +func (stack *Stack) Create(stackFileName string, parameters []cloudformation.Parameter) error { + log := logger.New() + defer log.LogDone() + stackName := stack.name + changeSetName := getNameFromStackFileName("create", stackFileName) + templateBody, err := getCfnTemplateContent(stackFileName) + if err != nil { + log.Failf("cannot retrieve %s", stackFileName) + } + log.Debugf("template body \n%s", templateBody) + + cfnStack, err := stack.Describe() + if err != nil { + log.Debugf("unexpected error occured while checking if stack '%s' exist ", stackName) + return err + } + + if cfnStack != nil { + log.Debugf("Stack %v already exists", stackName) + return nil + } + + opToken := stack. + CreateChangeSet(changeSetName, cloudformation.ChangeSetTypeCreate, templateBody, parameters). + WaitTillExecutable(). + SendExecuteRequest() + api := stack.api + err = api.WaitUntilStackCreateComplete(ctx.GetContext(), &cloudformation.DescribeStacksInput{ + StackName: &stack.name, + }) + if err != nil { + return err + } + + events, err := stack.GetEvents(*opToken) + var eventsSummary strings.Builder + for _, event := range events { + eventsSummary.WriteString(fmt.Sprintf("%s [%s] %s\n", + event.Timestamp.Format(time.Kitchen), + event.ResourceStatus, *event.LogicalResourceId)) + } + log.Debugf("events :\n%s", eventsSummary.String()) + return nil +} + +// Update creates stack, reports success if successfully create as well as if it already exist +// This function waits for completion +func (stack *Stack) Update(stackFileName string, parameters []cloudformation.Parameter) error { + log := logger.New() + defer log.LogDone() + stackName := stack.name + changeSetName := getNameFromStackFileName("update", stackFileName) + + templateBody, err := getCfnTemplateContent(stackFileName) + if err != nil { + log.Failf("cannot retrieve %s", stackFileName) + } + log.Debugf("template body \n%s", templateBody) + + _, err = stack.Describe() + if err != nil { + log.Debugf("unexpected error occurred while checking if stack '%s' exist ", stackName) + return err + } + + opToken := stack. + CreateChangeSet( + changeSetName, + cloudformation.ChangeSetTypeUpdate, + templateBody, + parameters). + WaitTillExecutable(). + SendExecuteRequest() + api := stack.api + err = api.WaitUntilStackUpdateComplete(ctx.GetContext(), + &cloudformation.DescribeStacksInput{ + StackName: &stack.name, + }) + + if err == nil { + return err + } + + events, err := stack.GetEvents(*opToken) + var eventsSummary strings.Builder + for _, event := range events { + eventsSummary.WriteString(fmt.Sprintf("%s [%s] %s\n", + event.Timestamp.Format(time.Kitchen), + event.ResourceStatus, *event.LogicalResourceId)) + } + log.Debugf("events :\n%s", eventsSummary.String()) + return nil +} diff --git a/provider/aws/start.go b/provider/aws/start.go new file mode 100644 index 0000000..fa4010b --- /dev/null +++ b/provider/aws/start.go @@ -0,0 +1,256 @@ +package aws + +import ( + "fmt" + "github.com/kahgeh/devenv/provider/types" + "time" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/cloudformation" + "github.com/aws/aws-sdk-go-v2/service/ec2" + "github.com/kahgeh/devenv/logger" + "github.com/kahgeh/devenv/utils/ctx" +) + +type waitResult struct { + output *string + err error +} + +func filterOutputs(outputs []cloudformation.Output, predicate func(cloudformation.Output) bool) []cloudformation.Output { + b := outputs[:0] + + for _, output := range outputs { + if predicate(output) { + b = append(b, output) + } + } + return b +} + +func (session *Session) createPublicIP(hostedZoneName string, domainName string) *string { + log := logger.NewTaskLogger() + defer log.LogDone() + cfg := session.GetComputeConfig() + stackName := cfg.PublicIPStackName + log.Debugf("hostedZoneName=%q", hostedZoneName) + cfnClient := cloudformation.New(session.config) + stack := &Stack{name: stackName, api: cfnClient} + err := stack.Create("publicIp.yml", []cloudformation.Parameter{ + { + ParameterKey: aws.String("HostedZoneName"), + ParameterValue: aws.String(hostedZoneName), + }, + { + ParameterKey: aws.String("DomainName"), + ParameterValue: aws.String(domainName), + }, + }) + if err != nil { + log.Debug(err.Error()) + log.Fail("fail to create public Ip") + } + publicIP := session.getStackOutputValue("PublicIp", stackName) + log.Infof("public ip %q is available and assigned to app.%s", *publicIP, domainName) + log.Succeed() + return publicIP +} + +func (session *Session) getStackOutputValue(name string, stackName string) *string { + cfnClient := cloudformation.New(session.config) + stack := &Stack{name: stackName, api: cfnClient} + description, _ := stack.Describe() + result := filterOutputs(description.Outputs, func(output cloudformation.Output) bool { + return *output.ExportName == name + }) + return result[0].OutputValue +} + +func (session *Session) getStackOutputValueByKey(name string, stackName string) *string { + cfnClient := cloudformation.New(session.config) + stack := &Stack{name: stackName, api: cfnClient} + description, _ := stack.Describe() + result := filterOutputs(description.Outputs, func(output cloudformation.Output) bool { + return *output.OutputKey == name + }) + return result[0].OutputValue +} + +func wait(resultChannel chan *waitResult, predicate func() (*string, error)) { + ticker := time.NewTicker(5 * time.Second) + allowedRetries := 3 + defer func() { + ticker.Stop() + close(resultChannel) + }() + for { + select { + case <-ctx.GetContext().Done(): + return + case <-ticker.C: + result, err := predicate() + if allowedRetries > 0 && err != nil { + allowedRetries-- + } + if allowedRetries == 0 && err != nil { + resultChannel <- &waitResult{ + err: err, + output: nil, + } + } + if result != nil { + resultChannel <- &waitResult{ + err: err, + output: result, + } + return + } + } + } +} + +func (session *Session) addEcsInstance() *string { + log := logger.NewTaskLogger() + defer log.LogDone() + + cfg := session.GetComputeConfig() + stackName := cfg.EcsSpotFleetStackName + + log.Info("get spot fleet details...") + spotFleetRequestID := session.getStackOutputValue( + fmt.Sprintf("%s-spotfleetrequest", stackName), + stackName) + + api := ec2.New(session.config) + describeRequest := api.DescribeSpotFleetInstancesRequest(&ec2.DescribeSpotFleetInstancesInput{ + SpotFleetRequestId: spotFleetRequestID, + }) + + descriptionResponse, err := describeRequest.Send(ctx.GetContext()) + if err != nil { + log.Fail("fail to get spot fleet instance") + return nil + } + + if len(descriptionResponse.ActiveInstances) > 0 { + log.Info("there's already one instance") + log.Succeed() + return descriptionResponse.ActiveInstances[0].InstanceId + } + + log.Info("starting ecs instance...") + modificationRequest := api.ModifySpotFleetRequestRequest(&ec2.ModifySpotFleetRequestInput{ + SpotFleetRequestId: spotFleetRequestID, + TargetCapacity: aws.Int64(1), + }) + + modificationResponse, err := modificationRequest.Send(ctx.GetContext()) + if err != nil { + log.Fail("fail to allocate new ECS instance") + return nil + } + + if !*modificationResponse.Return { + log.Debug(modificationResponse.String()) + log.Failf("fail to allocate new ECS instance") + return nil + } + + log.Info("waiting for ecs instance to be running...") + c := make(chan *waitResult) + go wait(c, func() (*string, error) { + request := api.DescribeSpotFleetInstancesRequest(&ec2.DescribeSpotFleetInstancesInput{ + SpotFleetRequestId: spotFleetRequestID, + }) + + response, err := request.Send(ctx.GetContext()) + if err != nil { + return nil, err + } + + if len(response.ActiveInstances) > 0 { + return response.ActiveInstances[0].InstanceId, nil + } + return nil, nil + }) + result := <-c + if result != nil && result.err != nil { + log.Debug(result.err.Error()) + log.Fail("fail to get spot fleet information") + return nil + } + if result == nil { + log.Fail("get spot fleet returns empty information") + return nil + } + instanceId := *result.output + err = api.WaitUntilSystemStatusOk(ctx.GetContext(), &ec2.DescribeInstanceStatusInput{ + InstanceIds: []string{instanceId}, + }) + + if err != nil { + log.Failf("waiting for %s to reach OK status failed", instanceId) + return nil + } + + log.Succeedf("instanceId %q started", instanceId) + return result.output +} + +func (session *Session) attachPublicIPToEcsInstance(publicIP *string, instanceID *string) { + log := logger.NewTaskLogger() + defer log.LogDone() + api := ec2.New(session.config) + + request := api.AssociateAddressRequest(&ec2.AssociateAddressInput{ + InstanceId: instanceID, + PublicIp: publicIP, + }) + response, err := request.Send(ctx.GetContext()) + if err != nil { + log.Failf("fail to attach %q to %q", publicIP, instanceID) + return + } + log.Debugf("associationId id=%q", *response.AssociationId) + log.Succeed() +} + +func (session *Session) waitTillInstanceRunning(instanceID string) { + log := logger.NewTaskLogger() + defer log.LogDone() + api := ec2.New(session.config) + + c := make(chan *waitResult) + go wait(c, func() (*string, error) { + request := api.DescribeInstanceStatusRequest(&ec2.DescribeInstanceStatusInput{ + InstanceIds: []string{instanceID}, + }) + response, err := request.Send(ctx.GetContext()) + if err != nil { + return nil, err + } + + if response.InstanceStatuses[0].InstanceState.Name == ec2.InstanceStateNameRunning { + return aws.String(string(ec2.InstanceStateNameRunning)), nil + } + + return nil, nil + }) + result := <-c + if result.err != nil { + log.Debug(result.err.Error()) + log.Fail("unexpected error while waiting for instance to be running") + return + } + log.Succeed() +} + +// Start starts up the required compute and public interface +func (session *Session) Start(parameters *types.StartParameters) { + hostedZoneName := parameters.HostedZoneName + domainName := parameters.DomainName + publicIP := session.createPublicIP(hostedZoneName, domainName) + instanceID := session.addEcsInstance() + session.waitTillInstanceRunning(*instanceID) + session.attachPublicIPToEcsInstance(publicIP, instanceID) +} diff --git a/provider/aws/stop.go b/provider/aws/stop.go new file mode 100644 index 0000000..a4fed9b --- /dev/null +++ b/provider/aws/stop.go @@ -0,0 +1,61 @@ +package aws + +import ( + "fmt" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/cloudformation" + "github.com/aws/aws-sdk-go-v2/service/ec2" + "github.com/kahgeh/devenv/logger" + "github.com/kahgeh/devenv/utils/ctx" +) + +func (session *Session) removeEcsInstance() { + log := logger.NewTaskLogger() + defer log.LogDone() + config := session.GetComputeConfig() + stackName := config.EcsSpotFleetStackName + + spotFleetRequestID := session.getStackOutputValue( + fmt.Sprintf("%s-spotfleetrequest", stackName), + stackName) + + api := ec2.New(session.config) + modificationRequest := api.ModifySpotFleetRequestRequest(&ec2.ModifySpotFleetRequestInput{ + SpotFleetRequestId: spotFleetRequestID, + TargetCapacity: aws.Int64(0), + }) + + _, err := modificationRequest.Send(ctx.GetContext()) + if err != nil { + log.Fail("failed to remove instance") + return + } + log.Succeed() + +} + +func (session *Session) deletePublicIP() { + log := logger.NewTaskLogger() + defer log.LogDone() + config := session.GetComputeConfig() + stackName := config.PublicIPStackName + stack := NewStack(stackName, session) + api := stack.api + stack.Delete() + err := api.WaitUntilStackDeleteComplete(ctx.GetContext(), &cloudformation.DescribeStacksInput{ + StackName: &stack.name, + }) + if err != nil { + log.Debug(err.Error()) + log.Fail("fail to wait for public ip deletion") + return + } + log.Succeed() +} + +// Stop terminates the ecs instance and remove any attached resources +func (session *Session) Stop() { + session.removeEcsInstance() + session.deletePublicIP() +} diff --git a/provider/aws/teardown.go b/provider/aws/teardown.go new file mode 100644 index 0000000..187a48e --- /dev/null +++ b/provider/aws/teardown.go @@ -0,0 +1,107 @@ +package aws + +import ( + "fmt" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/aws/awserr" + "github.com/aws/aws-sdk-go-v2/service/cloudformation" + "github.com/aws/aws-sdk-go-v2/service/ec2" + "github.com/kahgeh/devenv/logger" + "github.com/kahgeh/devenv/utils/ctx" + "os" +) + +func (session *Session) deleteKeyPair() { + log := logger.NewTaskLogger() + defer log.LogDone() + + keyPairName := session.GetKeyPairName() + api := ec2.New(session.config) + request := api.DeleteKeyPairRequest(&ec2.DeleteKeyPairInput{ + KeyName: aws.String(keyPairName), + }) + _, err := request.Send(ctx.GetContext()) + if err != nil { + if aerr, ok := err.(awserr.Error); ok { + if aerr.Code() == "InvalidKeyPair.NotFound" { + log.Infof("Key pair %q does not exists", keyPairName) + return + } + log.Debug(aerr.Message()) + log.Fail(aerr.Code()) + return + } + log.Failf("%v", err) + return + } + + sshFolderPath := getSshFolderPath() + sshPrivateKeyFilePath := fmt.Sprintf("%s/%s.pem", sshFolderPath, keyPairName) + log.Infof("deleting ssh key %s...", sshPrivateKeyFilePath) + if stat, _ := os.Stat(sshPrivateKeyFilePath); stat != nil { + err := os.Remove(sshPrivateKeyFilePath) + if err != nil { + log.Failf("fail to delete %s", sshPrivateKeyFilePath) + } + } + log.Succeed() +} + +func (session *Session) deleteVpc() { + log := logger.NewTaskLogger() + defer log.LogDone() + config := session.GetComputeConfig() + stackName := config.VpcStackName + stack := NewStack(stackName, session) + stack.Delete() + log.Succeed() +} + +func (session *Session) deleteEcsCluster() { + log := logger.NewTaskLogger() + defer log.LogDone() + config := session.GetComputeConfig() + stackName := config.EcsClusterStackName + + stack := NewStack(stackName, session) + api := stack.api + stack.Delete() + err := api.WaitUntilStackDeleteComplete(ctx.GetContext(), &cloudformation.DescribeStacksInput{ + StackName: &stack.name, + }) + + if err != nil { + log.Debug(err.Error()) + log.Fail("waiting ecs cluster deletion failed") + return + } + + log.Succeed() +} + +func (session *Session) deleteSpotFleet() { + log := logger.NewTaskLogger() + defer log.LogDone() + config := session.GetComputeConfig() + stackName := config.EcsSpotFleetStackName + stack := NewStack(stackName, session) + api := stack.api + stack.Delete() + err := api.WaitUntilStackDeleteComplete(ctx.GetContext(), &cloudformation.DescribeStacksInput{ + StackName: &stack.name, + }) + if err != nil { + log.Debug(err.Error()) + log.Fail("waiting spot fleet deletion failed") + return + } + log.Succeed() +} + +// Delete tears down the compute +func (session *Session) Delete() { + session.deleteSpotFleet() + session.deleteEcsCluster() + session.deleteVpc() + session.deleteKeyPair() +} diff --git a/provider/provider.go b/provider/provider.go new file mode 100644 index 0000000..2472b4d --- /dev/null +++ b/provider/provider.go @@ -0,0 +1,42 @@ +package provider + +import ( + "fmt" + "github.com/kahgeh/devenv/provider/types" + + daws "github.com/kahgeh/devenv/provider/aws" +) + +type Provider string + +const ( + Aws Provider = "aws" +) + +// Session is the cloud provider session +type Session interface { + Initialise(parameters *types.InitialisationParameters) + Delete() + Start(config *types.StartParameters) + Stop() + Deploy(parameters *types.DeployParameters) +} + +// NotSupported error +type NotSupported struct { + s string + name string +} + +func (e *NotSupported) Error() string { + return e.s +} + +func NewSession(provider Provider) (Session, error) { + switch provider { + case Aws: + return daws.CreateAwsSession() + default: + return nil, &NotSupported{s: fmt.Sprintf("Provider %v not supported", provider), name: string(provider)} + } +} diff --git a/provider/types/types.go b/provider/types/types.go new file mode 100644 index 0000000..61d0dc9 --- /dev/null +++ b/provider/types/types.go @@ -0,0 +1,29 @@ +package types + +type AppType string + +const ( + FrontProxy AppType = "front-proxy" + Api AppType = "api" +) + +type DeployParameters struct { + AppType AppType + AppName string + Path string + EnvironmentName string + DomainName string + DomainEmail string +} + +type InitialisationParameters struct { + DomainName string + DomainEmail string + EnvironmentName string +} + +type StartParameters struct { + HostedZoneName string + DomainName string + EnvironmentName string +} diff --git a/sample/Dockerfile b/sample/Dockerfile new file mode 100644 index 0000000..96c06f5 --- /dev/null +++ b/sample/Dockerfile @@ -0,0 +1,38 @@ +# Use the offical golang image to create a binary. +# This is based on Debian and sets the GOPATH to /go. +# https://hub.docker.com/_/golang +FROM golang:1.15-buster as builder + +# Create and change to the app directory. +WORKDIR /app + +# Retrieve application dependencies. +# This allows the container build to reuse cached dependencies. +# Expecting to copy go.mod and if present go.sum. +COPY go.* ./ +RUN go mod download + +# Copy local code to the container image. +COPY . ./ + +# Build the binary. +RUN go build -mod=readonly -v -o server + +# Use the official Debian slim image for a lean production container. +# https://hub.docker.com/_/debian +# https://docs.docker.com/develop/develop-images/multistage-build/#use-multi-stage-builds +FROM debian:buster-slim +RUN set -x && apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y \ + ca-certificates && \ + rm -rf /var/lib/apt/lists/* + +# Copy the binary to the production image from the builder stage. +COPY --from=builder /app/server /app/server +EXPOSE 80 + +LABEL CLUSTER_80_CATEGORY=api \ + CLUSTER_80_NAME=hello2 \ + CULSTER_80_URLPREFIX=hello2 + +# Run the web service on container startup. +CMD ["/app/server"] \ No newline at end of file diff --git a/sample/go.mod b/sample/go.mod new file mode 100644 index 0000000..4f7e828 --- /dev/null +++ b/sample/go.mod @@ -0,0 +1,3 @@ +module github.com/kahgeh/cloudrun-quickstart + +go 1.15 diff --git a/sample/main.go b/sample/main.go new file mode 100644 index 0000000..8391f69 --- /dev/null +++ b/sample/main.go @@ -0,0 +1,37 @@ +package main + +import ( + "fmt" + "log" + "net/http" + "os" +) + +func main() { + log.Print("starting server...") + http.HandleFunc("/", handler) + + // Determine port for HTTP service. + port := os.Getenv("PORT") + if port == "" { + port = "80" + log.Printf("defaulting to port %s", port) + } + + // Start HTTP server. + log.Printf("listening on port %s", port) + if err := http.ListenAndServe(":"+port, nil); err != nil { + log.Fatal(err) + } +} + +func handler(w http.ResponseWriter, _ *http.Request) { + name := os.Getenv("NAME") + if name == "" { + name = "0.^.0" + } + _, err := fmt.Fprintf(w, "Hello %s!\n", name) + if err != nil { + log.Println("error writing to response stream") + } +} diff --git a/utils/ctx/ctx.go b/utils/ctx/ctx.go new file mode 100644 index 0000000..5864775 --- /dev/null +++ b/utils/ctx/ctx.go @@ -0,0 +1,51 @@ +package ctx + +import ( + "context" + "fmt" + "os" + "os/signal" +) + +type ConsoleAppContext struct { + ctx context.Context + cancel context.CancelFunc + osSigChan chan os.Signal +} + +var consoleAppCtx *ConsoleAppContext + +func init() { + ctx := context.Background() + ctx, cancel := context.WithCancel(ctx) + osSigChan := make(chan os.Signal, 1) + + consoleAppCtx = &ConsoleAppContext{ctx: ctx, + cancel: cancel, + osSigChan: osSigChan} + + signal.Notify(osSigChan, os.Interrupt) + // trap Ctrl+C and call cancel on the context +} + +func GetContext() context.Context { + return consoleAppCtx.ctx +} + +func WaitOnCtrlCSignalOrCompletion() { + select { + case <-consoleAppCtx.osSigChan: + fmt.Println("program terminated because of user cancellation") + consoleAppCtx.cancel() + case <-consoleAppCtx.ctx.Done(): + } +} + +func CleanUp() { + consoleAppCtx.cleanUp() +} + +func (consoleAppCtx *ConsoleAppContext) cleanUp() { + signal.Stop(consoleAppCtx.osSigChan) + consoleAppCtx.cancel() +} diff --git a/utils/fs.go b/utils/fs.go new file mode 100644 index 0000000..fbb4990 --- /dev/null +++ b/utils/fs.go @@ -0,0 +1,31 @@ +package utils + +import ( + "fmt" + "github.com/mitchellh/go-homedir" + "io" + "os" +) + +// CreateFolderIfNotExist creates folder and assign permissive permission if it doesn't exist +func CreateFolderIfNotExist(folderPath string) error { + if _, err := os.Stat(folderPath); os.IsNotExist(err) { + return os.Mkdir(folderPath, 7666) + } + return nil +} + +func CloseReadCloser(closer io.ReadCloser, log func(x string)) { + if err := closer.Close(); err != nil { + log("failed to close") + } +} + +func GetSshFolderPath() string { + home, err := homedir.Dir() + if err != nil { + fmt.Println(err) + os.Exit(1) + } + return fmt.Sprintf("%v/.ssh", home) +} \ No newline at end of file