mirror of
https://github.com/lxc/incus.git
synced 2026-02-05 09:46:19 +01:00
4
.gitignore
vendored
Normal file
4
.gitignore
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
*.swp
|
||||
|
||||
lxd/lxd
|
||||
lxc/lxc
|
||||
111
client.go
Normal file
111
client.go
Normal file
@@ -0,0 +1,111 @@
|
||||
package lxd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"path"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Client can talk to a lxd daemon.
|
||||
type Client struct {
|
||||
config Config
|
||||
Remote *RemoteConfig
|
||||
http http.Client
|
||||
baseURL string
|
||||
}
|
||||
|
||||
// NewClient returns a new lxd client.
|
||||
func NewClient(config *Config, raw string) (*Client, string, error) {
|
||||
c := Client{
|
||||
config: *config,
|
||||
http: http.Client{
|
||||
// Added on Go 1.3. Wait until it's more popular.
|
||||
//Timeout: 10 * time.Second,
|
||||
},
|
||||
}
|
||||
|
||||
result := strings.SplitN(raw, ":", 2)
|
||||
var remote string
|
||||
var container string
|
||||
|
||||
if len(result) == 1 {
|
||||
remote = config.DefaultRemote
|
||||
container = result[0]
|
||||
} else {
|
||||
remote = result[0]
|
||||
container = result[1]
|
||||
}
|
||||
|
||||
// TODO: Here, we don't support configurable local remotes, we only
|
||||
// support the default local lxd at /var/lib/lxd/unix.socket.
|
||||
if remote == "" {
|
||||
c.baseURL = "http://unix.socket"
|
||||
c.http.Transport = &unixTransport
|
||||
} else if r, ok := config.Remotes[remote]; ok {
|
||||
c.baseURL = "http://" + r.Addr
|
||||
c.Remote = &r
|
||||
} else {
|
||||
return nil, "", fmt.Errorf("unknown remote name: %q", config.DefaultRemote)
|
||||
}
|
||||
if err := c.Ping(); err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
return &c, container, nil
|
||||
}
|
||||
|
||||
func (c *Client) getstr(base string, args map[string]string) (string, error) {
|
||||
vs := url.Values{}
|
||||
for k, v := range args {
|
||||
vs.Set(k, v)
|
||||
}
|
||||
|
||||
data, err := c.get(base + "?" + vs.Encode())
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(data), nil
|
||||
}
|
||||
|
||||
func (c *Client) get(elem ...string) ([]byte, error) {
|
||||
resp, err := c.http.Get(c.url(elem...))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
return ioutil.ReadAll(resp.Body)
|
||||
}
|
||||
|
||||
func (c *Client) url(elem ...string) string {
|
||||
return c.baseURL + path.Join(elem...)
|
||||
}
|
||||
|
||||
var unixTransport = http.Transport{
|
||||
Dial: func(network, addr string) (net.Conn, error) {
|
||||
if addr != "unix.socket:80" {
|
||||
return nil, fmt.Errorf("non-unix-socket addresses not supported yet")
|
||||
}
|
||||
raddr, err := net.ResolveUnixAddr("unix", VarPath("unix.socket"))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cannot resolve unix socket address: %v", err)
|
||||
}
|
||||
return net.DialUnix("unix", nil, raddr)
|
||||
},
|
||||
}
|
||||
|
||||
// Ping pings the daemon to see if it is up listening and working.
|
||||
func (c *Client) Ping() error {
|
||||
Debugf("pinging the daemon")
|
||||
data, err := c.getstr("/ping", nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if data != Version {
|
||||
return fmt.Errorf("version mismatch: mine: %q, daemon: %q", Version, data)
|
||||
}
|
||||
Debugf("pong received")
|
||||
return nil
|
||||
}
|
||||
91
config.go
Normal file
91
config.go
Normal file
@@ -0,0 +1,91 @@
|
||||
package lxd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"gopkg.in/yaml.v2"
|
||||
)
|
||||
|
||||
// Config holds settings to be used by a client or daemon.
|
||||
type Config struct {
|
||||
// TestOption is used only for testing purposes.
|
||||
TestOption string `yaml:"test-option,omitempty"`
|
||||
|
||||
// DefaultRemote holds the remote daemon name from the Remotes map
|
||||
// that the client should communicate with by default.
|
||||
// If empty it defaults to "local".
|
||||
DefaultRemote string `yaml:"default-remote"`
|
||||
|
||||
// Remotes defines a map of remote daemon names to the details for
|
||||
// communication with the named daemon.
|
||||
// The implicit "local" remote is always available and communicates
|
||||
// with the local daemon over a unix socket.
|
||||
Remotes map[string]RemoteConfig `yaml:"remotes"`
|
||||
|
||||
// ListenAddr defines an alternative address for the local daemon
|
||||
// to listen on. If empty, the daemon will listen only on the local
|
||||
// unix socket address.
|
||||
ListenAddr string `yaml:"listen-addr"`
|
||||
}
|
||||
|
||||
// RemoteConfig holds details for communication with a remote daemon.
|
||||
type RemoteConfig struct {
|
||||
Addr string `yaml:"addr"`
|
||||
}
|
||||
|
||||
var configPath = "$HOME/.lxd/config.yaml"
|
||||
|
||||
// LoadConfig reads the configuration from $HOME/.lxd/config.yaml.
|
||||
func LoadConfig() (*Config, error) {
|
||||
data, err := ioutil.ReadFile(os.ExpandEnv(configPath))
|
||||
if os.IsNotExist(err) {
|
||||
// A missing file is equivalent to the default configuration.
|
||||
return &Config{}, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cannot read config file: %v", err)
|
||||
}
|
||||
|
||||
var c Config
|
||||
err = yaml.Unmarshal(data, &c)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cannot parse configuration: %v", err)
|
||||
}
|
||||
if c.Remotes == nil {
|
||||
c.Remotes = make(map[string]RemoteConfig)
|
||||
}
|
||||
return &c, nil
|
||||
}
|
||||
|
||||
// SaveConfig writes the provided configuration to $HOME/.lxd/config.yaml.
|
||||
func SaveConfig(c *Config) error {
|
||||
fname := os.ExpandEnv(configPath)
|
||||
|
||||
// Ignore errors on these two calls. Create will report any problems.
|
||||
os.Remove(fname + ".new")
|
||||
os.Mkdir(filepath.Dir(fname), 0700)
|
||||
f, err := os.Create(fname + ".new")
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot create config file: %v", err)
|
||||
}
|
||||
|
||||
// If there are any errors, do not leave it around.
|
||||
defer f.Close()
|
||||
defer os.Remove(fname + ".new")
|
||||
|
||||
data, err := yaml.Marshal(c)
|
||||
_, err = f.Write(data)
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot write configuration: %v", err)
|
||||
}
|
||||
|
||||
f.Close()
|
||||
err = os.Rename(fname+".new", fname)
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot rename temporary config file: %v", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
28
flex.go
Normal file
28
flex.go
Normal file
@@ -0,0 +1,28 @@
|
||||
/* This is a FLEXible file which can be used by both client and daemon.
|
||||
* Teehee.
|
||||
*/
|
||||
package lxd
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
/*
|
||||
* Please increment the version number every time you change the API.
|
||||
*
|
||||
* Version 0.0.1: ping
|
||||
*/
|
||||
var Version = "0.0.1"
|
||||
|
||||
// VarPath returns the provided path elements joined by a slash and
|
||||
// appended to the end of $LXD_DIR, which defaults to /var/lib/lxd.
|
||||
func VarPath(path ...string) string {
|
||||
varDir := os.Getenv("LXD_DIR")
|
||||
if varDir == "" {
|
||||
varDir = "/var/lib/lxd"
|
||||
}
|
||||
items := []string{varDir}
|
||||
items = append(items, path...)
|
||||
return filepath.Join(items...)
|
||||
}
|
||||
24
internal/gnuflag/export_test.go
Normal file
24
internal/gnuflag/export_test.go
Normal file
@@ -0,0 +1,24 @@
|
||||
// Copyright 2010 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package gnuflag
|
||||
|
||||
import (
|
||||
"os"
|
||||
)
|
||||
|
||||
// Additional routines compiled into the package only during testing.
|
||||
|
||||
// ResetForTesting clears all flag state and sets the usage function as directed.
|
||||
// After calling ResetForTesting, parse errors in flag handling will not
|
||||
// exit the program.
|
||||
func ResetForTesting(usage func()) {
|
||||
commandLine = NewFlagSet(os.Args[0], ContinueOnError)
|
||||
Usage = usage
|
||||
}
|
||||
|
||||
// CommandLine returns the default FlagSet.
|
||||
func CommandLine() *FlagSet {
|
||||
return commandLine
|
||||
}
|
||||
890
internal/gnuflag/flag.go
Normal file
890
internal/gnuflag/flag.go
Normal file
@@ -0,0 +1,890 @@
|
||||
// Copyright 2009 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
/*
|
||||
Package flag implements command-line flag parsing in the GNU style.
|
||||
It is almost exactly the same as the standard flag package,
|
||||
the only difference being the extra argument to Parse.
|
||||
|
||||
Command line flag syntax:
|
||||
-f // single letter flag
|
||||
-fg // two single letter flags together
|
||||
--flag // multiple letter flag
|
||||
--flag x // non-boolean flags only
|
||||
-f x // non-boolean flags only
|
||||
-fx // if f is a non-boolean flag, x is its argument.
|
||||
|
||||
The last three forms are not permitted for boolean flags because the
|
||||
meaning of the command
|
||||
cmd -f *
|
||||
will change if there is a file called 0, false, etc. There is currently
|
||||
no way to turn off a boolean flag.
|
||||
|
||||
Flag parsing stops after the terminator "--", or just before the first
|
||||
non-flag argument ("-" is a non-flag argument) if the interspersed
|
||||
argument to Parse is false.
|
||||
*/
|
||||
package gnuflag
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// ErrHelp is the error returned if the flag -help is invoked but no such flag is defined.
|
||||
var ErrHelp = errors.New("flag: help requested")
|
||||
|
||||
// -- bool Value
|
||||
type boolValue bool
|
||||
|
||||
func newBoolValue(val bool, p *bool) *boolValue {
|
||||
*p = val
|
||||
return (*boolValue)(p)
|
||||
}
|
||||
|
||||
func (b *boolValue) Set(s string) error {
|
||||
v, err := strconv.ParseBool(s)
|
||||
*b = boolValue(v)
|
||||
return err
|
||||
}
|
||||
|
||||
func (b *boolValue) String() string { return fmt.Sprintf("%v", *b) }
|
||||
|
||||
// -- int Value
|
||||
type intValue int
|
||||
|
||||
func newIntValue(val int, p *int) *intValue {
|
||||
*p = val
|
||||
return (*intValue)(p)
|
||||
}
|
||||
|
||||
func (i *intValue) Set(s string) error {
|
||||
v, err := strconv.ParseInt(s, 0, 64)
|
||||
*i = intValue(v)
|
||||
return err
|
||||
}
|
||||
|
||||
func (i *intValue) String() string { return fmt.Sprintf("%v", *i) }
|
||||
|
||||
// -- int64 Value
|
||||
type int64Value int64
|
||||
|
||||
func newInt64Value(val int64, p *int64) *int64Value {
|
||||
*p = val
|
||||
return (*int64Value)(p)
|
||||
}
|
||||
|
||||
func (i *int64Value) Set(s string) error {
|
||||
v, err := strconv.ParseInt(s, 0, 64)
|
||||
*i = int64Value(v)
|
||||
return err
|
||||
}
|
||||
|
||||
func (i *int64Value) String() string { return fmt.Sprintf("%v", *i) }
|
||||
|
||||
// -- uint Value
|
||||
type uintValue uint
|
||||
|
||||
func newUintValue(val uint, p *uint) *uintValue {
|
||||
*p = val
|
||||
return (*uintValue)(p)
|
||||
}
|
||||
|
||||
func (i *uintValue) Set(s string) error {
|
||||
v, err := strconv.ParseUint(s, 0, 64)
|
||||
*i = uintValue(v)
|
||||
return err
|
||||
}
|
||||
|
||||
func (i *uintValue) String() string { return fmt.Sprintf("%v", *i) }
|
||||
|
||||
// -- uint64 Value
|
||||
type uint64Value uint64
|
||||
|
||||
func newUint64Value(val uint64, p *uint64) *uint64Value {
|
||||
*p = val
|
||||
return (*uint64Value)(p)
|
||||
}
|
||||
|
||||
func (i *uint64Value) Set(s string) error {
|
||||
v, err := strconv.ParseUint(s, 0, 64)
|
||||
*i = uint64Value(v)
|
||||
return err
|
||||
}
|
||||
|
||||
func (i *uint64Value) String() string { return fmt.Sprintf("%v", *i) }
|
||||
|
||||
// -- string Value
|
||||
type stringValue string
|
||||
|
||||
func newStringValue(val string, p *string) *stringValue {
|
||||
*p = val
|
||||
return (*stringValue)(p)
|
||||
}
|
||||
|
||||
func (s *stringValue) Set(val string) error {
|
||||
*s = stringValue(val)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *stringValue) String() string { return fmt.Sprintf("%s", *s) }
|
||||
|
||||
// -- float64 Value
|
||||
type float64Value float64
|
||||
|
||||
func newFloat64Value(val float64, p *float64) *float64Value {
|
||||
*p = val
|
||||
return (*float64Value)(p)
|
||||
}
|
||||
|
||||
func (f *float64Value) Set(s string) error {
|
||||
v, err := strconv.ParseFloat(s, 64)
|
||||
*f = float64Value(v)
|
||||
return err
|
||||
}
|
||||
|
||||
func (f *float64Value) String() string { return fmt.Sprintf("%v", *f) }
|
||||
|
||||
// -- time.Duration Value
|
||||
type durationValue time.Duration
|
||||
|
||||
func newDurationValue(val time.Duration, p *time.Duration) *durationValue {
|
||||
*p = val
|
||||
return (*durationValue)(p)
|
||||
}
|
||||
|
||||
func (d *durationValue) Set(s string) error {
|
||||
v, err := time.ParseDuration(s)
|
||||
*d = durationValue(v)
|
||||
return err
|
||||
}
|
||||
|
||||
func (d *durationValue) String() string { return (*time.Duration)(d).String() }
|
||||
|
||||
// Value is the interface to the dynamic value stored in a flag.
|
||||
// (The default value is represented as a string.)
|
||||
type Value interface {
|
||||
String() string
|
||||
Set(string) error
|
||||
}
|
||||
|
||||
// ErrorHandling defines how to handle flag parsing errors.
|
||||
type ErrorHandling int
|
||||
|
||||
const (
|
||||
ContinueOnError ErrorHandling = iota
|
||||
ExitOnError
|
||||
PanicOnError
|
||||
)
|
||||
|
||||
// A FlagSet represents a set of defined flags.
|
||||
type FlagSet struct {
|
||||
// Usage is the function called when an error occurs while parsing flags.
|
||||
// The field is a function (not a method) that may be changed to point to
|
||||
// a custom error handler.
|
||||
Usage func()
|
||||
|
||||
name string
|
||||
parsed bool
|
||||
actual map[string]*Flag
|
||||
formal map[string]*Flag
|
||||
args []string // arguments after flags
|
||||
procArgs []string // arguments being processed (gnu only)
|
||||
procFlag string // flag being processed (gnu only)
|
||||
allowIntersperse bool // (gnu only)
|
||||
exitOnError bool // does the program exit if there's an error?
|
||||
errorHandling ErrorHandling
|
||||
output io.Writer // nil means stderr; use out() accessor
|
||||
}
|
||||
|
||||
// A Flag represents the state of a flag.
|
||||
type Flag struct {
|
||||
Name string // name as it appears on command line
|
||||
Usage string // help message
|
||||
Value Value // value as set
|
||||
DefValue string // default value (as text); for usage message
|
||||
}
|
||||
|
||||
// sortFlags returns the flags as a slice in lexicographical sorted order.
|
||||
func sortFlags(flags map[string]*Flag) []*Flag {
|
||||
list := make(sort.StringSlice, len(flags))
|
||||
i := 0
|
||||
for _, f := range flags {
|
||||
list[i] = f.Name
|
||||
i++
|
||||
}
|
||||
list.Sort()
|
||||
result := make([]*Flag, len(list))
|
||||
for i, name := range list {
|
||||
result[i] = flags[name]
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func (f *FlagSet) out() io.Writer {
|
||||
if f.output == nil {
|
||||
return os.Stderr
|
||||
}
|
||||
return f.output
|
||||
}
|
||||
|
||||
// SetOutput sets the destination for usage and error messages.
|
||||
// If output is nil, os.Stderr is used.
|
||||
func (f *FlagSet) SetOutput(output io.Writer) {
|
||||
f.output = output
|
||||
}
|
||||
|
||||
// VisitAll visits the flags in lexicographical order, calling fn for each.
|
||||
// It visits all flags, even those not set.
|
||||
func (f *FlagSet) VisitAll(fn func(*Flag)) {
|
||||
for _, flag := range sortFlags(f.formal) {
|
||||
fn(flag)
|
||||
}
|
||||
}
|
||||
|
||||
// VisitAll visits the command-line flags in lexicographical order, calling
|
||||
// fn for each. It visits all flags, even those not set.
|
||||
func VisitAll(fn func(*Flag)) {
|
||||
commandLine.VisitAll(fn)
|
||||
}
|
||||
|
||||
// Visit visits the flags in lexicographical order, calling fn for each.
|
||||
// It visits only those flags that have been set.
|
||||
func (f *FlagSet) Visit(fn func(*Flag)) {
|
||||
for _, flag := range sortFlags(f.actual) {
|
||||
fn(flag)
|
||||
}
|
||||
}
|
||||
|
||||
// Visit visits the command-line flags in lexicographical order, calling fn
|
||||
// for each. It visits only those flags that have been set.
|
||||
func Visit(fn func(*Flag)) {
|
||||
commandLine.Visit(fn)
|
||||
}
|
||||
|
||||
// Lookup returns the Flag structure of the named flag, returning nil if none exists.
|
||||
func (f *FlagSet) Lookup(name string) *Flag {
|
||||
return f.formal[name]
|
||||
}
|
||||
|
||||
// Lookup returns the Flag structure of the named command-line flag,
|
||||
// returning nil if none exists.
|
||||
func Lookup(name string) *Flag {
|
||||
return commandLine.formal[name]
|
||||
}
|
||||
|
||||
// Set sets the value of the named flag.
|
||||
func (f *FlagSet) Set(name, value string) error {
|
||||
flag, ok := f.formal[name]
|
||||
if !ok {
|
||||
return fmt.Errorf("no such flag -%v", name)
|
||||
}
|
||||
err := flag.Value.Set(value)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if f.actual == nil {
|
||||
f.actual = make(map[string]*Flag)
|
||||
}
|
||||
f.actual[name] = flag
|
||||
return nil
|
||||
}
|
||||
|
||||
// Set sets the value of the named command-line flag.
|
||||
func Set(name, value string) error {
|
||||
return commandLine.Set(name, value)
|
||||
}
|
||||
|
||||
// flagsByLength is a slice of flags implementing sort.Interface,
|
||||
// sorting primarily by the length of the flag, and secondarily
|
||||
// alphabetically.
|
||||
type flagsByLength []*Flag
|
||||
|
||||
func (f flagsByLength) Less(i, j int) bool {
|
||||
s1, s2 := f[i].Name, f[j].Name
|
||||
if len(s1) != len(s2) {
|
||||
return len(s1) < len(s2)
|
||||
}
|
||||
return s1 < s2
|
||||
}
|
||||
func (f flagsByLength) Swap(i, j int) {
|
||||
f[i], f[j] = f[j], f[i]
|
||||
}
|
||||
func (f flagsByLength) Len() int {
|
||||
return len(f)
|
||||
}
|
||||
|
||||
// flagsByName is a slice of slices of flags implementing sort.Interface,
|
||||
// alphabetically sorting by the name of the first flag in each slice.
|
||||
type flagsByName [][]*Flag
|
||||
|
||||
func (f flagsByName) Less(i, j int) bool {
|
||||
return f[i][0].Name < f[j][0].Name
|
||||
}
|
||||
func (f flagsByName) Swap(i, j int) {
|
||||
f[i], f[j] = f[j], f[i]
|
||||
}
|
||||
func (f flagsByName) Len() int {
|
||||
return len(f)
|
||||
}
|
||||
|
||||
// PrintDefaults prints, to standard error unless configured
|
||||
// otherwise, the default values of all defined flags in the set.
|
||||
// If there is more than one name for a given flag, the usage information and
|
||||
// default value from the shortest will be printed (or the least alphabetically
|
||||
// if there are several equally short flag names).
|
||||
func (f *FlagSet) PrintDefaults() {
|
||||
// group together all flags for a given value
|
||||
flags := make(map[interface{}]flagsByLength)
|
||||
f.VisitAll(func(f *Flag) {
|
||||
flags[f.Value] = append(flags[f.Value], f)
|
||||
})
|
||||
|
||||
// sort the output flags by shortest name for each group.
|
||||
var byName flagsByName
|
||||
for _, f := range flags {
|
||||
sort.Sort(f)
|
||||
byName = append(byName, f)
|
||||
}
|
||||
sort.Sort(byName)
|
||||
|
||||
var line bytes.Buffer
|
||||
for _, fs := range byName {
|
||||
line.Reset()
|
||||
for i, f := range fs {
|
||||
if i > 0 {
|
||||
line.WriteString(", ")
|
||||
}
|
||||
line.WriteString(flagWithMinus(f.Name))
|
||||
}
|
||||
format := " %s (= %s)\n %s\n"
|
||||
if _, ok := fs[0].Value.(*stringValue); ok {
|
||||
// put quotes on the value
|
||||
format = " %s (= %q)\n %s\n"
|
||||
}
|
||||
fmt.Fprintf(f.out(), format, line.Bytes(), fs[0].DefValue, fs[0].Usage)
|
||||
}
|
||||
}
|
||||
|
||||
// PrintDefaults prints to standard error the default values of all defined command-line flags.
|
||||
func PrintDefaults() {
|
||||
commandLine.PrintDefaults()
|
||||
}
|
||||
|
||||
// defaultUsage is the default function to print a usage message.
|
||||
func defaultUsage(f *FlagSet) {
|
||||
fmt.Fprintf(f.out(), "Usage of %s:\n", f.name)
|
||||
f.PrintDefaults()
|
||||
}
|
||||
|
||||
// NOTE: Usage is not just defaultUsage(commandLine)
|
||||
// because it serves (via godoc flag Usage) as the example
|
||||
// for how to write your own usage function.
|
||||
|
||||
// Usage prints to standard error a usage message documenting all defined command-line flags.
|
||||
// The function is a variable that may be changed to point to a custom function.
|
||||
var Usage = func() {
|
||||
fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
|
||||
PrintDefaults()
|
||||
}
|
||||
|
||||
// NFlag returns the number of flags that have been set.
|
||||
func (f *FlagSet) NFlag() int { return len(f.actual) }
|
||||
|
||||
// NFlag returns the number of command-line flags that have been set.
|
||||
func NFlag() int { return len(commandLine.actual) }
|
||||
|
||||
// Arg returns the i'th argument. Arg(0) is the first remaining argument
|
||||
// after flags have been processed.
|
||||
func (f *FlagSet) Arg(i int) string {
|
||||
if i < 0 || i >= len(f.args) {
|
||||
return ""
|
||||
}
|
||||
return f.args[i]
|
||||
}
|
||||
|
||||
// Arg returns the i'th command-line argument. Arg(0) is the first remaining argument
|
||||
// after flags have been processed.
|
||||
func Arg(i int) string {
|
||||
return commandLine.Arg(i)
|
||||
}
|
||||
|
||||
// NArg is the number of arguments remaining after flags have been processed.
|
||||
func (f *FlagSet) NArg() int { return len(f.args) }
|
||||
|
||||
// NArg is the number of arguments remaining after flags have been processed.
|
||||
func NArg() int { return len(commandLine.args) }
|
||||
|
||||
// Args returns the non-flag arguments.
|
||||
func (f *FlagSet) Args() []string { return f.args }
|
||||
|
||||
// Args returns the non-flag command-line arguments.
|
||||
func Args() []string { return commandLine.args }
|
||||
|
||||
// BoolVar defines a bool flag with specified name, default value, and usage string.
|
||||
// The argument p points to a bool variable in which to store the value of the flag.
|
||||
func (f *FlagSet) BoolVar(p *bool, name string, value bool, usage string) {
|
||||
f.Var(newBoolValue(value, p), name, usage)
|
||||
}
|
||||
|
||||
// BoolVar defines a bool flag with specified name, default value, and usage string.
|
||||
// The argument p points to a bool variable in which to store the value of the flag.
|
||||
func BoolVar(p *bool, name string, value bool, usage string) {
|
||||
commandLine.Var(newBoolValue(value, p), name, usage)
|
||||
}
|
||||
|
||||
// Bool defines a bool flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a bool variable that stores the value of the flag.
|
||||
func (f *FlagSet) Bool(name string, value bool, usage string) *bool {
|
||||
p := new(bool)
|
||||
f.BoolVar(p, name, value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Bool defines a bool flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a bool variable that stores the value of the flag.
|
||||
func Bool(name string, value bool, usage string) *bool {
|
||||
return commandLine.Bool(name, value, usage)
|
||||
}
|
||||
|
||||
// IntVar defines an int flag with specified name, default value, and usage string.
|
||||
// The argument p points to an int variable in which to store the value of the flag.
|
||||
func (f *FlagSet) IntVar(p *int, name string, value int, usage string) {
|
||||
f.Var(newIntValue(value, p), name, usage)
|
||||
}
|
||||
|
||||
// IntVar defines an int flag with specified name, default value, and usage string.
|
||||
// The argument p points to an int variable in which to store the value of the flag.
|
||||
func IntVar(p *int, name string, value int, usage string) {
|
||||
commandLine.Var(newIntValue(value, p), name, usage)
|
||||
}
|
||||
|
||||
// Int defines an int flag with specified name, default value, and usage string.
|
||||
// The return value is the address of an int variable that stores the value of the flag.
|
||||
func (f *FlagSet) Int(name string, value int, usage string) *int {
|
||||
p := new(int)
|
||||
f.IntVar(p, name, value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Int defines an int flag with specified name, default value, and usage string.
|
||||
// The return value is the address of an int variable that stores the value of the flag.
|
||||
func Int(name string, value int, usage string) *int {
|
||||
return commandLine.Int(name, value, usage)
|
||||
}
|
||||
|
||||
// Int64Var defines an int64 flag with specified name, default value, and usage string.
|
||||
// The argument p points to an int64 variable in which to store the value of the flag.
|
||||
func (f *FlagSet) Int64Var(p *int64, name string, value int64, usage string) {
|
||||
f.Var(newInt64Value(value, p), name, usage)
|
||||
}
|
||||
|
||||
// Int64Var defines an int64 flag with specified name, default value, and usage string.
|
||||
// The argument p points to an int64 variable in which to store the value of the flag.
|
||||
func Int64Var(p *int64, name string, value int64, usage string) {
|
||||
commandLine.Var(newInt64Value(value, p), name, usage)
|
||||
}
|
||||
|
||||
// Int64 defines an int64 flag with specified name, default value, and usage string.
|
||||
// The return value is the address of an int64 variable that stores the value of the flag.
|
||||
func (f *FlagSet) Int64(name string, value int64, usage string) *int64 {
|
||||
p := new(int64)
|
||||
f.Int64Var(p, name, value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Int64 defines an int64 flag with specified name, default value, and usage string.
|
||||
// The return value is the address of an int64 variable that stores the value of the flag.
|
||||
func Int64(name string, value int64, usage string) *int64 {
|
||||
return commandLine.Int64(name, value, usage)
|
||||
}
|
||||
|
||||
// UintVar defines a uint flag with specified name, default value, and usage string.
|
||||
// The argument p points to a uint variable in which to store the value of the flag.
|
||||
func (f *FlagSet) UintVar(p *uint, name string, value uint, usage string) {
|
||||
f.Var(newUintValue(value, p), name, usage)
|
||||
}
|
||||
|
||||
// UintVar defines a uint flag with specified name, default value, and usage string.
|
||||
// The argument p points to a uint variable in which to store the value of the flag.
|
||||
func UintVar(p *uint, name string, value uint, usage string) {
|
||||
commandLine.Var(newUintValue(value, p), name, usage)
|
||||
}
|
||||
|
||||
// Uint defines a uint flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a uint variable that stores the value of the flag.
|
||||
func (f *FlagSet) Uint(name string, value uint, usage string) *uint {
|
||||
p := new(uint)
|
||||
f.UintVar(p, name, value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Uint defines a uint flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a uint variable that stores the value of the flag.
|
||||
func Uint(name string, value uint, usage string) *uint {
|
||||
return commandLine.Uint(name, value, usage)
|
||||
}
|
||||
|
||||
// Uint64Var defines a uint64 flag with specified name, default value, and usage string.
|
||||
// The argument p points to a uint64 variable in which to store the value of the flag.
|
||||
func (f *FlagSet) Uint64Var(p *uint64, name string, value uint64, usage string) {
|
||||
f.Var(newUint64Value(value, p), name, usage)
|
||||
}
|
||||
|
||||
// Uint64Var defines a uint64 flag with specified name, default value, and usage string.
|
||||
// The argument p points to a uint64 variable in which to store the value of the flag.
|
||||
func Uint64Var(p *uint64, name string, value uint64, usage string) {
|
||||
commandLine.Var(newUint64Value(value, p), name, usage)
|
||||
}
|
||||
|
||||
// Uint64 defines a uint64 flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a uint64 variable that stores the value of the flag.
|
||||
func (f *FlagSet) Uint64(name string, value uint64, usage string) *uint64 {
|
||||
p := new(uint64)
|
||||
f.Uint64Var(p, name, value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Uint64 defines a uint64 flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a uint64 variable that stores the value of the flag.
|
||||
func Uint64(name string, value uint64, usage string) *uint64 {
|
||||
return commandLine.Uint64(name, value, usage)
|
||||
}
|
||||
|
||||
// StringVar defines a string flag with specified name, default value, and usage string.
|
||||
// The argument p points to a string variable in which to store the value of the flag.
|
||||
func (f *FlagSet) StringVar(p *string, name string, value string, usage string) {
|
||||
f.Var(newStringValue(value, p), name, usage)
|
||||
}
|
||||
|
||||
// StringVar defines a string flag with specified name, default value, and usage string.
|
||||
// The argument p points to a string variable in which to store the value of the flag.
|
||||
func StringVar(p *string, name string, value string, usage string) {
|
||||
commandLine.Var(newStringValue(value, p), name, usage)
|
||||
}
|
||||
|
||||
// String defines a string flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a string variable that stores the value of the flag.
|
||||
func (f *FlagSet) String(name string, value string, usage string) *string {
|
||||
p := new(string)
|
||||
f.StringVar(p, name, value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// String defines a string flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a string variable that stores the value of the flag.
|
||||
func String(name string, value string, usage string) *string {
|
||||
return commandLine.String(name, value, usage)
|
||||
}
|
||||
|
||||
// Float64Var defines a float64 flag with specified name, default value, and usage string.
|
||||
// The argument p points to a float64 variable in which to store the value of the flag.
|
||||
func (f *FlagSet) Float64Var(p *float64, name string, value float64, usage string) {
|
||||
f.Var(newFloat64Value(value, p), name, usage)
|
||||
}
|
||||
|
||||
// Float64Var defines a float64 flag with specified name, default value, and usage string.
|
||||
// The argument p points to a float64 variable in which to store the value of the flag.
|
||||
func Float64Var(p *float64, name string, value float64, usage string) {
|
||||
commandLine.Var(newFloat64Value(value, p), name, usage)
|
||||
}
|
||||
|
||||
// Float64 defines a float64 flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a float64 variable that stores the value of the flag.
|
||||
func (f *FlagSet) Float64(name string, value float64, usage string) *float64 {
|
||||
p := new(float64)
|
||||
f.Float64Var(p, name, value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Float64 defines a float64 flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a float64 variable that stores the value of the flag.
|
||||
func Float64(name string, value float64, usage string) *float64 {
|
||||
return commandLine.Float64(name, value, usage)
|
||||
}
|
||||
|
||||
// DurationVar defines a time.Duration flag with specified name, default value, and usage string.
|
||||
// The argument p points to a time.Duration variable in which to store the value of the flag.
|
||||
func (f *FlagSet) DurationVar(p *time.Duration, name string, value time.Duration, usage string) {
|
||||
f.Var(newDurationValue(value, p), name, usage)
|
||||
}
|
||||
|
||||
// DurationVar defines a time.Duration flag with specified name, default value, and usage string.
|
||||
// The argument p points to a time.Duration variable in which to store the value of the flag.
|
||||
func DurationVar(p *time.Duration, name string, value time.Duration, usage string) {
|
||||
commandLine.Var(newDurationValue(value, p), name, usage)
|
||||
}
|
||||
|
||||
// Duration defines a time.Duration flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a time.Duration variable that stores the value of the flag.
|
||||
func (f *FlagSet) Duration(name string, value time.Duration, usage string) *time.Duration {
|
||||
p := new(time.Duration)
|
||||
f.DurationVar(p, name, value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Duration defines a time.Duration flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a time.Duration variable that stores the value of the flag.
|
||||
func Duration(name string, value time.Duration, usage string) *time.Duration {
|
||||
return commandLine.Duration(name, value, usage)
|
||||
}
|
||||
|
||||
// Var defines a flag with the specified name and usage string. The type and
|
||||
// value of the flag are represented by the first argument, of type Value, which
|
||||
// typically holds a user-defined implementation of Value. For instance, the
|
||||
// caller could create a flag that turns a comma-separated string into a slice
|
||||
// of strings by giving the slice the methods of Value; in particular, Set would
|
||||
// decompose the comma-separated string into the slice.
|
||||
func (f *FlagSet) Var(value Value, name string, usage string) {
|
||||
// Remember the default value as a string; it won't change.
|
||||
flag := &Flag{name, usage, value, value.String()}
|
||||
_, alreadythere := f.formal[name]
|
||||
if alreadythere {
|
||||
fmt.Fprintf(f.out(), "%s flag redefined: %s\n", f.name, name)
|
||||
panic("flag redefinition") // Happens only if flags are declared with identical names
|
||||
}
|
||||
if f.formal == nil {
|
||||
f.formal = make(map[string]*Flag)
|
||||
}
|
||||
f.formal[name] = flag
|
||||
}
|
||||
|
||||
// Var defines a flag with the specified name and usage string. The type and
|
||||
// value of the flag are represented by the first argument, of type Value, which
|
||||
// typically holds a user-defined implementation of Value. For instance, the
|
||||
// caller could create a flag that turns a comma-separated string into a slice
|
||||
// of strings by giving the slice the methods of Value; in particular, Set would
|
||||
// decompose the comma-separated string into the slice.
|
||||
func Var(value Value, name string, usage string) {
|
||||
commandLine.Var(value, name, usage)
|
||||
}
|
||||
|
||||
// failf prints to standard error a formatted error and usage message and
|
||||
// returns the error.
|
||||
func (f *FlagSet) failf(format string, a ...interface{}) error {
|
||||
err := fmt.Errorf(format, a...)
|
||||
fmt.Fprintf(f.out(), "error: %v\n", err)
|
||||
return err
|
||||
}
|
||||
|
||||
// usage calls the Usage method for the flag set, or the usage function if
|
||||
// the flag set is commandLine.
|
||||
func (f *FlagSet) usage() {
|
||||
if f == commandLine {
|
||||
Usage()
|
||||
} else if f.Usage == nil {
|
||||
defaultUsage(f)
|
||||
} else {
|
||||
f.Usage()
|
||||
}
|
||||
}
|
||||
|
||||
func (f *FlagSet) parseOneGnu() (flagName string, long, finished bool, err error) {
|
||||
if len(f.procArgs) == 0 {
|
||||
finished = true
|
||||
return
|
||||
}
|
||||
|
||||
// processing previously encountered single-rune flag
|
||||
if flag := f.procFlag; len(flag) > 0 {
|
||||
_, n := utf8.DecodeRuneInString(flag)
|
||||
f.procFlag = flag[n:]
|
||||
flagName = flag[0:n]
|
||||
return
|
||||
}
|
||||
|
||||
a := f.procArgs[0]
|
||||
|
||||
// one non-flag argument
|
||||
if a == "-" || a == "" || a[0] != '-' {
|
||||
if f.allowIntersperse {
|
||||
f.args = append(f.args, a)
|
||||
f.procArgs = f.procArgs[1:]
|
||||
return
|
||||
}
|
||||
f.args = append(f.args, f.procArgs...)
|
||||
f.procArgs = nil
|
||||
finished = true
|
||||
return
|
||||
}
|
||||
|
||||
// end of flags
|
||||
if f.procArgs[0] == "--" {
|
||||
f.args = append(f.args, f.procArgs[1:]...)
|
||||
f.procArgs = nil
|
||||
finished = true
|
||||
return
|
||||
}
|
||||
|
||||
// long flag signified with "--" prefix
|
||||
if a[1] == '-' {
|
||||
long = true
|
||||
i := strings.Index(a, "=")
|
||||
if i < 0 {
|
||||
f.procArgs = f.procArgs[1:]
|
||||
flagName = a[2:]
|
||||
return
|
||||
}
|
||||
flagName = a[2:i]
|
||||
if flagName == "" {
|
||||
err = fmt.Errorf("empty flag in argument %q", a)
|
||||
return
|
||||
}
|
||||
f.procArgs = f.procArgs[1:]
|
||||
f.procFlag = a[i:]
|
||||
return
|
||||
}
|
||||
|
||||
// some number of single-rune flags
|
||||
a = a[1:]
|
||||
_, n := utf8.DecodeRuneInString(a)
|
||||
flagName = a[0:n]
|
||||
f.procFlag = a[n:]
|
||||
f.procArgs = f.procArgs[1:]
|
||||
return
|
||||
}
|
||||
|
||||
func flagWithMinus(name string) string {
|
||||
if len(name) > 1 {
|
||||
return "--" + name
|
||||
}
|
||||
return "-" + name
|
||||
}
|
||||
|
||||
func (f *FlagSet) parseGnuFlagArg(name string, long bool) (finished bool, err error) {
|
||||
m := f.formal
|
||||
flag, alreadythere := m[name] // BUG
|
||||
if !alreadythere {
|
||||
if name == "help" || name == "h" { // special case for nice help message.
|
||||
f.usage()
|
||||
return false, ErrHelp
|
||||
}
|
||||
// TODO print --xxx when flag is more than one rune.
|
||||
return false, f.failf("flag provided but not defined: %s", flagWithMinus(name))
|
||||
}
|
||||
if fv, ok := flag.Value.(*boolValue); ok && !strings.HasPrefix(f.procFlag, "=") {
|
||||
// special case: doesn't need an arg, and an arg hasn't
|
||||
// been provided explicitly.
|
||||
fv.Set("true")
|
||||
} else {
|
||||
// It must have a value, which might be the next argument.
|
||||
var hasValue bool
|
||||
var value string
|
||||
if f.procFlag != "" {
|
||||
// value directly follows flag
|
||||
value = f.procFlag
|
||||
if long {
|
||||
if value[0] != '=' {
|
||||
panic("no leading '=' in long flag")
|
||||
}
|
||||
value = value[1:]
|
||||
}
|
||||
hasValue = true
|
||||
f.procFlag = ""
|
||||
}
|
||||
if !hasValue && len(f.procArgs) > 0 {
|
||||
// value is the next arg
|
||||
hasValue = true
|
||||
value, f.procArgs = f.procArgs[0], f.procArgs[1:]
|
||||
}
|
||||
if !hasValue {
|
||||
return false, f.failf("flag needs an argument: %s", flagWithMinus(name))
|
||||
}
|
||||
if err := flag.Value.Set(value); err != nil {
|
||||
return false, f.failf("invalid value %q for flag %s: %v", value, flagWithMinus(name), err)
|
||||
}
|
||||
}
|
||||
if f.actual == nil {
|
||||
f.actual = make(map[string]*Flag)
|
||||
}
|
||||
f.actual[name] = flag
|
||||
return
|
||||
}
|
||||
|
||||
// Parse parses flag definitions from the argument list, which should not
|
||||
// include the command name. Must be called after all flags in the FlagSet
|
||||
// are defined and before flags are accessed by the program.
|
||||
// The return value will be ErrHelp if --help was set but not defined.
|
||||
// If allowIntersperse is set, arguments and flags can be interspersed, that
|
||||
// is flags can follow positional arguments.
|
||||
func (f *FlagSet) Parse(allowIntersperse bool, arguments []string) error {
|
||||
f.parsed = true
|
||||
f.procArgs = arguments
|
||||
f.procFlag = ""
|
||||
f.args = nil
|
||||
f.allowIntersperse = allowIntersperse
|
||||
for {
|
||||
name, long, finished, err := f.parseOneGnu()
|
||||
if !finished {
|
||||
if name != "" {
|
||||
finished, err = f.parseGnuFlagArg(name, long)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
switch f.errorHandling {
|
||||
case ContinueOnError:
|
||||
return err
|
||||
case ExitOnError:
|
||||
os.Exit(2)
|
||||
case PanicOnError:
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
if !finished {
|
||||
continue
|
||||
}
|
||||
if err == nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Parsed reports whether f.Parse has been called.
|
||||
func (f *FlagSet) Parsed() bool {
|
||||
return f.parsed
|
||||
}
|
||||
|
||||
// Parse parses the command-line flags from os.Args[1:]. Must be called
|
||||
// after all flags are defined and before flags are accessed by the program.
|
||||
// If allowIntersperse is set, arguments and flags can be interspersed, that
|
||||
// is flags can follow positional arguments.
|
||||
func Parse(allowIntersperse bool) {
|
||||
// Ignore errors; commandLine is set for ExitOnError.
|
||||
commandLine.Parse(allowIntersperse, os.Args[1:])
|
||||
}
|
||||
|
||||
// Parsed returns true if the command-line flags have been parsed.
|
||||
func Parsed() bool {
|
||||
return commandLine.Parsed()
|
||||
}
|
||||
|
||||
// The default set of command-line flags, parsed from os.Args.
|
||||
var commandLine = NewFlagSet(os.Args[0], ExitOnError)
|
||||
|
||||
// NewFlagSet returns a new, empty flag set with the specified name and
|
||||
// error handling property.
|
||||
func NewFlagSet(name string, errorHandling ErrorHandling) *FlagSet {
|
||||
f := &FlagSet{
|
||||
name: name,
|
||||
errorHandling: errorHandling,
|
||||
}
|
||||
return f
|
||||
}
|
||||
|
||||
// Init sets the name and error handling property for a flag set.
|
||||
// By default, the zero FlagSet uses an empty name and the
|
||||
// ContinueOnError error handling policy.
|
||||
func (f *FlagSet) Init(name string, errorHandling ErrorHandling) {
|
||||
f.name = name
|
||||
f.errorHandling = errorHandling
|
||||
}
|
||||
549
internal/gnuflag/flag_test.go
Normal file
549
internal/gnuflag/flag_test.go
Normal file
@@ -0,0 +1,549 @@
|
||||
// Copyright 2009 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package gnuflag_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
. "launchpad.net/gnuflag"
|
||||
"os"
|
||||
"reflect"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
test_bool = Bool("test_bool", false, "bool value")
|
||||
test_int = Int("test_int", 0, "int value")
|
||||
test_int64 = Int64("test_int64", 0, "int64 value")
|
||||
test_uint = Uint("test_uint", 0, "uint value")
|
||||
test_uint64 = Uint64("test_uint64", 0, "uint64 value")
|
||||
test_string = String("test_string", "0", "string value")
|
||||
test_float64 = Float64("test_float64", 0, "float64 value")
|
||||
test_duration = Duration("test_duration", 0, "time.Duration value")
|
||||
)
|
||||
|
||||
func boolString(s string) string {
|
||||
if s == "0" {
|
||||
return "false"
|
||||
}
|
||||
return "true"
|
||||
}
|
||||
|
||||
func TestEverything(t *testing.T) {
|
||||
m := make(map[string]*Flag)
|
||||
desired := "0"
|
||||
visitor := func(f *Flag) {
|
||||
if len(f.Name) > 5 && f.Name[0:5] == "test_" {
|
||||
m[f.Name] = f
|
||||
ok := false
|
||||
switch {
|
||||
case f.Value.String() == desired:
|
||||
ok = true
|
||||
case f.Name == "test_bool" && f.Value.String() == boolString(desired):
|
||||
ok = true
|
||||
case f.Name == "test_duration" && f.Value.String() == desired+"s":
|
||||
ok = true
|
||||
}
|
||||
if !ok {
|
||||
t.Error("Visit: bad value", f.Value.String(), "for", f.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
VisitAll(visitor)
|
||||
if len(m) != 8 {
|
||||
t.Error("VisitAll misses some flags")
|
||||
for k, v := range m {
|
||||
t.Log(k, *v)
|
||||
}
|
||||
}
|
||||
m = make(map[string]*Flag)
|
||||
Visit(visitor)
|
||||
if len(m) != 0 {
|
||||
t.Errorf("Visit sees unset flags")
|
||||
for k, v := range m {
|
||||
t.Log(k, *v)
|
||||
}
|
||||
}
|
||||
// Now set all flags
|
||||
Set("test_bool", "true")
|
||||
Set("test_int", "1")
|
||||
Set("test_int64", "1")
|
||||
Set("test_uint", "1")
|
||||
Set("test_uint64", "1")
|
||||
Set("test_string", "1")
|
||||
Set("test_float64", "1")
|
||||
Set("test_duration", "1s")
|
||||
desired = "1"
|
||||
Visit(visitor)
|
||||
if len(m) != 8 {
|
||||
t.Error("Visit fails after set")
|
||||
for k, v := range m {
|
||||
t.Log(k, *v)
|
||||
}
|
||||
}
|
||||
// Now test they're visited in sort order.
|
||||
var flagNames []string
|
||||
Visit(func(f *Flag) { flagNames = append(flagNames, f.Name) })
|
||||
if !sort.StringsAreSorted(flagNames) {
|
||||
t.Errorf("flag names not sorted: %v", flagNames)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUsage(t *testing.T) {
|
||||
called := false
|
||||
ResetForTesting(func() { called = true })
|
||||
f := CommandLine()
|
||||
f.SetOutput(nullWriter{})
|
||||
if f.Parse(true, []string{"-x"}) == nil {
|
||||
t.Error("parse did not fail for unknown flag")
|
||||
}
|
||||
if !called {
|
||||
t.Error("did not call Usage for unknown flag")
|
||||
}
|
||||
}
|
||||
|
||||
var parseTests = []struct {
|
||||
about string
|
||||
intersperse bool
|
||||
args []string
|
||||
vals map[string]interface{}
|
||||
remaining []string
|
||||
error string
|
||||
}{{
|
||||
about: "regular args",
|
||||
intersperse: true,
|
||||
args: []string{
|
||||
"--bool2",
|
||||
"--int", "22",
|
||||
"--int64", "0x23",
|
||||
"--uint", "24",
|
||||
"--uint64", "25",
|
||||
"--string", "hello",
|
||||
"--float64", "2718e28",
|
||||
"--duration", "2m",
|
||||
"one - extra - argument",
|
||||
},
|
||||
vals: map[string]interface{}{
|
||||
"bool": false,
|
||||
"bool2": true,
|
||||
"int": 22,
|
||||
"int64": int64(0x23),
|
||||
"uint": uint(24),
|
||||
"uint64": uint64(25),
|
||||
"string": "hello",
|
||||
"float64": 2718e28,
|
||||
"duration": 2 * 60 * time.Second,
|
||||
},
|
||||
remaining: []string{
|
||||
"one - extra - argument",
|
||||
},
|
||||
}, {
|
||||
about: "playing with -",
|
||||
intersperse: true,
|
||||
args: []string{
|
||||
"-a",
|
||||
"-",
|
||||
"-bc",
|
||||
"2",
|
||||
"-de1s",
|
||||
"-f2s",
|
||||
"-g", "3s",
|
||||
"--h",
|
||||
"--long",
|
||||
"--long2", "-4s",
|
||||
"3",
|
||||
"4",
|
||||
"--", "-5",
|
||||
},
|
||||
vals: map[string]interface{}{
|
||||
"a": true,
|
||||
"b": true,
|
||||
"c": true,
|
||||
"d": true,
|
||||
"e": "1s",
|
||||
"f": "2s",
|
||||
"g": "3s",
|
||||
"h": true,
|
||||
"long": true,
|
||||
"long2": "-4s",
|
||||
"z": "default",
|
||||
"www": 99,
|
||||
},
|
||||
remaining: []string{
|
||||
"-",
|
||||
"2",
|
||||
"3",
|
||||
"4",
|
||||
"-5",
|
||||
},
|
||||
}, {
|
||||
about: "flag after explicit --",
|
||||
intersperse: true,
|
||||
args: []string{
|
||||
"-a",
|
||||
"--",
|
||||
"-b",
|
||||
},
|
||||
vals: map[string]interface{}{
|
||||
"a": true,
|
||||
"b": false,
|
||||
},
|
||||
remaining: []string{
|
||||
"-b",
|
||||
},
|
||||
}, {
|
||||
about: "flag after end",
|
||||
args: []string{
|
||||
"-a",
|
||||
"foo",
|
||||
"-b",
|
||||
},
|
||||
vals: map[string]interface{}{
|
||||
"a": true,
|
||||
"b": false,
|
||||
},
|
||||
remaining: []string{
|
||||
"foo",
|
||||
"-b",
|
||||
},
|
||||
}, {
|
||||
about: "arg and flag after explicit end",
|
||||
args: []string{
|
||||
"-a",
|
||||
"--",
|
||||
"foo",
|
||||
"-b",
|
||||
},
|
||||
vals: map[string]interface{}{
|
||||
"a": true,
|
||||
"b": false,
|
||||
},
|
||||
remaining: []string{
|
||||
"foo",
|
||||
"-b",
|
||||
},
|
||||
}, {
|
||||
about: "boolean args, explicitly and non-explicitly given",
|
||||
args: []string{
|
||||
"--a=false",
|
||||
"--b=true",
|
||||
"--c",
|
||||
},
|
||||
vals: map[string]interface{}{
|
||||
"a": false,
|
||||
"b": true,
|
||||
"c": true,
|
||||
},
|
||||
}, {
|
||||
about: "using =",
|
||||
args: []string{
|
||||
"--arble=bar",
|
||||
"--bletch=",
|
||||
"--a=something",
|
||||
"-b=other",
|
||||
"-cdand more",
|
||||
"--curdle=--milk",
|
||||
"--sandwich", "=",
|
||||
"--darn=",
|
||||
"=arg",
|
||||
},
|
||||
vals: map[string]interface{}{
|
||||
"arble": "bar",
|
||||
"bletch": "",
|
||||
"a": "something",
|
||||
"b": "=other",
|
||||
"c": true,
|
||||
"d": "and more",
|
||||
"curdle": "--milk",
|
||||
"sandwich": "=",
|
||||
"darn": "",
|
||||
},
|
||||
remaining: []string{"=arg"},
|
||||
}, {
|
||||
about: "empty flag #1",
|
||||
args: []string{
|
||||
"--=bar",
|
||||
},
|
||||
error: `empty flag in argument "--=bar"`,
|
||||
}, {
|
||||
about: "single-letter equals",
|
||||
args: []string{
|
||||
"-=bar",
|
||||
},
|
||||
error: `flag provided but not defined: -=`,
|
||||
}, {
|
||||
about: "empty flag #2",
|
||||
args: []string{
|
||||
"--=",
|
||||
},
|
||||
error: `empty flag in argument "--="`,
|
||||
}, {
|
||||
about: "no equals",
|
||||
args: []string{
|
||||
"-=",
|
||||
},
|
||||
error: `flag provided but not defined: -=`,
|
||||
}, {
|
||||
args: []string{
|
||||
"-a=true",
|
||||
},
|
||||
vals: map[string]interface{}{
|
||||
"a": true,
|
||||
},
|
||||
error: `invalid value "=true" for flag -a: strconv.ParseBool: parsing "=true": invalid syntax`,
|
||||
}, {
|
||||
intersperse: true,
|
||||
args: []string{
|
||||
"-a",
|
||||
"-b",
|
||||
},
|
||||
vals: map[string]interface{}{
|
||||
"a": true,
|
||||
},
|
||||
error: "flag provided but not defined: -b",
|
||||
}, {
|
||||
intersperse: true,
|
||||
args: []string{
|
||||
"-a",
|
||||
},
|
||||
vals: map[string]interface{}{
|
||||
"a": "default",
|
||||
},
|
||||
error: "flag needs an argument: -a",
|
||||
}, {
|
||||
intersperse: true,
|
||||
args: []string{
|
||||
"-a", "b",
|
||||
},
|
||||
vals: map[string]interface{}{
|
||||
"a": 0,
|
||||
},
|
||||
error: `invalid value "b" for flag -a: strconv.ParseInt: parsing "b": invalid syntax`,
|
||||
},
|
||||
}
|
||||
|
||||
func testParse(newFlagSet func() *FlagSet, t *testing.T) {
|
||||
for i, g := range parseTests {
|
||||
t.Logf("test %d. %s", i, g.about)
|
||||
f := newFlagSet()
|
||||
flags := make(map[string]interface{})
|
||||
for name, val := range g.vals {
|
||||
switch val.(type) {
|
||||
case bool:
|
||||
flags[name] = f.Bool(name, false, "bool value "+name)
|
||||
case string:
|
||||
flags[name] = f.String(name, "default", "string value "+name)
|
||||
case int:
|
||||
flags[name] = f.Int(name, 99, "int value "+name)
|
||||
case uint:
|
||||
flags[name] = f.Uint(name, 0, "uint value")
|
||||
case uint64:
|
||||
flags[name] = f.Uint64(name, 0, "uint64 value")
|
||||
case int64:
|
||||
flags[name] = f.Int64(name, 0, "uint64 value")
|
||||
case float64:
|
||||
flags[name] = f.Float64(name, 0, "float64 value")
|
||||
case time.Duration:
|
||||
flags[name] = f.Duration(name, 5*time.Second, "duration value")
|
||||
default:
|
||||
t.Fatalf("unhandled type %T", val)
|
||||
}
|
||||
}
|
||||
err := f.Parse(g.intersperse, g.args)
|
||||
if g.error != "" {
|
||||
if err == nil {
|
||||
t.Errorf("expected error %q got nil", g.error)
|
||||
} else if err.Error() != g.error {
|
||||
t.Errorf("expected error %q got %q", g.error, err.Error())
|
||||
}
|
||||
continue
|
||||
}
|
||||
for name, val := range g.vals {
|
||||
actual := reflect.ValueOf(flags[name]).Elem().Interface()
|
||||
if val != actual {
|
||||
t.Errorf("flag %q, expected %v got %v", name, val, actual)
|
||||
}
|
||||
}
|
||||
if len(f.Args()) != len(g.remaining) {
|
||||
t.Fatalf("remaining args, expected %q got %q", g.remaining, f.Args())
|
||||
}
|
||||
for j, a := range f.Args() {
|
||||
if a != g.remaining[j] {
|
||||
t.Errorf("arg %d, expected %q got %q", j, g.remaining[i], a)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParse(t *testing.T) {
|
||||
testParse(func() *FlagSet {
|
||||
ResetForTesting(func() {})
|
||||
f := CommandLine()
|
||||
f.SetOutput(nullWriter{})
|
||||
return f
|
||||
}, t)
|
||||
}
|
||||
|
||||
func TestFlagSetParse(t *testing.T) {
|
||||
testParse(func() *FlagSet {
|
||||
f := NewFlagSet("test", ContinueOnError)
|
||||
f.SetOutput(nullWriter{})
|
||||
return f
|
||||
}, t)
|
||||
}
|
||||
|
||||
// Declare a user-defined flag type.
|
||||
type flagVar []string
|
||||
|
||||
func (f *flagVar) String() string {
|
||||
return fmt.Sprint([]string(*f))
|
||||
}
|
||||
|
||||
func (f *flagVar) Set(value string) error {
|
||||
*f = append(*f, value)
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestUserDefined(t *testing.T) {
|
||||
var flags FlagSet
|
||||
flags.Init("test", ContinueOnError)
|
||||
var v flagVar
|
||||
flags.Var(&v, "v", "usage")
|
||||
if err := flags.Parse(true, []string{"-v", "1", "-v", "2", "-v3"}); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
if len(v) != 3 {
|
||||
t.Fatal("expected 3 args; got ", len(v))
|
||||
}
|
||||
expect := "[1 2 3]"
|
||||
if v.String() != expect {
|
||||
t.Errorf("expected value %q got %q", expect, v.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetOutput(t *testing.T) {
|
||||
var flags FlagSet
|
||||
var buf bytes.Buffer
|
||||
flags.SetOutput(&buf)
|
||||
flags.Init("test", ContinueOnError)
|
||||
flags.Parse(true, []string{"-unknown"})
|
||||
if out := buf.String(); !strings.Contains(out, "-unknown") {
|
||||
t.Logf("expected output mentioning unknown; got %q", out)
|
||||
}
|
||||
}
|
||||
|
||||
// This tests that one can reset the flags. This still works but not well, and is
|
||||
// superseded by FlagSet.
|
||||
func TestChangingArgs(t *testing.T) {
|
||||
ResetForTesting(func() { t.Fatal("bad parse") })
|
||||
oldArgs := os.Args
|
||||
defer func() { os.Args = oldArgs }()
|
||||
os.Args = []string{"cmd", "--before", "subcmd", "--after", "args"}
|
||||
before := Bool("before", false, "")
|
||||
if err := CommandLine().Parse(false, os.Args[1:]); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cmd := Arg(0)
|
||||
os.Args = Args()
|
||||
after := Bool("after", false, "")
|
||||
Parse(false)
|
||||
args := Args()
|
||||
|
||||
if !*before || cmd != "subcmd" || !*after || len(args) != 1 || args[0] != "args" {
|
||||
t.Fatalf("expected true subcmd true [args] got %v %v %v %v", *before, cmd, *after, args)
|
||||
}
|
||||
}
|
||||
|
||||
// Test that -help invokes the usage message and returns ErrHelp.
|
||||
func TestHelp(t *testing.T) {
|
||||
var helpCalled = false
|
||||
fs := NewFlagSet("help test", ContinueOnError)
|
||||
fs.SetOutput(nullWriter{})
|
||||
fs.Usage = func() { helpCalled = true }
|
||||
var flag bool
|
||||
fs.BoolVar(&flag, "flag", false, "regular flag")
|
||||
// Regular flag invocation should work
|
||||
err := fs.Parse(true, []string{"--flag"})
|
||||
if err != nil {
|
||||
t.Fatal("expected no error; got ", err)
|
||||
}
|
||||
if !flag {
|
||||
t.Error("flag was not set by --flag")
|
||||
}
|
||||
if helpCalled {
|
||||
t.Error("help called for regular flag")
|
||||
helpCalled = false // reset for next test
|
||||
}
|
||||
// Help flag should work as expected.
|
||||
err = fs.Parse(true, []string{"--help"})
|
||||
if err == nil {
|
||||
t.Fatal("error expected")
|
||||
}
|
||||
if err != ErrHelp {
|
||||
t.Fatal("expected ErrHelp; got ", err)
|
||||
}
|
||||
if !helpCalled {
|
||||
t.Fatal("help was not called")
|
||||
}
|
||||
// If we define a help flag, that should override.
|
||||
var help bool
|
||||
fs.BoolVar(&help, "help", false, "help flag")
|
||||
helpCalled = false
|
||||
err = fs.Parse(true, []string{"--help"})
|
||||
if err != nil {
|
||||
t.Fatal("expected no error for defined --help; got ", err)
|
||||
}
|
||||
if helpCalled {
|
||||
t.Fatal("help was called; should not have been for defined help flag")
|
||||
}
|
||||
}
|
||||
|
||||
type nullWriter struct{}
|
||||
|
||||
func (nullWriter) Write(buf []byte) (int, error) {
|
||||
return len(buf), nil
|
||||
}
|
||||
|
||||
func TestPrintDefaults(t *testing.T) {
|
||||
f := NewFlagSet("print test", ContinueOnError)
|
||||
f.SetOutput(nullWriter{})
|
||||
var b bool
|
||||
var c int
|
||||
var d string
|
||||
var e float64
|
||||
f.IntVar(&c, "trapclap", 99, "usage not shown")
|
||||
f.IntVar(&c, "c", 99, "c usage")
|
||||
|
||||
f.BoolVar(&b, "bal", false, "usage not shown")
|
||||
f.BoolVar(&b, "x", false, "usage not shown")
|
||||
f.BoolVar(&b, "b", false, "b usage")
|
||||
f.BoolVar(&b, "balalaika", false, "usage not shown")
|
||||
|
||||
f.StringVar(&d, "d", "d default", "d usage")
|
||||
|
||||
f.Float64Var(&e, "elephant", 3.14, "elephant usage")
|
||||
|
||||
var buf bytes.Buffer
|
||||
f.SetOutput(&buf)
|
||||
f.PrintDefaults()
|
||||
f.SetOutput(nullWriter{})
|
||||
|
||||
expect :=
|
||||
`-b, -x, --bal, --balalaika (= false)
|
||||
b usage
|
||||
-c, --trapclap (= 99)
|
||||
c usage
|
||||
-d (= "d default")
|
||||
d usage
|
||||
--elephant (= 3.14)
|
||||
elephant usage
|
||||
`
|
||||
if buf.String() != expect {
|
||||
t.Errorf("expect %q got %q", expect, buf.String())
|
||||
}
|
||||
}
|
||||
40
log.go
Normal file
40
log.go
Normal file
@@ -0,0 +1,40 @@
|
||||
package lxd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// Logger is implemented by the standard *log.Logger.
|
||||
type Logger interface {
|
||||
Output(calldepth int, s string) error
|
||||
}
|
||||
|
||||
var logger Logger
|
||||
var debug bool
|
||||
|
||||
// SetLogger defines the *log.Logger where log messages are sent to.
|
||||
func SetLogger(l Logger) {
|
||||
logger = l
|
||||
}
|
||||
|
||||
// SetDebug defines whether debugging is enabled or not.
|
||||
func SetDebug(enabled bool) {
|
||||
debug = enabled
|
||||
}
|
||||
|
||||
// Logf sends to the logger registered via SetLogger the string resulting
|
||||
// from running format and args through Sprintf.
|
||||
func Logf(format string, args ...interface{}) {
|
||||
if logger != nil {
|
||||
logger.Output(2, fmt.Sprintf(format, args...))
|
||||
}
|
||||
}
|
||||
|
||||
// Debugf sends to the logger registered via SetLogger the string resulting
|
||||
// from running format and args through Sprintf, but only if debugging was
|
||||
// enabled via SetDebug.
|
||||
func Debugf(format string, args ...interface{}) {
|
||||
if debug && logger != nil {
|
||||
logger.Output(2, fmt.Sprintf(format, args...))
|
||||
}
|
||||
}
|
||||
60
lxc/help.go
Normal file
60
lxc/help.go
Normal file
@@ -0,0 +1,60 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"fmt"
|
||||
"sort"
|
||||
|
||||
"strings"
|
||||
)
|
||||
|
||||
type helpCmd struct{}
|
||||
|
||||
const helpUsage = `
|
||||
lxd help
|
||||
|
||||
Presents details on how to use lxd.
|
||||
`
|
||||
|
||||
func (c *helpCmd) usage() string {
|
||||
return helpUsage
|
||||
}
|
||||
|
||||
func (c *helpCmd) flags() {}
|
||||
|
||||
func (c *helpCmd) run(args []string) error {
|
||||
if len(args) > 0 {
|
||||
return errArgs
|
||||
}
|
||||
|
||||
fmt.Println("Usage: lxd [subcommand] [options]\n")
|
||||
fmt.Println("Available commands:\n")
|
||||
var names []string
|
||||
for name, _ := range commands {
|
||||
names = append(names, name)
|
||||
}
|
||||
sort.Strings(names)
|
||||
for _, name := range names {
|
||||
cmd := commands[name]
|
||||
fmt.Printf("\t%-10s - %s\n", name, summaryLine(cmd.usage()))
|
||||
}
|
||||
fmt.Println()
|
||||
return nil
|
||||
}
|
||||
|
||||
// summaryLine returns the first non-empty line immediately after the first
|
||||
// line. Conventionally, this should be a one-line command summary, potentially
|
||||
// followed by a longer explanation.
|
||||
func summaryLine(usage string) string {
|
||||
usage = strings.TrimSpace(usage)
|
||||
s := bufio.NewScanner(bytes.NewBufferString(usage))
|
||||
if s.Scan() {
|
||||
for s.Scan() {
|
||||
if len(s.Text()) > 1 {
|
||||
return s.Text()
|
||||
}
|
||||
}
|
||||
}
|
||||
return "Missing summary."
|
||||
}
|
||||
63
lxc/main.go
Normal file
63
lxc/main.go
Normal file
@@ -0,0 +1,63 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/lxc/lxd"
|
||||
"github.com/lxc/lxd/internal/gnuflag"
|
||||
)
|
||||
|
||||
func main() {
|
||||
if err := run(); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "error: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
var verbose = gnuflag.Bool("v", false, "Enables verbose mode.")
|
||||
var debug = gnuflag.Bool("debug", false, "Enables debug mode.")
|
||||
|
||||
func run() error {
|
||||
if len(os.Args) == 2 && (os.Args[1] == "-h" || os.Args[1] == "--help") {
|
||||
os.Args[1] = "help"
|
||||
}
|
||||
if len(os.Args) < 2 || os.Args[1] == "" || os.Args[1][0] == '-' {
|
||||
return fmt.Errorf("missing subcommand")
|
||||
}
|
||||
name := os.Args[1]
|
||||
cmd, ok := commands[name]
|
||||
if !ok {
|
||||
return fmt.Errorf("unknown command: %s", name)
|
||||
}
|
||||
cmd.flags()
|
||||
gnuflag.Usage = func() {
|
||||
fmt.Fprintf(os.Stderr, "Usage: %s\n\nOptions:\n\n", strings.TrimSpace(cmd.usage()))
|
||||
gnuflag.PrintDefaults()
|
||||
}
|
||||
|
||||
os.Args = os.Args[1:]
|
||||
gnuflag.Parse(true)
|
||||
|
||||
if *verbose || *debug {
|
||||
lxd.SetLogger(log.New(os.Stderr, "", log.LstdFlags))
|
||||
lxd.SetDebug(*debug)
|
||||
}
|
||||
return cmd.run(gnuflag.Args())
|
||||
}
|
||||
|
||||
type command interface {
|
||||
usage() string
|
||||
flags()
|
||||
run(args []string) error
|
||||
}
|
||||
|
||||
var commands = map[string]command{
|
||||
"version": &versionCmd{},
|
||||
"help": &helpCmd{},
|
||||
"ping": &pingCmd{},
|
||||
}
|
||||
|
||||
var errArgs = fmt.Errorf("too many subcommand arguments")
|
||||
43
lxc/ping.go
Normal file
43
lxc/ping.go
Normal file
@@ -0,0 +1,43 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/lxc/lxd"
|
||||
)
|
||||
|
||||
type pingCmd struct {
|
||||
httpAddr string
|
||||
}
|
||||
|
||||
const pingUsage = `
|
||||
lxcping
|
||||
|
||||
Pings the lxd instance to check if it is up and working.
|
||||
`
|
||||
|
||||
func (c *pingCmd) usage() string {
|
||||
return pingUsage
|
||||
}
|
||||
|
||||
func (c *pingCmd) flags() {}
|
||||
|
||||
func (c *pingCmd) run(args []string) error {
|
||||
if len(args) > 1 {
|
||||
return errArgs
|
||||
}
|
||||
|
||||
config, err := lxd.LoadConfig()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var remote string
|
||||
if len(args) == 1 {
|
||||
remote = args[0]
|
||||
} else {
|
||||
remote = config.DefaultRemote
|
||||
}
|
||||
|
||||
// NewClient will ping the server to test the connection before returning.
|
||||
_, _, err = lxd.NewClient(config, remote)
|
||||
return err
|
||||
}
|
||||
30
lxc/version.go
Normal file
30
lxc/version.go
Normal file
@@ -0,0 +1,30 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/lxc/lxd"
|
||||
)
|
||||
|
||||
type versionCmd struct{}
|
||||
|
||||
const versionUsage = `
|
||||
lxd version
|
||||
|
||||
Prints the version number of lxd.
|
||||
`
|
||||
|
||||
func (c *versionCmd) usage() string {
|
||||
return versionUsage
|
||||
}
|
||||
|
||||
func (c *versionCmd) flags() {
|
||||
}
|
||||
|
||||
func (c *versionCmd) run(args []string) error {
|
||||
if len(args) > 0 {
|
||||
return errArgs
|
||||
}
|
||||
fmt.Println(lxd.Version)
|
||||
return nil
|
||||
}
|
||||
98
lxd/daemon.go
Normal file
98
lxd/daemon.go
Normal file
@@ -0,0 +1,98 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
|
||||
"gopkg.in/tomb.v2"
|
||||
"github.com/lxc/lxd"
|
||||
)
|
||||
|
||||
// A Daemon can respond to requests from a lxd client.
|
||||
type Daemon struct {
|
||||
tomb tomb.Tomb
|
||||
unixl net.Listener
|
||||
tcpl net.Listener
|
||||
lxcpath string
|
||||
mux *http.ServeMux
|
||||
}
|
||||
|
||||
// StartDaemon starts the lxd daemon with the provided configuration.
|
||||
func StartDaemon(listenAddr string) (*Daemon, error) {
|
||||
d := &Daemon{}
|
||||
d.mux = http.NewServeMux()
|
||||
d.mux.HandleFunc("/ping", d.servePing)
|
||||
|
||||
var err error
|
||||
|
||||
d.lxcpath = lxd.VarPath("lxc")
|
||||
err = os.MkdirAll(lxd.VarPath("/"), 0755)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
err = os.MkdirAll(d.lxcpath, 0755)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
unixAddr, err := net.ResolveUnixAddr("unix", lxd.VarPath("unix.socket"))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cannot resolve unix socket address: %v", err)
|
||||
}
|
||||
unixl, err := net.ListenUnix("unix", unixAddr)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cannot listen on unix socket: %v", err)
|
||||
}
|
||||
d.unixl = unixl
|
||||
|
||||
if listenAddr != "" {
|
||||
// Watch out. Threre's a listener active which must be closed on errors.
|
||||
tcpAddr, err := net.ResolveTCPAddr("tcp", listenAddr)
|
||||
if err != nil {
|
||||
d.unixl.Close()
|
||||
return nil, fmt.Errorf("cannot resolve unix socket address: %v", err)
|
||||
}
|
||||
tcpl, err := net.ListenTCP("tcp", tcpAddr)
|
||||
if err != nil {
|
||||
d.unixl.Close()
|
||||
return nil, fmt.Errorf("cannot listen on unix socket: %v", err)
|
||||
}
|
||||
d.tcpl = tcpl
|
||||
d.tomb.Go(func() error { return http.Serve(d.tcpl, d.mux) })
|
||||
}
|
||||
|
||||
d.tomb.Go(func() error { return http.Serve(d.unixl, d.mux) })
|
||||
return d, nil
|
||||
}
|
||||
|
||||
var errStop = fmt.Errorf("requested stop")
|
||||
|
||||
// Stop stops the lxd daemon.
|
||||
func (d *Daemon) Stop() error {
|
||||
d.tomb.Kill(errStop)
|
||||
d.unixl.Close()
|
||||
if d.tcpl != nil {
|
||||
d.tcpl.Close()
|
||||
}
|
||||
err := d.tomb.Wait()
|
||||
if err == errStop {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// None of the daemon methods should print anything to stdout or stderr. If
|
||||
// there's a local issue in the daemon that the admin should know about, it
|
||||
// should be logged using either Logf or Debugf.
|
||||
//
|
||||
// Then, all of those issues that prevent the request from being served properly
|
||||
// for any reason (bad parameters or any other local error) should be notified
|
||||
// back to the client by writing an error json document to w, which in turn will
|
||||
// be read by the client and returned via the API as an error result. These
|
||||
// errors then surface via the CLI (cmd/lxd/*) in os.Stderr.
|
||||
//
|
||||
// Together, these ideas ensure that we have a proper daemon, and a proper client,
|
||||
// which can both be used independently and also embedded into other applications.
|
||||
|
||||
48
lxd/main.go
Normal file
48
lxd/main.go
Normal file
@@ -0,0 +1,48 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
|
||||
"github.com/lxc/lxd"
|
||||
"github.com/lxc/lxd/internal/gnuflag"
|
||||
)
|
||||
|
||||
func main() {
|
||||
if err := run(); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "error: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
var verbose = gnuflag.Bool("v", false, "Enables verbose mode.")
|
||||
var debug = gnuflag.Bool("debug", false, "Enables debug mode.")
|
||||
var listenAddr = gnuflag.String("tcp", "", "TCP address to listen on in addition to the unix socket")
|
||||
|
||||
func run() error {
|
||||
gnuflag.Usage = func() {
|
||||
fmt.Fprintf(os.Stderr, "Usage: %s\n\nOptions:\n\n--tcp <addr:port> Bind to addr:port.")
|
||||
gnuflag.PrintDefaults()
|
||||
}
|
||||
|
||||
gnuflag.Parse(true)
|
||||
|
||||
if *verbose || *debug {
|
||||
lxd.SetLogger(log.New(os.Stderr, "", log.LstdFlags))
|
||||
lxd.SetDebug(*debug)
|
||||
}
|
||||
|
||||
d, err := StartDaemon(*listenAddr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
ch := make(chan os.Signal)
|
||||
signal.Notify(ch, syscall.SIGINT)
|
||||
signal.Notify(ch, syscall.SIGTERM)
|
||||
<-ch
|
||||
return d.Stop()
|
||||
}
|
||||
17
lxd/ping.go
Normal file
17
lxd/ping.go
Normal file
@@ -0,0 +1,17 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/lxc/lxd"
|
||||
)
|
||||
|
||||
func (d *Daemon) servePing(w http.ResponseWriter, r *http.Request) {
|
||||
remoteAddr := r.RemoteAddr
|
||||
if remoteAddr == "@" {
|
||||
remoteAddr = "unix socket"
|
||||
}
|
||||
lxd.Debugf("responding to ping from %s", remoteAddr)
|
||||
w.Write([]byte(lxd.Version))
|
||||
}
|
||||
|
||||
@@ -69,6 +69,7 @@ possible.
|
||||
|
||||
Command | Description
|
||||
:------ | :----------
|
||||
ping | Ping the lxd instance to see if it is online.
|
||||
start | Create and/or start a container (option for ephemeral)
|
||||
stop | Stop a container
|
||||
status | Show the status of a resource (host, container, snapshot, ...)
|
||||
@@ -86,6 +87,19 @@ publish | Publish a local snapshot or container as a bundled image
|
||||
|
||||
* * *
|
||||
|
||||
## ping
|
||||
|
||||
**Arguments**
|
||||
|
||||
[resource]
|
||||
|
||||
**Description**
|
||||
|
||||
Sends a ping to the lxd instance, and wait for the daemon's version number as a
|
||||
response.
|
||||
|
||||
* * *
|
||||
|
||||
## start
|
||||
|
||||
**Arguments**
|
||||
|
||||
Reference in New Issue
Block a user