yunion.io/x/cloudmux@v0.3.10-0-alpha.1/cmd/ctyuncli/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/ctyun"
    29  	_ "yunion.io/x/cloudmux/pkg/multicloud/ctyun/shell"
    30  	"yunion.io/x/onecloud/pkg/util/shellutils"
    31  )
    32  
    33  type BaseOptions struct {
    34  	cloudprovider.SCtyunExtraOptions
    35  
    36  	Debug      bool   `help:"Show debug" default:"false"`
    37  	AccessKey  string `help:"Access key" default:"$CTYUN_ACCESS_KEY"`
    38  	Secret     string `help:"Secret" default:"$CTYUN_SECRET"`
    39  	RegionId   string `help:"RegionId" default:"$CTYUN_REGION"`
    40  	SUBCOMMAND string `help:"ctyuncli subcommand" subcommand:"true"`
    41  }
    42  
    43  func getSubcommandParser() (*structarg.ArgumentParser, error) {
    44  	parse, e := structarg.NewArgumentParserWithHelp(&BaseOptions{},
    45  		"ctyuncli",
    46  		"Command-line interface to ctyun API.",
    47  		`See "ctyuncli COMMAND --help" for help on a specific command.`)
    48  
    49  	if e != nil {
    50  		return nil, e
    51  	}
    52  
    53  	subcmd := parse.GetSubcommand()
    54  	if subcmd == nil {
    55  		return nil, fmt.Errorf("No subcommand argument.")
    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) (*ctyun.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 := ctyun.NewSCtyunClient(
    92  		ctyun.NewSCtyunClientConfig(
    93  			options.AccessKey, options.Secret, &options.SCtyunExtraOptions,
    94  		).Debug(options.Debug).
    95  			CloudproviderConfig(
    96  				cloudprovider.ProviderConfig{
    97  					ProxyFunc: proxyFunc,
    98  				},
    99  			),
   100  	)
   101  	if err != nil {
   102  		return nil, err
   103  	}
   104  
   105  	region := cli.GetRegion(options.RegionId)
   106  	if region == nil {
   107  		return nil, fmt.Errorf("No such region %s", options.RegionId)
   108  	}
   109  
   110  	return region, nil
   111  }
   112  
   113  func main() {
   114  	parser, e := getSubcommandParser()
   115  	if e != nil {
   116  		showErrorAndExit(e)
   117  	}
   118  	e = parser.ParseArgs(os.Args[1:], false)
   119  	options := parser.Options().(*BaseOptions)
   120  
   121  	if parser.IsHelpSet() {
   122  		fmt.Print(parser.HelpString())
   123  		return
   124  	}
   125  	subcmd := parser.GetSubcommand()
   126  	subparser := subcmd.GetSubParser()
   127  	if e != nil || subparser == nil {
   128  		if subparser != nil {
   129  			fmt.Print(subparser.Usage())
   130  		} else {
   131  			fmt.Print(parser.Usage())
   132  		}
   133  		showErrorAndExit(e)
   134  	}
   135  	suboptions := subparser.Options()
   136  	if subparser.IsHelpSet() {
   137  		fmt.Print(subparser.HelpString())
   138  		return
   139  	}
   140  	var region *ctyun.SRegion
   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  }