yunion.io/x/cloudmux@v0.3.10-0-alpha.1/cmd/qcloudcli/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/qcloud"
    29  	_ "yunion.io/x/cloudmux/pkg/multicloud/qcloud/shell"
    30  	"yunion.io/x/onecloud/pkg/util/shellutils"
    31  )
    32  
    33  type BaseOptions struct {
    34  	Debug      bool   `help:"debug mode"`
    35  	AppID      string `help:"AppID" default:"$QCLOUD_APPID" metavar:"QCLOUD_APPID"`
    36  	SecretID   string `help:"Secret" default:"$QCLOUD_SECRET_ID" metavar:"QCLOUD_SECRET_ID"`
    37  	SecretKey  string `help:"Access key" default:"$QCLOUD_SECRET_KEY" metavar:"QCLOUD_SECRET_KEY"`
    38  	RegionId   string `help:"RegionId" default:"$QCLOUD_REGION" metavar:"QCLOUD_REGION"`
    39  	SUBCOMMAND string `help:"azurecli subcommand" subcommand:"true"`
    40  }
    41  
    42  func getSubcommandParser() (*structarg.ArgumentParser, error) {
    43  	parse, e := structarg.NewArgumentParserWithHelp(&BaseOptions{},
    44  		"qcloudcli",
    45  		"Command-line interface to tencentcloud API.",
    46  		`See "qcloudcli 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  	for _, v := range shellutils.CommandTable {
    57  		_, e := subcmd.AddSubParserWithHelp(v.Options, v.Command, v.Desc, v.Callback)
    58  		if e != nil {
    59  			return nil, e
    60  		}
    61  	}
    62  	return parse, nil
    63  }
    64  
    65  func showErrorAndExit(e error) {
    66  	fmt.Fprintf(os.Stderr, "%s", e)
    67  	fmt.Fprintln(os.Stderr)
    68  	os.Exit(1)
    69  }
    70  
    71  func newClient(options *BaseOptions) (*qcloud.SRegion, error) {
    72  	if len(options.SecretKey) == 0 {
    73  		return nil, fmt.Errorf("Missing SecretKey")
    74  	}
    75  
    76  	if len(options.SecretID) == 0 {
    77  		return nil, fmt.Errorf("Missing SecretID")
    78  	}
    79  
    80  	cfg := &httpproxy.Config{
    81  		HTTPProxy:  os.Getenv("HTTP_PROXY"),
    82  		HTTPSProxy: os.Getenv("HTTPS_PROXY"),
    83  		NoProxy:    os.Getenv("NO_PROXY"),
    84  	}
    85  	cfgProxyFunc := cfg.ProxyFunc()
    86  	proxyFunc := func(req *http.Request) (*url.URL, error) {
    87  		return cfgProxyFunc(req.URL)
    88  	}
    89  
    90  	if cli, err := qcloud.NewQcloudClient(
    91  		qcloud.NewQcloudClientConfig(
    92  			options.SecretID,
    93  			options.SecretKey,
    94  		).AppId(options.AppID).
    95  			Debug(options.Debug).
    96  			CloudproviderConfig(
    97  				cloudprovider.ProviderConfig{
    98  					ProxyFunc: proxyFunc,
    99  				},
   100  			),
   101  	); err != nil {
   102  		return nil, err
   103  	} else if region := cli.GetRegion(options.RegionId); region == nil {
   104  		return nil, fmt.Errorf("No such region %s", options.RegionId)
   105  	} else {
   106  		return region, nil
   107  	}
   108  }
   109  
   110  func main() {
   111  	parser, e := getSubcommandParser()
   112  	if e != nil {
   113  		showErrorAndExit(e)
   114  	}
   115  	e = parser.ParseArgs(os.Args[1:], false)
   116  	options := parser.Options().(*BaseOptions)
   117  
   118  	if parser.IsHelpSet() {
   119  		fmt.Print(parser.HelpString())
   120  		return
   121  	}
   122  	subcmd := parser.GetSubcommand()
   123  	subparser := subcmd.GetSubParser()
   124  	if e != nil || subparser == nil {
   125  		if subparser != nil {
   126  			fmt.Print(subparser.Usage())
   127  		} else {
   128  			fmt.Print(parser.Usage())
   129  		}
   130  		showErrorAndExit(e)
   131  	}
   132  	suboptions := subparser.Options()
   133  	if subparser.IsHelpSet() {
   134  		fmt.Print(subparser.HelpString())
   135  		return
   136  	}
   137  	var region *qcloud.SRegion
   138  	if len(options.RegionId) == 0 {
   139  		options.RegionId = qcloud.QCLOUD_DEFAULT_REGION
   140  	}
   141  	region, e = newClient(options)
   142  	if e != nil {
   143  		showErrorAndExit(e)
   144  	}
   145  	e = subcmd.Invoke(region, suboptions)
   146  	if e != nil {
   147  		showErrorAndExit(e)
   148  	}
   149  }