yunion.io/x/cloudmux@v0.3.10-0-alpha.1/cmd/incloudspherecli/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/incloudsphere"
    29  	_ "yunion.io/x/cloudmux/pkg/multicloud/incloudsphere/shell"
    30  	"yunion.io/x/onecloud/pkg/util/shellutils"
    31  )
    32  
    33  type BaseOptions struct {
    34  	Debug        bool   `help:"debug mode"`
    35  	Host         string `help:"Host" default:"$INCLOUD_SPHERE_HOST" metavar:"INCLOUD_SPHERE_HOST"`
    36  	AccessKeyId  string `help:"AccessKey" default:"$INCLOUD_SPHERE_ACCESS_KEY_ID" metavar:"INCLOUD_SPHERE_ACCESS_KEY_ID"`
    37  	AccessSecret string `help:"AccessSecret" default:"$INCLOUD_SPHERE_ACCESS_KEY_SECRET" metavar:"INCLOUD_SPHERE_ACCESS_SECRET"`
    38  	SUBCOMMAND   string `help:"incloudspherecli subcommand" subcommand:"true"`
    39  }
    40  
    41  func getSubcommandParser() (*structarg.ArgumentParser, error) {
    42  	parse, e := structarg.NewArgumentParserWithHelp(&BaseOptions{},
    43  		"incloudspherecli",
    44  		"Command-line interface to InCloud Sphere API.",
    45  		`See "incloudspherecli COMMAND --help" for help on a specific command.`)
    46  
    47  	if e != nil {
    48  		return nil, e
    49  	}
    50  
    51  	subcmd := parse.GetSubcommand()
    52  	if subcmd == nil {
    53  		return nil, fmt.Errorf("No subcommand argument.")
    54  	}
    55  	for _, v := range shellutils.CommandTable {
    56  		_, e := subcmd.AddSubParserWithHelp(v.Options, v.Command, v.Desc, v.Callback)
    57  		if e != nil {
    58  			return nil, e
    59  		}
    60  	}
    61  	return parse, nil
    62  }
    63  
    64  func showErrorAndExit(e error) {
    65  	fmt.Fprintf(os.Stderr, "%s", e)
    66  	fmt.Fprintln(os.Stderr)
    67  	os.Exit(1)
    68  }
    69  
    70  func newClient(options *BaseOptions) (*incloudsphere.SRegion, error) {
    71  	if len(options.Host) == 0 {
    72  		return nil, fmt.Errorf("Missing host")
    73  	}
    74  
    75  	if len(options.AccessKeyId) == 0 {
    76  		return nil, fmt.Errorf("Missing access key id")
    77  	}
    78  
    79  	if len(options.AccessSecret) == 0 {
    80  		return nil, fmt.Errorf("Missing access secret")
    81  	}
    82  
    83  	cfg := &httpproxy.Config{
    84  		HTTPProxy:  os.Getenv("HTTP_PROXY"),
    85  		HTTPSProxy: os.Getenv("HTTPS_PROXY"),
    86  		NoProxy:    os.Getenv("NO_PROXY"),
    87  	}
    88  	cfgProxyFunc := cfg.ProxyFunc()
    89  	proxyFunc := func(req *http.Request) (*url.URL, error) {
    90  		return cfgProxyFunc(req.URL)
    91  	}
    92  
    93  	cli, err := incloudsphere.NewSphereClient(
    94  		incloudsphere.NewSphereClientConfig(
    95  			options.Host,
    96  			options.AccessKeyId,
    97  			options.AccessSecret,
    98  		).Debug(options.Debug).
    99  			CloudproviderConfig(
   100  				cloudprovider.ProviderConfig{
   101  					ProxyFunc: proxyFunc,
   102  				},
   103  			),
   104  	)
   105  	if err != nil {
   106  		return nil, err
   107  	}
   108  
   109  	return cli.GetRegion()
   110  }
   111  
   112  func main() {
   113  	parser, e := getSubcommandParser()
   114  	if e != nil {
   115  		showErrorAndExit(e)
   116  	}
   117  	e = parser.ParseArgs(os.Args[1:], false)
   118  	options := parser.Options().(*BaseOptions)
   119  
   120  	if parser.IsHelpSet() {
   121  		fmt.Print(parser.HelpString())
   122  		return
   123  	}
   124  	subcmd := parser.GetSubcommand()
   125  	subparser := subcmd.GetSubParser()
   126  	if e != nil || subparser == nil {
   127  		if subparser != nil {
   128  			fmt.Print(subparser.Usage())
   129  		} else {
   130  			fmt.Print(parser.Usage())
   131  		}
   132  		showErrorAndExit(e)
   133  		return
   134  	}
   135  	suboptions := subparser.Options()
   136  	if subparser.IsHelpSet() {
   137  		fmt.Print(subparser.HelpString())
   138  		return
   139  	}
   140  	var region *incloudsphere.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  }