yunion.io/x/cloudmux@v0.3.10-0-alpha.1/cmd/aliyuncli/main.go (about)

     1  // Copyright 2019 Yunion
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package main
    16  
    17  import (
    18  	"fmt"
    19  	"net/http"
    20  	"net/url"
    21  	"os"
    22  
    23  	"golang.org/x/net/http/httpproxy"
    24  
    25  	"yunion.io/x/structarg"
    26  
    27  	"yunion.io/x/cloudmux/pkg/cloudprovider"
    28  	"yunion.io/x/cloudmux/pkg/multicloud/aliyun"
    29  	_ "yunion.io/x/cloudmux/pkg/multicloud/aliyun/shell"
    30  	"yunion.io/x/onecloud/pkg/util/shellutils"
    31  )
    32  
    33  type BaseOptions struct {
    34  	Debug      bool   `help:"debug mode"`
    35  	CloudEnv   string `help:"Cloud environment" default:"$ALIYUN_CLOUD_ENV" choices:"InternationalCloud|FinanceCloud" metavar:"ALIYUN_CLOUD_ENV"`
    36  	AccessKey  string `help:"Access key" default:"$ALIYUN_ACCESS_KEY" metavar:"ALIYUN_ACCESS_KEY"`
    37  	Secret     string `help:"Secret" default:"$ALIYUN_SECRET" metavar:"ALIYUN_SECRET"`
    38  	RegionId   string `help:"RegionId" default:"$ALIYUN_REGION" metavar:"ALIYUN_REGION"`
    39  	SUBCOMMAND string `help:"aliyuncli subcommand" subcommand:"true"`
    40  }
    41  
    42  func getSubcommandParser() (*structarg.ArgumentParser, error) {
    43  	parse, e := structarg.NewArgumentParserWithHelp(&BaseOptions{},
    44  		"aliyuncli",
    45  		"Command-line interface to aliyun API.",
    46  		`See "aliyuncli COMMAND --help" for help on a specific command.`)
    47  
    48  	if e != nil {
    49  		return nil, e
    50  	}
    51  
    52  	subcmd := parse.GetSubcommand()
    53  	if subcmd == nil {
    54  		return nil, fmt.Errorf("No subcommand argument.")
    55  	}
    56  
    57  	for _, v := range shellutils.CommandTable {
    58  		_, e := subcmd.AddSubParserWithHelp(v.Options, v.Command, v.Desc, v.Callback)
    59  		if e != nil {
    60  			return nil, e
    61  		}
    62  	}
    63  	return parse, nil
    64  }
    65  
    66  func showErrorAndExit(e error) {
    67  	fmt.Fprintf(os.Stderr, "%s", e)
    68  	fmt.Fprintln(os.Stderr)
    69  	os.Exit(1)
    70  }
    71  
    72  func newClient(options *BaseOptions) (*aliyun.SRegion, error) {
    73  	if len(options.AccessKey) == 0 {
    74  		return nil, fmt.Errorf("Missing accessKey")
    75  	}
    76  
    77  	if len(options.Secret) == 0 {
    78  		return nil, fmt.Errorf("Missing secret")
    79  	}
    80  
    81  	cfg := &httpproxy.Config{
    82  		HTTPProxy:  os.Getenv("HTTP_PROXY"),
    83  		HTTPSProxy: os.Getenv("HTTPS_PROXY"),
    84  		NoProxy:    os.Getenv("NO_PROXY"),
    85  	}
    86  	cfgProxyFunc := cfg.ProxyFunc()
    87  	proxyFunc := func(req *http.Request) (*url.URL, error) {
    88  		return cfgProxyFunc(req.URL)
    89  	}
    90  
    91  	cli, err := aliyun.NewAliyunClient(
    92  		aliyun.NewAliyunClientConfig(
    93  			options.CloudEnv,
    94  			options.AccessKey,
    95  			options.Secret,
    96  		).Debug(options.Debug).
    97  			CloudproviderConfig(
    98  				cloudprovider.ProviderConfig{
    99  					ProxyFunc: proxyFunc,
   100  				},
   101  			),
   102  	)
   103  	if err != nil {
   104  		return nil, err
   105  	}
   106  
   107  	region := cli.GetRegion(options.RegionId)
   108  	if region == nil {
   109  		return nil, fmt.Errorf("No such region %s", options.RegionId)
   110  	}
   111  
   112  	return region, nil
   113  }
   114  
   115  func main() {
   116  	parser, e := getSubcommandParser()
   117  	if e != nil {
   118  		showErrorAndExit(e)
   119  	}
   120  	e = parser.ParseArgs(os.Args[1:], false)
   121  	options := parser.Options().(*BaseOptions)
   122  
   123  	if parser.IsHelpSet() {
   124  		fmt.Print(parser.HelpString())
   125  		return
   126  	}
   127  	subcmd := parser.GetSubcommand()
   128  	subparser := subcmd.GetSubParser()
   129  	if e != nil || subparser == nil {
   130  		if subparser != nil {
   131  			fmt.Print(subparser.Usage())
   132  		} else {
   133  			fmt.Print(parser.Usage())
   134  		}
   135  		showErrorAndExit(e)
   136  		return
   137  	}
   138  	suboptions := subparser.Options()
   139  	if subparser.IsHelpSet() {
   140  		fmt.Print(subparser.HelpString())
   141  		return
   142  	}
   143  	var region *aliyun.SRegion
   144  	region, e = newClient(options)
   145  	if e != nil {
   146  		showErrorAndExit(e)
   147  	}
   148  	e = subcmd.Invoke(region, suboptions)
   149  	if e != nil {
   150  		showErrorAndExit(e)
   151  	}
   152  }