yunion.io/x/cloudmux@v0.3.10-0-alpha.1/cmd/cloudpodscli/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/cloudpods"
    29  	_ "yunion.io/x/cloudmux/pkg/multicloud/cloudpods/shell"
    30  	"yunion.io/x/onecloud/pkg/util/shellutils"
    31  )
    32  
    33  type BaseOptions struct {
    34  	Debug        bool   `help:"debug mode"`
    35  	AuthURL      string `help:"Auth URL" default:"$CLOUDPODS_AUTH_URL" metavar:"CLOUDPODS_AUTH_URL"`
    36  	AccessKey    string `help:"AccessKey" default:"$CLOUDPODS_ACCESS_KEY" metavar:"CLOUDPODS_ACCESS_KEY"`
    37  	AccessSecret string `help:"AccessSecret" default:"$CLOUDPODS_ACCESS_SECRET" metavar:"CLOUDPODS_ACCESS_SECRET"`
    38  	RegionId     string `help:"RegionId" default:"$CLOUDPODS_REGION_ID|default" metavar:"CLOUDPODS_REGION_ID"`
    39  	SUBCOMMAND   string `help:"cloudpodscli subcommand" subcommand:"true"`
    40  }
    41  
    42  func getSubcommandParser() (*structarg.ArgumentParser, error) {
    43  	parse, err := structarg.NewArgumentParserWithHelp(&BaseOptions{},
    44  		"cloudpodscli",
    45  		"Command-line interface to cloudpods API.",
    46  		`See "cloudpodscli COMMAND --help" for help on a specific command.`)
    47  
    48  	if err != nil {
    49  		return nil, err
    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  		_, err = subcmd.AddSubParserWithHelp(v.Options, v.Command, v.Desc, v.Callback)
    58  		if err != nil {
    59  			return nil, err
    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) (*cloudpods.SRegion, error) {
    72  	if len(options.AuthURL) == 0 {
    73  		return nil, fmt.Errorf("Missing AuthURL")
    74  	}
    75  
    76  	if len(options.AccessKey) == 0 {
    77  		return nil, fmt.Errorf("Missing access key")
    78  	}
    79  
    80  	if len(options.AccessSecret) == 0 {
    81  		return nil, fmt.Errorf("Missing access secret")
    82  	}
    83  
    84  	cfg := &httpproxy.Config{
    85  		HTTPProxy:  os.Getenv("HTTP_PROXY"),
    86  		HTTPSProxy: os.Getenv("HTTPS_PROXY"),
    87  		NoProxy:    os.Getenv("NO_PROXY"),
    88  	}
    89  	cfgProxyFunc := cfg.ProxyFunc()
    90  	proxyFunc := func(req *http.Request) (*url.URL, error) {
    91  		return cfgProxyFunc(req.URL)
    92  	}
    93  
    94  	cli, err := cloudpods.NewCloudpodsClient(
    95  		cloudpods.NewCloudpodsClientConfig(
    96  			options.AuthURL,
    97  			options.AccessKey,
    98  			options.AccessSecret,
    99  		).Debug(options.Debug).
   100  			CloudproviderConfig(
   101  				cloudprovider.ProviderConfig{
   102  					ProxyFunc: proxyFunc,
   103  				},
   104  			),
   105  	)
   106  	if err != nil {
   107  		return nil, err
   108  	}
   109  	region, err := cli.GetRegion(options.RegionId)
   110  	if err != nil {
   111  		return nil, err
   112  	}
   113  	return region, nil
   114  }
   115  
   116  func main() {
   117  	parser, err := getSubcommandParser()
   118  	if err != nil {
   119  		showErrorAndExit(err)
   120  	}
   121  	err = parser.ParseArgs(os.Args[1:], false)
   122  	options := parser.Options().(*BaseOptions)
   123  
   124  	if parser.IsHelpSet() {
   125  		fmt.Print(parser.HelpString())
   126  		return
   127  	}
   128  	subcmd := parser.GetSubcommand()
   129  	subparser := subcmd.GetSubParser()
   130  	if err != nil || subparser == nil {
   131  		if subparser != nil {
   132  			fmt.Print(subparser.Usage())
   133  		} else {
   134  			fmt.Print(parser.Usage())
   135  		}
   136  		showErrorAndExit(err)
   137  		return
   138  	}
   139  	suboptions := subparser.Options()
   140  	if subparser.IsHelpSet() {
   141  		fmt.Print(subparser.HelpString())
   142  		return
   143  	}
   144  	var region *cloudpods.SRegion
   145  	region, err = newClient(options)
   146  	if err != nil {
   147  		showErrorAndExit(err)
   148  	}
   149  	err = subcmd.Invoke(region, suboptions)
   150  	if err != nil {
   151  		showErrorAndExit(err)
   152  	}
   153  }