repo
stringlengths
5
67
sha
stringlengths
40
40
path
stringlengths
4
234
url
stringlengths
85
339
language
stringclasses
6 values
split
stringclasses
3 values
doc
stringlengths
3
51.2k
sign
stringlengths
5
8.01k
problem
stringlengths
13
51.2k
output
stringlengths
0
3.87M
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
client/mflag/flag.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/client/mflag/flag.go#L822-L824
go
train
// 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 (fs *FlagSet) StringVar(p *string, names []string, value string, usage string)
// 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 (fs *FlagSet) StringVar(p *string, names []string, value string, usage string)
{ fs.Var(newStringValue(value, p), names, usage) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
client/mflag/flag.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/client/mflag/flag.go#L828-L830
go
train
// 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, names []string, value string, usage string)
// 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, names []string, value string, usage string)
{ CommandLine.Var(newStringValue(value, p), names, usage) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
client/mflag/flag.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/client/mflag/flag.go#L834-L838
go
train
// 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 (fs *FlagSet) String(names []string, value string, usage string) *string
// 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 (fs *FlagSet) String(names []string, value string, usage string) *string
{ p := new(string) fs.StringVar(p, names, value, usage) return p }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
client/mflag/flag.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/client/mflag/flag.go#L842-L844
go
train
// 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(names []string, value string, usage string) *string
// 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(names []string, value string, usage string) *string
{ return CommandLine.String(names, value, usage) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
client/mflag/flag.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/client/mflag/flag.go#L848-L850
go
train
// 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 (fs *FlagSet) Float64Var(p *float64, names []string, value float64, usage string)
// 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 (fs *FlagSet) Float64Var(p *float64, names []string, value float64, usage string)
{ fs.Var(newFloat64Value(value, p), names, usage) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
client/mflag/flag.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/client/mflag/flag.go#L860-L864
go
train
// 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 (fs *FlagSet) Float64(names []string, value float64, usage string) *float64
// 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 (fs *FlagSet) Float64(names []string, value float64, usage string) *float64
{ p := new(float64) fs.Float64Var(p, names, value, usage) return p }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
client/mflag/flag.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/client/mflag/flag.go#L868-L870
go
train
// 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(names []string, value float64, usage string) *float64
// 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(names []string, value float64, usage string) *float64
{ return CommandLine.Float64(names, value, usage) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
client/mflag/flag.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/client/mflag/flag.go#L874-L876
go
train
// 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 (fs *FlagSet) DurationVar(p *time.Duration, names []string, value time.Duration, usage string)
// 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 (fs *FlagSet) DurationVar(p *time.Duration, names []string, value time.Duration, usage string)
{ fs.Var(newDurationValue(value, p), names, usage) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
client/mflag/flag.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/client/mflag/flag.go#L880-L882
go
train
// 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, names []string, value time.Duration, usage string)
// 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, names []string, value time.Duration, usage string)
{ CommandLine.Var(newDurationValue(value, p), names, usage) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
client/mflag/flag.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/client/mflag/flag.go#L886-L890
go
train
// 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 (fs *FlagSet) Duration(names []string, value time.Duration, usage string) *time.Duration
// 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 (fs *FlagSet) Duration(names []string, value time.Duration, usage string) *time.Duration
{ p := new(time.Duration) fs.DurationVar(p, names, value, usage) return p }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
client/mflag/flag.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/client/mflag/flag.go#L894-L896
go
train
// 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(names []string, value time.Duration, usage string) *time.Duration
// 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(names []string, value time.Duration, usage string) *time.Duration
{ return CommandLine.Duration(names, value, usage) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
client/mflag/flag.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/client/mflag/flag.go#L904-L925
go
train
// 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 (fs *FlagSet) Var(value Value, names []string, usage string)
// 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 (fs *FlagSet) Var(value Value, names []string, usage string)
{ // Remember the default value as a string; it won't change. flag := &Flag{names, usage, value, value.String()} for _, name := range names { name = strings.TrimPrefix(name, "#") _, alreadythere := fs.formal[name] if alreadythere { var msg string if fs.name == "" { msg = fmt.Sprintf("flag redefined: %s", name) } else { msg = fmt.Sprintf("%s flag redefined: %s", fs.name, name) } fmt.Fprintln(fs.Out(), msg) panic(msg) // Happens only if flags are declared with identical names } if fs.formal == nil { fs.formal = make(map[string]*Flag) } fs.formal[name] = flag } }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
client/mflag/flag.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/client/mflag/flag.go#L933-L935
go
train
// 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, names []string, usage string)
// 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, names []string, usage string)
{ CommandLine.Var(value, names, usage) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
client/mflag/flag.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/client/mflag/flag.go#L939-L948
go
train
// failf prints to standard error a formatted error and usage message and // returns the error.
func (fs *FlagSet) failf(format string, a ...interface{}) error
// failf prints to standard error a formatted error and usage message and // returns the error. func (fs *FlagSet) failf(format string, a ...interface{}) error
{ err := fmt.Errorf(format, a...) fmt.Fprintln(fs.Out(), err) if os.Args[0] == fs.name { fmt.Fprintf(fs.Out(), "See '%s --help'.\n", os.Args[0]) } else { fmt.Fprintf(fs.Out(), "See '%s %s --help'.\n", os.Args[0], fs.name) } return err }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
client/mflag/flag.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/client/mflag/flag.go#L952-L960
go
train
// usage calls the Usage method for the flag set, or the usage function if // the flag set is CommandLine.
func (fs *FlagSet) usage()
// usage calls the Usage method for the flag set, or the usage function if // the flag set is CommandLine. func (fs *FlagSet) usage()
{ if fs == CommandLine { Usage() } else if fs.Usage == nil { defaultUsage(fs) } else { fs.Usage() } }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
client/mflag/flag.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/client/mflag/flag.go#L997-L1079
go
train
// parseOne parses one flag. It reports whether a flag was seen.
func (fs *FlagSet) parseOne() (bool, string, error)
// parseOne parses one flag. It reports whether a flag was seen. func (fs *FlagSet) parseOne() (bool, string, error)
{ if len(fs.args) == 0 { return false, "", nil } s := fs.args[0] if len(s) == 0 || s[0] != '-' || len(s) == 1 { return false, "", nil } if s[1] == '-' && len(s) == 2 { // "--" terminates the flags fs.args = fs.args[1:] return false, "", nil } name := s[1:] if len(name) == 0 || name[0] == '=' { return false, "", fs.failf("bad flag syntax: %s", s) } // it's a flag. does it have an argument? fs.args = fs.args[1:] hasValue := false value := "" if i := strings.Index(name, "="); i != -1 { value = trimQuotes(name[i+1:]) hasValue = true name = name[:i] } m := fs.formal flag, alreadythere := m[name] // BUG if !alreadythere { if name == "-help" || name == "help" || name == "h" { // special case for nice help message. fs.usage() return false, "", ErrHelp } if len(name) > 0 && name[0] == '-' { return false, "", fs.failf("flag provided but not defined: -%s", name) } return false, name, ErrRetry } if fv, ok := flag.Value.(boolFlag); ok && fv.IsBoolFlag() { // special case: doesn't need an arg if hasValue { if err := fv.Set(value); err != nil { return false, "", fs.failf("invalid boolean value %q for -%s: %v", value, name, err) } } else { fv.Set("true") } } else { // It must have a value, which might be the next argument. if !hasValue && len(fs.args) > 0 { // value is the next arg hasValue = true value, fs.args = fs.args[0], fs.args[1:] } if !hasValue { return false, "", fs.failf("flag needs an argument: -%s", name) } if err := flag.Value.Set(value); err != nil { return false, "", fs.failf("invalid value %q for flag -%s: %v", value, name, err) } } if fs.actual == nil { fs.actual = make(map[string]*Flag) } fs.actual[name] = flag for i, n := range flag.Names { if n == fmt.Sprintf("#%s", name) { replacement := "" for j := i; j < len(flag.Names); j++ { if flag.Names[j][0] != '#' { replacement = flag.Names[j] break } } if replacement != "" { fmt.Fprintf(fs.Out(), "Warning: '-%s' is deprecated, it will be replaced by '-%s' soon. See usage.\n", name, replacement) } else { fmt.Fprintf(fs.Out(), "Warning: '-%s' is deprecated, it will be removed soon. See usage.\n", name) } } } return true, "", nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
client/mflag/flag.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/client/mflag/flag.go#L1085-L1127
go
train
// 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.
func (fs *FlagSet) Parse(arguments []string) error
// 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. func (fs *FlagSet) Parse(arguments []string) error
{ fs.parsed = true fs.args = arguments for { seen, name, err := fs.parseOne() if seen { continue } if err == nil { break } if err == ErrRetry { if len(name) > 1 { err = nil for _, letter := range strings.Split(name, "") { fs.args = append([]string{"-" + letter}, fs.args...) seen2, _, err2 := fs.parseOne() if seen2 { continue } if err2 != nil { err = fs.failf("flag provided but not defined: -%s", name) break } } if err == nil { continue } } else { err = fs.failf("flag provided but not defined: -%s", name) } } switch fs.errorHandling { case ContinueOnError: return err case ExitOnError: os.Exit(125) case PanicOnError: panic(err) } } return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
client/mflag/flag.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/client/mflag/flag.go#L1134-L1154
go
train
// ParseFlags is a utility function that adds a help flag if withHelp is true, // calls fs.Parse(args) and prints a relevant error message if there are // incorrect number of arguments. It returns error only if error handling is // set to ContinueOnError and parsing fails. If error handling is set to // ExitOnError, it's safe to ignore the return value.
func (fs *FlagSet) ParseFlags(args []string, withHelp bool) error
// ParseFlags is a utility function that adds a help flag if withHelp is true, // calls fs.Parse(args) and prints a relevant error message if there are // incorrect number of arguments. It returns error only if error handling is // set to ContinueOnError and parsing fails. If error handling is set to // ExitOnError, it's safe to ignore the return value. func (fs *FlagSet) ParseFlags(args []string, withHelp bool) error
{ var help *bool if withHelp { help = fs.Bool([]string{"#help", "-help"}, false, "Print usage") } if err := fs.Parse(args); err != nil { return err } if help != nil && *help { fs.SetOutput(os.Stdout) fs.Usage() os.Exit(0) } if str := fs.CheckArgs(); str != "" { fs.SetOutput(os.Stderr) fs.ReportError(str, withHelp) fs.ShortUsage() os.Exit(1) } return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
client/mflag/flag.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/client/mflag/flag.go#L1158-L1167
go
train
// ReportError is a utility method that prints a user-friendly message // containing the error that occurred during parsing and a suggestion to get help
func (fs *FlagSet) ReportError(str string, withHelp bool)
// ReportError is a utility method that prints a user-friendly message // containing the error that occurred during parsing and a suggestion to get help func (fs *FlagSet) ReportError(str string, withHelp bool)
{ if withHelp { if os.Args[0] == fs.Name() { str += ".\nSee '" + os.Args[0] + " --help'" } else { str += ".\nSee '" + os.Args[0] + " " + fs.Name() + " --help'" } } fmt.Fprintf(fs.Out(), "%s: %s.\n", os.Args[0], str) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
client/mflag/flag.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/client/mflag/flag.go#L1193-L1199
go
train
// NewFlagSet returns a new, empty flag set with the specified name and // error handling property.
func NewFlagSet(name string, errorHandling ErrorHandling) *FlagSet
// 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 }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
client/mflag/flag.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/client/mflag/flag.go#L1204-L1207
go
train
// 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 (fs *FlagSet) Init(name string, errorHandling ErrorHandling)
// 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 (fs *FlagSet) Init(name string, errorHandling ErrorHandling)
{ fs.name = name fs.errorHandling = errorHandling }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
client/mflag/flag.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/client/mflag/flag.go#L1229-L1237
go
train
// Name returns the name of a mergeVal. // If the original value had a name, return the original name, // otherwise, return the key assigned to this mergeVal.
func (v mergeVal) Name() string
// Name returns the name of a mergeVal. // If the original value had a name, return the original name, // otherwise, return the key assigned to this mergeVal. func (v mergeVal) Name() string
{ type namedValue interface { Name() string } if nVal, ok := v.Value.(namedValue); ok { return nVal.Name() } return v.key }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
client/mflag/flag.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/client/mflag/flag.go#L1242-L1275
go
train
// Merge is an helper function that merges n FlagSets into a single dest FlagSet // In case of name collision between the flagsets it will apply // the destination FlagSet's errorHandling behavior.
func Merge(dest *FlagSet, flagsets ...*FlagSet) error
// Merge is an helper function that merges n FlagSets into a single dest FlagSet // In case of name collision between the flagsets it will apply // the destination FlagSet's errorHandling behavior. func Merge(dest *FlagSet, flagsets ...*FlagSet) error
{ for _, fset := range flagsets { if fset.formal == nil { continue } for k, f := range fset.formal { if _, ok := dest.formal[k]; ok { var err error if fset.name == "" { err = fmt.Errorf("flag redefined: %s", k) } else { err = fmt.Errorf("%s flag redefined: %s", fset.name, k) } fmt.Fprintln(fset.Out(), err.Error()) // Happens only if flags are declared with identical names switch dest.errorHandling { case ContinueOnError: return err case ExitOnError: os.Exit(2) case PanicOnError: panic(err) } } newF := *f newF.Value = mergeVal{f.Value, k, fset} if dest.formal == nil { dest.formal = make(map[string]*Flag) } dest.formal[k] = &newF } } return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
sandbox_dns_unix.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/sandbox_dns_unix.go#L351-L405
go
train
// Embedded DNS server has to be enabled for this sandbox. Rebuild the container's // resolv.conf by doing the following // - Add only the embedded server's IP to container's resolv.conf // - If the embedded server needs any resolv.conf options add it to the current list
func (sb *sandbox) rebuildDNS() error
// Embedded DNS server has to be enabled for this sandbox. Rebuild the container's // resolv.conf by doing the following // - Add only the embedded server's IP to container's resolv.conf // - If the embedded server needs any resolv.conf options add it to the current list func (sb *sandbox) rebuildDNS() error
{ currRC, err := resolvconf.GetSpecific(sb.config.resolvConfPath) if err != nil { return err } if len(sb.extDNS) == 0 { sb.setExternalResolvers(currRC.Content, types.IPv4, false) } var ( dnsList = []string{sb.resolver.NameServer()} dnsOptionsList = resolvconf.GetOptions(currRC.Content) dnsSearchList = resolvconf.GetSearchDomains(currRC.Content) ) // external v6 DNS servers has to be listed in resolv.conf dnsList = append(dnsList, resolvconf.GetNameservers(currRC.Content, types.IPv6)...) // If the user config and embedded DNS server both have ndots option set, // remember the user's config so that unqualified names not in the docker // domain can be dropped. resOptions := sb.resolver.ResolverOptions() dnsOpt: for _, resOpt := range resOptions { if strings.Contains(resOpt, "ndots") { for _, option := range dnsOptionsList { if strings.Contains(option, "ndots") { parts := strings.Split(option, ":") if len(parts) != 2 { return fmt.Errorf("invalid ndots option %v", option) } if num, err := strconv.Atoi(parts[1]); err != nil { return fmt.Errorf("invalid number for ndots option: %v", parts[1]) } else if num >= 0 { // if the user sets ndots, use the user setting sb.ndotsSet = true break dnsOpt } else { return fmt.Errorf("invalid number for ndots option: %v", num) } } } } } if !sb.ndotsSet { // if the user did not set the ndots, set it to 0 to prioritize the service name resolution // Ref: https://linux.die.net/man/5/resolv.conf dnsOptionsList = append(dnsOptionsList, resOptions...) } _, err = resolvconf.Build(sb.config.resolvConfPath, dnsList, dnsSearchList, dnsOptionsList) return err }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
client/client.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/client/client.go#L25-L31
go
train
// NewNetworkCli is a convenient function to create a NetworkCli object
func NewNetworkCli(out, err io.Writer, call CallFunc) *NetworkCli
// NewNetworkCli is a convenient function to create a NetworkCli object func NewNetworkCli(out, err io.Writer, call CallFunc) *NetworkCli
{ return &NetworkCli{ out: out, err: err, call: call, } }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
client/client.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/client/client.go#L34-L48
go
train
// getMethod is Borrowed from Docker UI which uses reflection to identify the UI Handler
func (cli *NetworkCli) getMethod(args ...string) (func(string, ...string) error, bool)
// getMethod is Borrowed from Docker UI which uses reflection to identify the UI Handler func (cli *NetworkCli) getMethod(args ...string) (func(string, ...string) error, bool)
{ camelArgs := make([]string, len(args)) for i, s := range args { if len(s) == 0 { return nil, false } camelArgs[i] = strings.ToUpper(s[:1]) + strings.ToLower(s[1:]) } methodName := "Cmd" + strings.Join(camelArgs, "") method := reflect.ValueOf(cli).MethodByName(methodName) if !method.IsValid() { return nil, false } return method.Interface().(func(string, ...string) error), true }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
client/client.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/client/client.go#L52-L74
go
train
// Cmd is borrowed from Docker UI and acts as the entry point for network UI commands. // network UI commands are designed to be invoked from multiple parent chains
func (cli *NetworkCli) Cmd(chain string, args ...string) error
// Cmd is borrowed from Docker UI and acts as the entry point for network UI commands. // network UI commands are designed to be invoked from multiple parent chains func (cli *NetworkCli) Cmd(chain string, args ...string) error
{ if len(args) > 2 { method, exists := cli.getMethod(args[:3]...) if exists { return method(chain+" "+args[0]+" "+args[1], args[3:]...) } } if len(args) > 1 { method, exists := cli.getMethod(args[:2]...) if exists { return method(chain+" "+args[0], args[2:]...) } } if len(args) > 0 { method, exists := cli.getMethod(args[0]) if !exists { return fmt.Errorf("%s: '%s' is not a %s command. See '%s --help'", chain, args[0], chain, chain) } return method(chain, args[1:]...) } flag.Usage() return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
client/client.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/client/client.go#L77-L101
go
train
// Subcmd is borrowed from Docker UI and performs the same function of configuring the subCmds
func (cli *NetworkCli) Subcmd(chain, name, signature, description string, exitOnError bool) *flag.FlagSet
// Subcmd is borrowed from Docker UI and performs the same function of configuring the subCmds func (cli *NetworkCli) Subcmd(chain, name, signature, description string, exitOnError bool) *flag.FlagSet
{ var errorHandling flag.ErrorHandling if exitOnError { errorHandling = flag.ExitOnError } else { errorHandling = flag.ContinueOnError } flags := flag.NewFlagSet(name, errorHandling) flags.Usage = func() { flags.ShortUsage() flags.PrintDefaults() } flags.ShortUsage = func() { options := "" if signature != "" { signature = " " + signature } if flags.FlagCountUndeprecated() > 0 { options = " [OPTIONS]" } fmt.Fprintf(cli.out, "\nUsage: %s %s%s%s\n\n%s\n\n", chain, name, options, signature, description) flags.SetOutput(cli.out) } return flags }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
etchosts/etchosts.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/etchosts/etchosts.go#L22-L25
go
train
// WriteTo writes record to file and returns bytes written or error
func (r Record) WriteTo(w io.Writer) (int64, error)
// WriteTo writes record to file and returns bytes written or error func (r Record) WriteTo(w io.Writer) (int64, error)
{ n, err := fmt.Fprintf(w, "%s\t%s\n", r.IP, r.Hosts) return int64(n), err }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
etchosts/etchosts.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/etchosts/etchosts.go#L63-L68
go
train
// Drop drops the path string from the path cache
func Drop(path string)
// Drop drops the path string from the path cache func Drop(path string)
{ pathMutex.Lock() defer pathMutex.Unlock() delete(pathMap, path) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
etchosts/etchosts.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/etchosts/etchosts.go#L74-L112
go
train
// Build function // path is path to host file string required // IP, hostname, and domainname set main record leave empty for no master record // extraContent is an array of extra host records.
func Build(path, IP, hostname, domainname string, extraContent []Record) error
// Build function // path is path to host file string required // IP, hostname, and domainname set main record leave empty for no master record // extraContent is an array of extra host records. func Build(path, IP, hostname, domainname string, extraContent []Record) error
{ defer pathLock(path)() content := bytes.NewBuffer(nil) if IP != "" { //set main record var mainRec Record mainRec.IP = IP // User might have provided a FQDN in hostname or split it across hostname // and domainname. We want the FQDN and the bare hostname. fqdn := hostname if domainname != "" { fqdn = fmt.Sprintf("%s.%s", fqdn, domainname) } parts := strings.SplitN(fqdn, ".", 2) if len(parts) == 2 { mainRec.Hosts = fmt.Sprintf("%s %s", fqdn, parts[0]) } else { mainRec.Hosts = fqdn } if _, err := mainRec.WriteTo(content); err != nil { return err } } // Write defaultContent slice to buffer for _, r := range defaultContent { if _, err := r.WriteTo(content); err != nil { return err } } // Write extra content from function arguments for _, r := range extraContent { if _, err := r.WriteTo(content); err != nil { return err } } return ioutil.WriteFile(path, content.Bytes(), 0644) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
etchosts/etchosts.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/etchosts/etchosts.go#L115-L128
go
train
// Add adds an arbitrary number of Records to an already existing /etc/hosts file
func Add(path string, recs []Record) error
// Add adds an arbitrary number of Records to an already existing /etc/hosts file func Add(path string, recs []Record) error
{ defer pathLock(path)() if len(recs) == 0 { return nil } b, err := mergeRecords(path, recs) if err != nil { return err } return ioutil.WriteFile(path, b, 0644) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
etchosts/etchosts.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/etchosts/etchosts.go#L153-L193
go
train
// Delete deletes an arbitrary number of Records already existing in /etc/hosts file
func Delete(path string, recs []Record) error
// Delete deletes an arbitrary number of Records already existing in /etc/hosts file func Delete(path string, recs []Record) error
{ defer pathLock(path)() if len(recs) == 0 { return nil } old, err := os.Open(path) if err != nil { return err } var buf bytes.Buffer s := bufio.NewScanner(old) eol := []byte{'\n'} loop: for s.Scan() { b := s.Bytes() if len(b) == 0 { continue } if b[0] == '#' { buf.Write(b) buf.Write(eol) continue } for _, r := range recs { if bytes.HasSuffix(b, []byte("\t"+r.Hosts)) { continue loop } } buf.Write(b) buf.Write(eol) } old.Close() if err := s.Err(); err != nil { return err } return ioutil.WriteFile(path, buf.Bytes(), 0644) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
etchosts/etchosts.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/etchosts/etchosts.go#L199-L208
go
train
// Update all IP addresses where hostname matches. // path is path to host file // IP is new IP address // hostname is hostname to search for to replace IP
func Update(path, IP, hostname string) error
// Update all IP addresses where hostname matches. // path is path to host file // IP is new IP address // hostname is hostname to search for to replace IP func Update(path, IP, hostname string) error
{ defer pathLock(path)() old, err := ioutil.ReadFile(path) if err != nil { return err } var re = regexp.MustCompile(fmt.Sprintf("(\\S*)(\\t%s)(\\s|\\.)", regexp.QuoteMeta(hostname))) return ioutil.WriteFile(path, re.ReplaceAll(old, []byte(IP+"$2"+"$3")), 0644) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
drivers/overlay/overlay.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/overlay/overlay.go#L59-L108
go
train
// Init registers a new instance of overlay driver
func Init(dc driverapi.DriverCallback, config map[string]interface{}) error
// Init registers a new instance of overlay driver func Init(dc driverapi.DriverCallback, config map[string]interface{}) error
{ c := driverapi.Capability{ DataScope: datastore.GlobalScope, ConnectivityScope: datastore.GlobalScope, } d := &driver{ networks: networkTable{}, peerDb: peerNetworkMap{ mp: map[string]*peerMap{}, }, secMap: &encrMap{nodes: map[string][]*spi{}}, config: config, peerOpCh: make(chan *peerOperation), } // Launch the go routine for processing peer operations ctx, cancel := context.WithCancel(context.Background()) d.peerOpCancel = cancel go d.peerOpRoutine(ctx, d.peerOpCh) if data, ok := config[netlabel.GlobalKVClient]; ok { var err error dsc, ok := data.(discoverapi.DatastoreConfigData) if !ok { return types.InternalErrorf("incorrect data in datastore configuration: %v", data) } d.store, err = datastore.NewDataStoreFromConfig(dsc) if err != nil { return types.InternalErrorf("failed to initialize data store: %v", err) } } if data, ok := config[netlabel.LocalKVClient]; ok { var err error dsc, ok := data.(discoverapi.DatastoreConfigData) if !ok { return types.InternalErrorf("incorrect data in datastore configuration: %v", data) } d.localStore, err = datastore.NewDataStoreFromConfig(dsc) if err != nil { return types.InternalErrorf("failed to initialize local data store: %v", err) } } if err := d.restoreEndpoints(); err != nil { logrus.Warnf("Failure during overlay endpoints restore: %v", err) } return dc.RegisterDriver(networkType, d, c) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
drivers/overlay/overlay.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/overlay/overlay.go#L111-L160
go
train
// Endpoints are stored in the local store. Restore them and reconstruct the overlay sandbox
func (d *driver) restoreEndpoints() error
// Endpoints are stored in the local store. Restore them and reconstruct the overlay sandbox func (d *driver) restoreEndpoints() error
{ if d.localStore == nil { logrus.Warn("Cannot restore overlay endpoints because local datastore is missing") return nil } kvol, err := d.localStore.List(datastore.Key(overlayEndpointPrefix), &endpoint{}) if err != nil && err != datastore.ErrKeyNotFound { return fmt.Errorf("failed to read overlay endpoint from store: %v", err) } if err == datastore.ErrKeyNotFound { return nil } for _, kvo := range kvol { ep := kvo.(*endpoint) n := d.network(ep.nid) if n == nil { logrus.Debugf("Network (%.7s) not found for restored endpoint (%.7s)", ep.nid, ep.id) logrus.Debugf("Deleting stale overlay endpoint (%.7s) from store", ep.id) if err := d.deleteEndpointFromStore(ep); err != nil { logrus.Debugf("Failed to delete stale overlay endpoint (%.7s) from store", ep.id) } continue } n.addEndpoint(ep) s := n.getSubnetforIP(ep.addr) if s == nil { return fmt.Errorf("could not find subnet for endpoint %s", ep.id) } if err := n.joinSandbox(s, true, true); err != nil { return fmt.Errorf("restore network sandbox failed: %v", err) } Ifaces := make(map[string][]osl.IfaceOption) vethIfaceOption := make([]osl.IfaceOption, 1) vethIfaceOption = append(vethIfaceOption, n.sbox.InterfaceOptions().Master(s.brName)) Ifaces["veth+veth"] = vethIfaceOption err := n.sbox.Restore(Ifaces, nil, nil, nil) if err != nil { n.leaveSandbox() return fmt.Errorf("failed to restore overlay sandbox: %v", err) } d.peerAdd(ep.nid, ep.id, ep.addr.IP, ep.addr.Mask, ep.mac, net.ParseIP(d.advertiseAddress), false, false, true) } return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
drivers/overlay/overlay.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/overlay/overlay.go#L163-L178
go
train
// Fini cleans up the driver resources
func Fini(drv driverapi.Driver)
// Fini cleans up the driver resources func Fini(drv driverapi.Driver)
{ d := drv.(*driver) // Notify the peer go routine to return if d.peerOpCancel != nil { d.peerOpCancel() } if d.exitCh != nil { waitCh := make(chan struct{}) d.exitCh <- waitCh <-waitCh } }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
drivers/overlay/overlay.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/overlay/overlay.go#L319-L386
go
train
// DiscoverNew is a notification for a new discovery event, such as a new node joining a cluster
func (d *driver) DiscoverNew(dType discoverapi.DiscoveryType, data interface{}) error
// DiscoverNew is a notification for a new discovery event, such as a new node joining a cluster func (d *driver) DiscoverNew(dType discoverapi.DiscoveryType, data interface{}) error
{ var err error switch dType { case discoverapi.NodeDiscovery: nodeData, ok := data.(discoverapi.NodeDiscoveryData) if !ok || nodeData.Address == "" { return fmt.Errorf("invalid discovery data") } d.nodeJoin(nodeData.Address, nodeData.BindAddress, nodeData.Self) case discoverapi.DatastoreConfig: if d.store != nil { return types.ForbiddenErrorf("cannot accept datastore configuration: Overlay driver has a datastore configured already") } dsc, ok := data.(discoverapi.DatastoreConfigData) if !ok { return types.InternalErrorf("incorrect data in datastore configuration: %v", data) } d.store, err = datastore.NewDataStoreFromConfig(dsc) if err != nil { return types.InternalErrorf("failed to initialize data store: %v", err) } case discoverapi.EncryptionKeysConfig: encrData, ok := data.(discoverapi.DriverEncryptionConfig) if !ok { return fmt.Errorf("invalid encryption key notification data") } keys := make([]*key, 0, len(encrData.Keys)) for i := 0; i < len(encrData.Keys); i++ { k := &key{ value: encrData.Keys[i], tag: uint32(encrData.Tags[i]), } keys = append(keys, k) } if err := d.setKeys(keys); err != nil { logrus.Warn(err) } case discoverapi.EncryptionKeysUpdate: var newKey, delKey, priKey *key encrData, ok := data.(discoverapi.DriverEncryptionUpdate) if !ok { return fmt.Errorf("invalid encryption key notification data") } if encrData.Key != nil { newKey = &key{ value: encrData.Key, tag: uint32(encrData.Tag), } } if encrData.Primary != nil { priKey = &key{ value: encrData.Primary, tag: uint32(encrData.PrimaryTag), } } if encrData.Prune != nil { delKey = &key{ value: encrData.Prune, tag: uint32(encrData.PruneTag), } } if err := d.updateKeys(newKey, priKey, delKey); err != nil { logrus.Warn(err) } default: } return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
drivers/host/host.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/host/host.go#L20-L26
go
train
// Init registers a new instance of host driver
func Init(dc driverapi.DriverCallback, config map[string]interface{}) error
// Init registers a new instance of host driver func Init(dc driverapi.DriverCallback, config map[string]interface{}) error
{ c := driverapi.Capability{ DataScope: datastore.LocalScope, ConnectivityScope: datastore.LocalScope, } return dc.RegisterDriver(networkType, &driver{}, c) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
drivers/host/host.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/host/host.go#L73-L75
go
train
// Join method is invoked when a Sandbox is attached to an endpoint.
func (d *driver) Join(nid, eid string, sboxKey string, jinfo driverapi.JoinInfo, options map[string]interface{}) error
// Join method is invoked when a Sandbox is attached to an endpoint. func (d *driver) Join(nid, eid string, sboxKey string, jinfo driverapi.JoinInfo, options map[string]interface{}) error
{ return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
drivers/bridge/interface.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/bridge/interface.go#L31-L48
go
train
// newInterface creates a new bridge interface structure. It attempts to find // an already existing device identified by the configuration BridgeName field, // or the default bridge name when unspecified, but doesn't attempt to create // one when missing
func newInterface(nlh *netlink.Handle, config *networkConfiguration) (*bridgeInterface, error)
// newInterface creates a new bridge interface structure. It attempts to find // an already existing device identified by the configuration BridgeName field, // or the default bridge name when unspecified, but doesn't attempt to create // one when missing func newInterface(nlh *netlink.Handle, config *networkConfiguration) (*bridgeInterface, error)
{ var err error i := &bridgeInterface{nlh: nlh} // Initialize the bridge name to the default if unspecified. if config.BridgeName == "" { config.BridgeName = DefaultBridgeName } // Attempt to find an existing bridge named with the specified name. i.Link, err = nlh.LinkByName(config.BridgeName) if err != nil { logrus.Debugf("Did not find any interface with name %s: %v", config.BridgeName, err) } else if _, ok := i.Link.(*netlink.Bridge); !ok { return nil, fmt.Errorf("existing interface %s is not a bridge", i.Link.Attrs().Name) } return i, nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
drivers/bridge/interface.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/bridge/interface.go#L56-L71
go
train
// addresses returns all IPv4 addresses and all IPv6 addresses for the bridge interface.
func (i *bridgeInterface) addresses() ([]netlink.Addr, []netlink.Addr, error)
// addresses returns all IPv4 addresses and all IPv6 addresses for the bridge interface. func (i *bridgeInterface) addresses() ([]netlink.Addr, []netlink.Addr, error)
{ v4addr, err := i.nlh.AddrList(i.Link, netlink.FAMILY_V4) if err != nil { return nil, nil, fmt.Errorf("Failed to retrieve V4 addresses: %v", err) } v6addr, err := i.nlh.AddrList(i.Link, netlink.FAMILY_V6) if err != nil { return nil, nil, fmt.Errorf("Failed to retrieve V6 addresses: %v", err) } if len(v4addr) == 0 { return nil, v6addr, nil } return v4addr, v6addr, nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
diagnostic/server.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/diagnostic/server.go#L25-L27
go
train
// ServeHTTP TODO
func (h httpHandlerCustom) ServeHTTP(w http.ResponseWriter, r *http.Request)
// ServeHTTP TODO func (h httpHandlerCustom) ServeHTTP(w http.ResponseWriter, r *http.Request)
{ h.F(h.ctx, w, r) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
diagnostic/server.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/diagnostic/server.go#L55-L60
go
train
// Init initialize the mux for the http handling and register the base hooks
func (s *Server) Init()
// Init initialize the mux for the http handling and register the base hooks func (s *Server) Init()
{ s.mux = http.NewServeMux() // Register local handlers s.RegisterHandler(s, diagPaths2Func) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
diagnostic/server.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/diagnostic/server.go#L63-L73
go
train
// RegisterHandler allows to register new handlers to the mux and to a specific path
func (s *Server) RegisterHandler(ctx interface{}, hdlrs map[string]HTTPHandlerFunc)
// RegisterHandler allows to register new handlers to the mux and to a specific path func (s *Server) RegisterHandler(ctx interface{}, hdlrs map[string]HTTPHandlerFunc)
{ s.Lock() defer s.Unlock() for path, fun := range hdlrs { if _, ok := s.registeredHanders[path]; ok { continue } s.mux.Handle(path, httpHandlerCustom{ctx, fun}) s.registeredHanders[path] = true } }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
diagnostic/server.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/diagnostic/server.go#L82-L104
go
train
// EnableDiagnostic opens a TCP socket to debug the passed network DB
func (s *Server) EnableDiagnostic(ip string, port int)
// EnableDiagnostic opens a TCP socket to debug the passed network DB func (s *Server) EnableDiagnostic(ip string, port int)
{ s.Lock() defer s.Unlock() s.port = port if s.enable == 1 { logrus.Info("The server is already up and running") return } logrus.Infof("Starting the diagnostic server listening on %d for commands", port) srv := &http.Server{Addr: fmt.Sprintf("%s:%d", ip, port), Handler: s} s.srv = srv s.enable = 1 go func(n *Server) { // Ignore ErrServerClosed that is returned on the Shutdown call if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed { logrus.Errorf("ListenAndServe error: %s", err) atomic.SwapInt32(&n.enable, 0) } }(s) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
diagnostic/server.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/diagnostic/server.go#L107-L115
go
train
// DisableDiagnostic stop the dubug and closes the tcp socket
func (s *Server) DisableDiagnostic()
// DisableDiagnostic stop the dubug and closes the tcp socket func (s *Server) DisableDiagnostic()
{ s.Lock() defer s.Unlock() s.srv.Shutdown(context.Background()) s.srv = nil s.enable = 0 logrus.Info("Disabling the diagnostic server") }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
diagnostic/server.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/diagnostic/server.go#L118-L122
go
train
// IsDiagnosticEnabled returns true when the debug is enabled
func (s *Server) IsDiagnosticEnabled() bool
// IsDiagnosticEnabled returns true when the debug is enabled func (s *Server) IsDiagnosticEnabled() bool
{ s.Lock() defer s.Unlock() return s.enable == 1 }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
diagnostic/server.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/diagnostic/server.go#L183-L187
go
train
// DebugHTTPForm helper to print the form url parameters
func DebugHTTPForm(r *http.Request)
// DebugHTTPForm helper to print the form url parameters func DebugHTTPForm(r *http.Request)
{ for k, v := range r.Form { logrus.Debugf("Form[%q] = %q\n", k, v) } }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
diagnostic/server.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/diagnostic/server.go#L196-L204
go
train
// ParseHTTPFormOptions easily parse the JSON printing options
func ParseHTTPFormOptions(r *http.Request) (bool, *JSONOutput)
// ParseHTTPFormOptions easily parse the JSON printing options func ParseHTTPFormOptions(r *http.Request) (bool, *JSONOutput)
{ _, unsafe := r.Form["unsafe"] v, json := r.Form["json"] var pretty bool if len(v) > 0 { pretty = v[0] == "pretty" } return unsafe, &JSONOutput{enable: json, prettyPrint: pretty} }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
diagnostic/server.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/diagnostic/server.go#L207-L227
go
train
// HTTPReply helper function that takes care of sending the message out
func HTTPReply(w http.ResponseWriter, r *HTTPResult, j *JSONOutput) (int, error)
// HTTPReply helper function that takes care of sending the message out func HTTPReply(w http.ResponseWriter, r *HTTPResult, j *JSONOutput) (int, error)
{ var response []byte if j.enable { w.Header().Set("Content-Type", "application/json") var err error if j.prettyPrint { response, err = json.MarshalIndent(r, "", " ") if err != nil { response, _ = json.MarshalIndent(FailCommand(err), "", " ") } } else { response, err = json.Marshal(r) if err != nil { response, _ = json.Marshal(FailCommand(err)) } } } else { response = []byte(r.String()) } return fmt.Fprint(w, string(response)) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
ipams/remote/remote.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipams/remote/remote.go#L34-L66
go
train
// Init registers a remote ipam when its plugin is activated
func Init(cb ipamapi.Callback, l, g interface{}) error
// Init registers a remote ipam when its plugin is activated func Init(cb ipamapi.Callback, l, g interface{}) error
{ newPluginHandler := func(name string, client *plugins.Client) { a := newAllocator(name, client) if cps, err := a.(*allocator).getCapabilities(); err == nil { if err := cb.RegisterIpamDriverWithCapabilities(name, a, cps); err != nil { logrus.Errorf("error registering remote ipam driver %s due to %v", name, err) } } else { logrus.Infof("remote ipam driver %s does not support capabilities", name) logrus.Debug(err) if err := cb.RegisterIpamDriver(name, a); err != nil { logrus.Errorf("error registering remote ipam driver %s due to %v", name, err) } } } // Unit test code is unaware of a true PluginStore. So we fall back to v1 plugins. handleFunc := plugins.Handle if pg := cb.GetPluginGetter(); pg != nil { handleFunc = pg.Handle activePlugins := pg.GetAllManagedPluginsByCap(ipamapi.PluginEndpointType) for _, ap := range activePlugins { client, err := getPluginClient(ap) if err != nil { return err } newPluginHandler(ap.Name(), client) } } handleFunc(ipamapi.PluginEndpointType, newPluginHandler) return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
ipams/remote/remote.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipams/remote/remote.go#L111-L117
go
train
// GetDefaultAddressSpaces returns the local and global default address spaces
func (a *allocator) GetDefaultAddressSpaces() (string, string, error)
// GetDefaultAddressSpaces returns the local and global default address spaces func (a *allocator) GetDefaultAddressSpaces() (string, string, error)
{ res := &api.GetAddressSpacesResponse{} if err := a.call("GetDefaultAddressSpaces", nil, res); err != nil { return "", "", err } return res.LocalDefaultAddressSpace, res.GlobalDefaultAddressSpace, nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
ipams/remote/remote.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipams/remote/remote.go#L120-L128
go
train
// RequestPool requests an address pool in the specified address space
func (a *allocator) RequestPool(addressSpace, pool, subPool string, options map[string]string, v6 bool) (string, *net.IPNet, map[string]string, error)
// RequestPool requests an address pool in the specified address space func (a *allocator) RequestPool(addressSpace, pool, subPool string, options map[string]string, v6 bool) (string, *net.IPNet, map[string]string, error)
{ req := &api.RequestPoolRequest{AddressSpace: addressSpace, Pool: pool, SubPool: subPool, Options: options, V6: v6} res := &api.RequestPoolResponse{} if err := a.call("RequestPool", req, res); err != nil { return "", nil, nil, err } retPool, err := types.ParseCIDR(res.Pool) return res.PoolID, retPool, res.Data, err }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
ipams/remote/remote.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipams/remote/remote.go#L131-L135
go
train
// ReleasePool removes an address pool from the specified address space
func (a *allocator) ReleasePool(poolID string) error
// ReleasePool removes an address pool from the specified address space func (a *allocator) ReleasePool(poolID string) error
{ req := &api.ReleasePoolRequest{PoolID: poolID} res := &api.ReleasePoolResponse{} return a.call("ReleasePool", req, res) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
ipams/remote/remote.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipams/remote/remote.go#L138-L158
go
train
// RequestAddress requests an address from the address pool
func (a *allocator) RequestAddress(poolID string, address net.IP, options map[string]string) (*net.IPNet, map[string]string, error)
// RequestAddress requests an address from the address pool func (a *allocator) RequestAddress(poolID string, address net.IP, options map[string]string) (*net.IPNet, map[string]string, error)
{ var ( prefAddress string retAddress *net.IPNet err error ) if address != nil { prefAddress = address.String() } req := &api.RequestAddressRequest{PoolID: poolID, Address: prefAddress, Options: options} res := &api.RequestAddressResponse{} if err := a.call("RequestAddress", req, res); err != nil { return nil, nil, err } if res.Address != "" { retAddress, err = types.ParseCIDR(res.Address) } else { return nil, nil, ipamapi.ErrNoIPReturned } return retAddress, res.Data, err }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
ipams/remote/remote.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/ipams/remote/remote.go#L161-L169
go
train
// ReleaseAddress releases the address from the specified address pool
func (a *allocator) ReleaseAddress(poolID string, address net.IP) error
// ReleaseAddress releases the address from the specified address pool func (a *allocator) ReleaseAddress(poolID string, address net.IP) error
{ var relAddress string if address != nil { relAddress = address.String() } req := &api.ReleaseAddressRequest{PoolID: poolID, Address: relAddress} res := &api.ReleaseAddressResponse{} return a.call("ReleaseAddress", req, res) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
diagnostic/types.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/diagnostic/types.go#L19-L24
go
train
// FailCommand creates a failure message with error
func FailCommand(err error) *HTTPResult
// FailCommand creates a failure message with error func FailCommand(err error) *HTTPResult
{ return &HTTPResult{ Message: "FAIL", Details: &ErrorCmd{Error: err.Error()}, } }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
diagnostic/types.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/diagnostic/types.go#L27-L32
go
train
// WrongCommand creates a wrong command response
func WrongCommand(message, usage string) *HTTPResult
// WrongCommand creates a wrong command response func WrongCommand(message, usage string) *HTTPResult
{ return &HTTPResult{ Message: message, Details: &UsageCmd{Usage: usage}, } }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
cmd/proxy/main.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/cmd/proxy/main.go#L35-L61
go
train
// parseHostContainerAddrs parses the flags passed on reexec to create the TCP/UDP/SCTP // net.Addrs to map the host and container ports
func parseHostContainerAddrs() (host net.Addr, container net.Addr)
// parseHostContainerAddrs parses the flags passed on reexec to create the TCP/UDP/SCTP // net.Addrs to map the host and container ports func parseHostContainerAddrs() (host net.Addr, container net.Addr)
{ var ( proto = flag.String("proto", "tcp", "proxy protocol") hostIP = flag.String("host-ip", "", "host ip") hostPort = flag.Int("host-port", -1, "host port") containerIP = flag.String("container-ip", "", "container ip") containerPort = flag.Int("container-port", -1, "container port") ) flag.Parse() switch *proto { case "tcp": host = &net.TCPAddr{IP: net.ParseIP(*hostIP), Port: *hostPort} container = &net.TCPAddr{IP: net.ParseIP(*containerIP), Port: *containerPort} case "udp": host = &net.UDPAddr{IP: net.ParseIP(*hostIP), Port: *hostPort} container = &net.UDPAddr{IP: net.ParseIP(*containerIP), Port: *containerPort} case "sctp": host = &sctp.SCTPAddr{IP: []net.IP{net.ParseIP(*hostIP)}, Port: *hostPort} container = &sctp.SCTPAddr{IP: []net.IP{net.ParseIP(*containerIP)}, Port: *containerPort} default: log.Fatalf("unsupported protocol %s", *proto) } return host, container }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
drivers/bridge/bridge.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/bridge/bridge.go#L159-L170
go
train
// Init registers a new instance of bridge driver
func Init(dc driverapi.DriverCallback, config map[string]interface{}) error
// Init registers a new instance of bridge driver func Init(dc driverapi.DriverCallback, config map[string]interface{}) error
{ d := newDriver() if err := d.configure(config); err != nil { return err } c := driverapi.Capability{ DataScope: datastore.LocalScope, ConnectivityScope: datastore.LocalScope, } return dc.RegisterDriver(networkType, d, c) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
drivers/bridge/bridge.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/bridge/bridge.go#L174-L196
go
train
// Validate performs a static validation on the network configuration parameters. // Whatever can be assessed a priori before attempting any programming.
func (c *networkConfiguration) Validate() error
// Validate performs a static validation on the network configuration parameters. // Whatever can be assessed a priori before attempting any programming. func (c *networkConfiguration) Validate() error
{ if c.Mtu < 0 { return ErrInvalidMtu(c.Mtu) } // If bridge v4 subnet is specified if c.AddressIPv4 != nil { // If default gw is specified, it must be part of bridge subnet if c.DefaultGatewayIPv4 != nil { if !c.AddressIPv4.Contains(c.DefaultGatewayIPv4) { return &ErrInvalidGateway{} } } } // If default v6 gw is specified, AddressIPv6 must be specified and gw must belong to AddressIPv6 subnet if c.EnableIPv6 && c.DefaultGatewayIPv6 != nil { if c.AddressIPv6 == nil || !c.AddressIPv6.Contains(c.DefaultGatewayIPv6) { return &ErrInvalidGateway{} } } return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
drivers/bridge/bridge.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/bridge/bridge.go#L199-L222
go
train
// Conflicts check if two NetworkConfiguration objects overlap
func (c *networkConfiguration) Conflicts(o *networkConfiguration) error
// Conflicts check if two NetworkConfiguration objects overlap func (c *networkConfiguration) Conflicts(o *networkConfiguration) error
{ if o == nil { return errors.New("same configuration") } // Also empty, because only one network with empty name is allowed if c.BridgeName == o.BridgeName { return errors.New("networks have same bridge name") } // They must be in different subnets if (c.AddressIPv4 != nil && o.AddressIPv4 != nil) && (c.AddressIPv4.Contains(o.AddressIPv4.IP) || o.AddressIPv4.Contains(c.AddressIPv4.IP)) { return errors.New("networks have overlapping IPv4") } // They must be in different v6 subnets if (c.AddressIPv6 != nil && o.AddressIPv6 != nil) && (c.AddressIPv6.Contains(o.AddressIPv6.IP) || o.AddressIPv6.Contains(c.AddressIPv6.IP)) { return errors.New("networks have overlapping IPv6") } return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
drivers/bridge/bridge.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/bridge/bridge.go#L306-L317
go
train
// Install/Removes the iptables rules needed to isolate this network // from each of the other networks
func (n *bridgeNetwork) isolateNetwork(others []*bridgeNetwork, enable bool) error
// Install/Removes the iptables rules needed to isolate this network // from each of the other networks func (n *bridgeNetwork) isolateNetwork(others []*bridgeNetwork, enable bool) error
{ n.Lock() thisConfig := n.config n.Unlock() if thisConfig.Internal { return nil } // Install the rules to isolate this network against each of the other networks return setINC(thisConfig.BridgeName, enable) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
drivers/bridge/bridge.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/bridge/bridge.go#L509-L518
go
train
// Returns the non link-local IPv6 subnet for the containers attached to this bridge if found, nil otherwise
func getV6Network(config *networkConfiguration, i *bridgeInterface) *net.IPNet
// Returns the non link-local IPv6 subnet for the containers attached to this bridge if found, nil otherwise func getV6Network(config *networkConfiguration, i *bridgeInterface) *net.IPNet
{ if config.AddressIPv6 != nil { return config.AddressIPv6 } if i.bridgeIPv6 != nil && i.bridgeIPv6.IP != nil && !i.bridgeIPv6.IP.IsLinkLocalUnicast() { return i.bridgeIPv6 } return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
drivers/bridge/bridge.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/bridge/bridge.go#L548-L592
go
train
// Create a new network using bridge plugin
func (d *driver) CreateNetwork(id string, option map[string]interface{}, nInfo driverapi.NetworkInfo, ipV4Data, ipV6Data []driverapi.IPAMData) error
// Create a new network using bridge plugin func (d *driver) CreateNetwork(id string, option map[string]interface{}, nInfo driverapi.NetworkInfo, ipV4Data, ipV6Data []driverapi.IPAMData) error
{ if len(ipV4Data) == 0 || ipV4Data[0].Pool.String() == "0.0.0.0/0" { return types.BadRequestErrorf("ipv4 pool is empty") } // Sanity checks d.Lock() if _, ok := d.networks[id]; ok { d.Unlock() return types.ForbiddenErrorf("network %s exists", id) } d.Unlock() // Parse and validate the config. It should not be conflict with existing networks' config config, err := parseNetworkOptions(id, option) if err != nil { return err } if err = config.processIPAM(id, ipV4Data, ipV6Data); err != nil { return err } // start the critical section, from this point onward we are dealing with the list of networks // so to be consistent we cannot allow that the list changes d.configNetwork.Lock() defer d.configNetwork.Unlock() // check network conflicts if err = d.checkConflict(config); err != nil { nerr, ok := err.(defaultBridgeNetworkConflict) if !ok { return err } // Got a conflict with a stale default network, clean that up and continue logrus.Warn(nerr) d.deleteNetwork(nerr.ID) } // there is no conflict, now create the network if err = d.createNetwork(config); err != nil { return err } return d.storeUpdate(config) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
drivers/bridge/bridge.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/bridge/bridge.go#L1180-L1223
go
train
// Join method is invoked when a Sandbox is attached to an endpoint.
func (d *driver) Join(nid, eid string, sboxKey string, jinfo driverapi.JoinInfo, options map[string]interface{}) error
// Join method is invoked when a Sandbox is attached to an endpoint. func (d *driver) Join(nid, eid string, sboxKey string, jinfo driverapi.JoinInfo, options map[string]interface{}) error
{ defer osl.InitOSContext()() network, err := d.getNetwork(nid) if err != nil { return err } endpoint, err := network.getEndpoint(eid) if err != nil { return err } if endpoint == nil { return EndpointNotFoundError(eid) } endpoint.containerConfig, err = parseContainerOptions(options) if err != nil { return err } iNames := jinfo.InterfaceName() containerVethPrefix := defaultContainerVethPrefix if network.config.ContainerIfacePrefix != "" { containerVethPrefix = network.config.ContainerIfacePrefix } err = iNames.SetNames(endpoint.srcName, containerVethPrefix) if err != nil { return err } err = jinfo.SetGateway(network.bridge.gatewayIPv4) if err != nil { return err } err = jinfo.SetGatewayIPv6(network.bridge.gatewayIPv6) if err != nil { return err } return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
drivers/bridge/bridge.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/bridge/bridge.go#L1226-L1250
go
train
// Leave method is invoked when a Sandbox detaches from an endpoint.
func (d *driver) Leave(nid, eid string) error
// Leave method is invoked when a Sandbox detaches from an endpoint. func (d *driver) Leave(nid, eid string) error
{ defer osl.InitOSContext()() network, err := d.getNetwork(nid) if err != nil { return types.InternalMaskableErrorf("%s", err) } endpoint, err := network.getEndpoint(eid) if err != nil { return err } if endpoint == nil { return EndpointNotFoundError(eid) } if !network.config.EnableICC { if err = d.link(network, endpoint, false); err != nil { return err } } return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
service.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/service.go#L67-L69
go
train
// assignIPToEndpoint inserts the mapping between the IP and the endpoint identifier // returns true if the mapping was not present, false otherwise // returns also the number of endpoints associated to the IP
func (s *service) assignIPToEndpoint(ip, eID string) (bool, int)
// assignIPToEndpoint inserts the mapping between the IP and the endpoint identifier // returns true if the mapping was not present, false otherwise // returns also the number of endpoints associated to the IP func (s *service) assignIPToEndpoint(ip, eID string) (bool, int)
{ return s.ipToEndpoint.Insert(ip, eID) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
service.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/service.go#L74-L76
go
train
// removeIPToEndpoint removes the mapping between the IP and the endpoint identifier // returns true if the mapping was deleted, false otherwise // returns also the number of endpoints associated to the IP
func (s *service) removeIPToEndpoint(ip, eID string) (bool, int)
// removeIPToEndpoint removes the mapping between the IP and the endpoint identifier // returns true if the mapping was deleted, false otherwise // returns also the number of endpoints associated to the IP func (s *service) removeIPToEndpoint(ip, eID string) (bool, int)
{ return s.ipToEndpoint.Remove(ip, eID) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
options/options.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/options/options.go#L58-L88
go
train
// GenerateFromModel takes the generic options, and tries to build a new // instance of the model's type by matching keys from the generic options to // fields in the model. // // The return value is of the same type than the model (including a potential // pointer qualifier).
func GenerateFromModel(options Generic, model interface{}) (interface{}, error)
// GenerateFromModel takes the generic options, and tries to build a new // instance of the model's type by matching keys from the generic options to // fields in the model. // // The return value is of the same type than the model (including a potential // pointer qualifier). func GenerateFromModel(options Generic, model interface{}) (interface{}, error)
{ modType := reflect.TypeOf(model) // If the model is of pointer type, we need to dereference for New. resType := reflect.TypeOf(model) if modType.Kind() == reflect.Ptr { resType = resType.Elem() } // Populate the result structure with the generic layout content. res := reflect.New(resType) for name, value := range options { field := res.Elem().FieldByName(name) if !field.IsValid() { return nil, NoSuchFieldError{name, resType.String()} } if !field.CanSet() { return nil, CannotSetFieldError{name, resType.String()} } if reflect.TypeOf(value) != field.Type() { return nil, TypeMismatchError{name, field.Type().String(), reflect.TypeOf(value).String()} } field.Set(reflect.ValueOf(value)) } // If the model is not of pointer type, return content of the result. if modType.Kind() == reflect.Ptr { return res.Interface(), nil } return res.Elem().Interface(), nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
controller.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/controller.go#L189-L256
go
train
// New creates a new instance of network controller.
func New(cfgOptions ...config.Option) (NetworkController, error)
// New creates a new instance of network controller. func New(cfgOptions ...config.Option) (NetworkController, error)
{ c := &controller{ id: stringid.GenerateRandomID(), cfg: config.ParseConfigOptions(cfgOptions...), sandboxes: sandboxTable{}, svcRecords: make(map[string]svcInfo), serviceBindings: make(map[serviceKey]*service), agentInitDone: make(chan struct{}), networkLocker: locker.New(), DiagnosticServer: diagnostic.New(), } c.DiagnosticServer.Init() if err := c.initStores(); err != nil { return nil, err } drvRegistry, err := drvregistry.New(c.getStore(datastore.LocalScope), c.getStore(datastore.GlobalScope), c.RegisterDriver, nil, c.cfg.PluginGetter) if err != nil { return nil, err } for _, i := range getInitializers(c.cfg.Daemon.Experimental) { var dcfg map[string]interface{} // External plugins don't need config passed through daemon. They can // bootstrap themselves if i.ntype != "remote" { dcfg = c.makeDriverConfig(i.ntype) } if err := drvRegistry.AddDriver(i.ntype, i.fn, dcfg); err != nil { return nil, err } } if err = initIPAMDrivers(drvRegistry, nil, c.getStore(datastore.GlobalScope), c.cfg.Daemon.DefaultAddressPool); err != nil { return nil, err } c.drvRegistry = drvRegistry if c.cfg != nil && c.cfg.Cluster.Watcher != nil { if err := c.initDiscovery(c.cfg.Cluster.Watcher); err != nil { // Failing to initialize discovery is a bad situation to be in. // But it cannot fail creating the Controller logrus.Errorf("Failed to Initialize Discovery : %v", err) } } c.WalkNetworks(populateSpecial) // Reserve pools first before doing cleanup. Otherwise the // cleanups of endpoint/network and sandbox below will // generate many unnecessary warnings c.reservePools() // Cleanup resources c.sandboxCleanup(c.cfg.ActiveSandboxes) c.cleanupLocalEndpoints() c.networkCleanup() if err := c.startExternalKeyListener(); err != nil { return nil, err } return c, nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
controller.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/controller.go#L285-L309
go
train
// libnetwork side of agent depends on the keys. On the first receipt of // keys setup the agent. For subsequent key set handle the key change
func (c *controller) SetKeys(keys []*types.EncryptionKey) error
// libnetwork side of agent depends on the keys. On the first receipt of // keys setup the agent. For subsequent key set handle the key change func (c *controller) SetKeys(keys []*types.EncryptionKey) error
{ subsysKeys := make(map[string]int) for _, key := range keys { if key.Subsystem != subsysGossip && key.Subsystem != subsysIPSec { return fmt.Errorf("key received for unrecognized subsystem") } subsysKeys[key.Subsystem]++ } for s, count := range subsysKeys { if count != keyringSize { return fmt.Errorf("incorrect number of keys for subsystem %v", s) } } agent := c.getAgent() if agent == nil { c.Lock() c.keys = keys c.Unlock() return nil } return c.handleKeyChange(keys) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
controller.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/controller.go#L367-L375
go
train
// AgentInitWait waits for agent initialization to be completed in the controller.
func (c *controller) AgentInitWait()
// AgentInitWait waits for agent initialization to be completed in the controller. func (c *controller) AgentInitWait()
{ c.Lock() agentInitDone := c.agentInitDone c.Unlock() if agentInitDone != nil { <-agentInitDone } }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
controller.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/controller.go#L378-L385
go
train
// AgentStopWait waits for the Agent stop to be completed in the controller
func (c *controller) AgentStopWait()
// AgentStopWait waits for the Agent stop to be completed in the controller func (c *controller) AgentStopWait()
{ c.Lock() agentStopDone := c.agentStopDone c.Unlock() if agentStopDone != nil { <-agentStopDone } }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
controller.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/controller.go#L388-L397
go
train
// agentOperationStart marks the start of an Agent Init or Agent Stop
func (c *controller) agentOperationStart()
// agentOperationStart marks the start of an Agent Init or Agent Stop func (c *controller) agentOperationStart()
{ c.Lock() if c.agentInitDone == nil { c.agentInitDone = make(chan struct{}) } if c.agentStopDone == nil { c.agentStopDone = make(chan struct{}) } c.Unlock() }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
controller.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/controller.go#L400-L407
go
train
// agentInitComplete notifies the successful completion of the Agent initialization
func (c *controller) agentInitComplete()
// agentInitComplete notifies the successful completion of the Agent initialization func (c *controller) agentInitComplete()
{ c.Lock() if c.agentInitDone != nil { close(c.agentInitDone) c.agentInitDone = nil } c.Unlock() }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
controller.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/controller.go#L410-L417
go
train
// agentStopComplete notifies the successful completion of the Agent stop
func (c *controller) agentStopComplete()
// agentStopComplete notifies the successful completion of the Agent stop func (c *controller) agentStopComplete()
{ c.Lock() if c.agentStopDone != nil { close(c.agentStopDone) c.agentStopDone = nil } c.Unlock() }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
controller.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/controller.go#L708-L908
go
train
// NewNetwork creates a new network of the specified network type. The options // are network specific and modeled in a generic way.
func (c *controller) NewNetwork(networkType, name string, id string, options ...NetworkOption) (Network, error)
// NewNetwork creates a new network of the specified network type. The options // are network specific and modeled in a generic way. func (c *controller) NewNetwork(networkType, name string, id string, options ...NetworkOption) (Network, error)
{ if id != "" { c.networkLocker.Lock(id) defer c.networkLocker.Unlock(id) if _, err := c.NetworkByID(id); err == nil { return nil, NetworkNameError(id) } } if !config.IsValidName(name) { return nil, ErrInvalidName(name) } if id == "" { id = stringid.GenerateRandomID() } defaultIpam := defaultIpamForNetworkType(networkType) // Construct the network object network := &network{ name: name, networkType: networkType, generic: map[string]interface{}{netlabel.GenericData: make(map[string]string)}, ipamType: defaultIpam, id: id, created: time.Now(), ctrlr: c, persist: true, drvOnce: &sync.Once{}, loadBalancerMode: loadBalancerModeDefault, } network.processOptions(options...) if err := network.validateConfiguration(); err != nil { return nil, err } var ( cap *driverapi.Capability err error ) // Reset network types, force local scope and skip allocation and // plumbing for configuration networks. Reset of the config-only // network drivers is needed so that this special network is not // usable by old engine versions. if network.configOnly { network.scope = datastore.LocalScope network.networkType = "null" goto addToStore } _, cap, err = network.resolveDriver(network.networkType, true) if err != nil { return nil, err } if network.scope == datastore.LocalScope && cap.DataScope == datastore.GlobalScope { return nil, types.ForbiddenErrorf("cannot downgrade network scope for %s networks", networkType) } if network.ingress && cap.DataScope != datastore.GlobalScope { return nil, types.ForbiddenErrorf("Ingress network can only be global scope network") } // At this point the network scope is still unknown if not set by user if (cap.DataScope == datastore.GlobalScope || network.scope == datastore.SwarmScope) && !c.isDistributedControl() && !network.dynamic { if c.isManager() { // For non-distributed controlled environment, globalscoped non-dynamic networks are redirected to Manager return nil, ManagerRedirectError(name) } return nil, types.ForbiddenErrorf("Cannot create a multi-host network from a worker node. Please create the network from a manager node.") } if network.scope == datastore.SwarmScope && c.isDistributedControl() { return nil, types.ForbiddenErrorf("cannot create a swarm scoped network when swarm is not active") } // Make sure we have a driver available for this network type // before we allocate anything. if _, err := network.driver(true); err != nil { return nil, err } // From this point on, we need the network specific configuration, // which may come from a configuration-only network if network.configFrom != "" { t, err := c.getConfigNetwork(network.configFrom) if err != nil { return nil, types.NotFoundErrorf("configuration network %q does not exist", network.configFrom) } if err := t.applyConfigurationTo(network); err != nil { return nil, types.InternalErrorf("Failed to apply configuration: %v", err) } defer func() { if err == nil { if err := t.getEpCnt().IncEndpointCnt(); err != nil { logrus.Warnf("Failed to update reference count for configuration network %q on creation of network %q: %v", t.Name(), network.Name(), err) } } }() } err = network.ipamAllocate() if err != nil { return nil, err } defer func() { if err != nil { network.ipamRelease() } }() err = c.addNetwork(network) if err != nil { return nil, err } defer func() { if err != nil { if e := network.deleteNetwork(); e != nil { logrus.Warnf("couldn't roll back driver network on network %s creation failure: %v", network.name, err) } } }() // XXX If the driver type is "overlay" check the options for DSR // being set. If so, set the network's load balancing mode to DSR. // This should really be done in a network option, but due to // time pressure to get this in without adding changes to moby, // swarm and CLI, it is being implemented as a driver-specific // option. Unfortunately, drivers can't influence the core // "libnetwork.network" data type. Hence we need this hack code // to implement in this manner. if gval, ok := network.generic[netlabel.GenericData]; ok && network.networkType == "overlay" { optMap := gval.(map[string]string) if _, ok := optMap[overlayDSROptionString]; ok { network.loadBalancerMode = loadBalancerModeDSR } } addToStore: // First store the endpoint count, then the network. To avoid to // end up with a datastore containing a network and not an epCnt, // in case of an ungraceful shutdown during this function call. epCnt := &endpointCnt{n: network} if err = c.updateToStore(epCnt); err != nil { return nil, err } defer func() { if err != nil { if e := c.deleteFromStore(epCnt); e != nil { logrus.Warnf("could not rollback from store, epCnt %v on failure (%v): %v", epCnt, err, e) } } }() network.epCnt = epCnt if err = c.updateToStore(network); err != nil { return nil, err } defer func() { if err != nil { if e := c.deleteFromStore(network); e != nil { logrus.Warnf("could not rollback from store, network %v on failure (%v): %v", network, err, e) } } }() if network.configOnly { return network, nil } joinCluster(network) defer func() { if err != nil { network.cancelDriverWatches() if e := network.leaveCluster(); e != nil { logrus.Warnf("Failed to leave agent cluster on network %s on failure (%v): %v", network.name, err, e) } } }() if network.hasLoadBalancerEndpoint() { if err = network.createLoadBalancerSandbox(); err != nil { return nil, err } } if !c.isDistributedControl() { c.Lock() arrangeIngressFilterRule() c.Unlock() } c.arrangeUserFilterRule() return network, nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
controller.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/controller.go#L1070-L1190
go
train
// NewSandbox creates a new sandbox for the passed container id
func (c *controller) NewSandbox(containerID string, options ...SandboxOption) (Sandbox, error)
// NewSandbox creates a new sandbox for the passed container id func (c *controller) NewSandbox(containerID string, options ...SandboxOption) (Sandbox, error)
{ if containerID == "" { return nil, types.BadRequestErrorf("invalid container ID") } var sb *sandbox c.Lock() for _, s := range c.sandboxes { if s.containerID == containerID { // If not a stub, then we already have a complete sandbox. if !s.isStub { sbID := s.ID() c.Unlock() return nil, types.ForbiddenErrorf("container %s is already present in sandbox %s", containerID, sbID) } // We already have a stub sandbox from the // store. Make use of it so that we don't lose // the endpoints from store but reset the // isStub flag. sb = s sb.isStub = false break } } c.Unlock() sandboxID := stringid.GenerateRandomID() if runtime.GOOS == "windows" { sandboxID = containerID } // Create sandbox and process options first. Key generation depends on an option if sb == nil { sb = &sandbox{ id: sandboxID, containerID: containerID, endpoints: []*endpoint{}, epPriority: map[string]int{}, populatedEndpoints: map[string]struct{}{}, config: containerConfig{}, controller: c, extDNS: []extDNSEntry{}, } } sb.processOptions(options...) c.Lock() if sb.ingress && c.ingressSandbox != nil { c.Unlock() return nil, types.ForbiddenErrorf("ingress sandbox already present") } if sb.ingress { c.ingressSandbox = sb sb.config.hostsPath = filepath.Join(c.cfg.Daemon.DataDir, "/network/files/hosts") sb.config.resolvConfPath = filepath.Join(c.cfg.Daemon.DataDir, "/network/files/resolv.conf") sb.id = "ingress_sbox" } else if sb.loadBalancerNID != "" { sb.id = "lb_" + sb.loadBalancerNID } c.Unlock() var err error defer func() { if err != nil { c.Lock() if sb.ingress { c.ingressSandbox = nil } c.Unlock() } }() if err = sb.setupResolutionFiles(); err != nil { return nil, err } if sb.config.useDefaultSandBox { c.sboxOnce.Do(func() { c.defOsSbox, err = osl.NewSandbox(sb.Key(), false, false) }) if err != nil { c.sboxOnce = sync.Once{} return nil, fmt.Errorf("failed to create default sandbox: %v", err) } sb.osSbox = c.defOsSbox } if sb.osSbox == nil && !sb.config.useExternalKey { if sb.osSbox, err = osl.NewSandbox(sb.Key(), !sb.config.useDefaultSandBox, false); err != nil { return nil, fmt.Errorf("failed to create new osl sandbox: %v", err) } } if sb.osSbox != nil { // Apply operating specific knobs on the load balancer sandbox sb.osSbox.ApplyOSTweaks(sb.oslTypes) } c.Lock() c.sandboxes[sb.id] = sb c.Unlock() defer func() { if err != nil { c.Lock() delete(c.sandboxes, sb.id) c.Unlock() } }() err = sb.storeUpdate() if err != nil { return nil, fmt.Errorf("failed to update the store state of sandbox: %v", err) } return sb, nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
controller.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/controller.go#L1231-L1248
go
train
// SandboxDestroy destroys a sandbox given a container ID
func (c *controller) SandboxDestroy(id string) error
// SandboxDestroy destroys a sandbox given a container ID func (c *controller) SandboxDestroy(id string) error
{ var sb *sandbox c.Lock() for _, s := range c.sandboxes { if s.containerID == id { sb = s break } } c.Unlock() // It is not an error if sandbox is not available if sb == nil { return nil } return sb.Delete() }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
controller.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/controller.go#L1251-L1259
go
train
// SandboxContainerWalker returns a Sandbox Walker function which looks for an existing Sandbox with the passed containerID
func SandboxContainerWalker(out *Sandbox, containerID string) SandboxWalker
// SandboxContainerWalker returns a Sandbox Walker function which looks for an existing Sandbox with the passed containerID func SandboxContainerWalker(out *Sandbox, containerID string) SandboxWalker
{ return func(sb Sandbox) bool { if sb.ContainerID() == containerID { *out = sb return true } return false } }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
controller.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/controller.go#L1262-L1270
go
train
// SandboxKeyWalker returns a Sandbox Walker function which looks for an existing Sandbox with the passed key
func SandboxKeyWalker(out *Sandbox, key string) SandboxWalker
// SandboxKeyWalker returns a Sandbox Walker function which looks for an existing Sandbox with the passed key func SandboxKeyWalker(out *Sandbox, key string) SandboxWalker
{ return func(sb Sandbox) bool { if sb.Key() == key { *out = sb return true } return false } }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
controller.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/controller.go#L1335-L1341
go
train
// StartDiagnostic start the network dias mode
func (c *controller) StartDiagnostic(port int)
// StartDiagnostic start the network dias mode func (c *controller) StartDiagnostic(port int)
{ c.Lock() if !c.DiagnosticServer.IsDiagnosticEnabled() { c.DiagnosticServer.EnableDiagnostic("127.0.0.1", port) } c.Unlock() }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
controller.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/controller.go#L1344-L1350
go
train
// StopDiagnostic start the network dias mode
func (c *controller) StopDiagnostic()
// StopDiagnostic start the network dias mode func (c *controller) StopDiagnostic()
{ c.Lock() if c.DiagnosticServer.IsDiagnosticEnabled() { c.DiagnosticServer.DisableDiagnostic() } c.Unlock() }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
controller.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/controller.go#L1353-L1357
go
train
// IsDiagnosticEnabled returns true if the dias is enabled
func (c *controller) IsDiagnosticEnabled() bool
// IsDiagnosticEnabled returns true if the dias is enabled func (c *controller) IsDiagnosticEnabled() bool
{ c.Lock() defer c.Unlock() return c.DiagnosticServer.IsDiagnosticEnabled() }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
drivers/overlay/ov_network.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/overlay/ov_network.go#L374-L412
go
train
// to be called while holding network lock
func (n *network) destroySandbox()
// to be called while holding network lock func (n *network) destroySandbox()
{ if n.sbox != nil { for _, iface := range n.sbox.Info().Interfaces() { if err := iface.Remove(); err != nil { logrus.Debugf("Remove interface %s failed: %v", iface.SrcName(), err) } } for _, s := range n.subnets { if hostMode { if err := removeFilters(n.id[:12], s.brName); err != nil { logrus.Warnf("Could not remove overlay filters: %v", err) } } if s.vxlanName != "" { err := deleteInterface(s.vxlanName) if err != nil { logrus.Warnf("could not cleanup sandbox properly: %v", err) } } } if hostMode { if err := removeNetworkChain(n.id[:12]); err != nil { logrus.Warnf("could not remove network chain: %v", err) } } // Close the netlink socket, this will also release the watchMiss goroutine that is using it if n.nlSocket != nil { n.nlSocket.Close() n.nlSocket = nil } n.sbox.Destroy() n.sbox = nil } }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
drivers/overlay/ov_network.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/overlay/ov_network.go#L662-L680
go
train
// Must be called with the network lock
func (n *network) initSubnetSandbox(s *subnet, restore bool) error
// Must be called with the network lock func (n *network) initSubnetSandbox(s *subnet, restore bool) error
{ brName := n.generateBridgeName(s) vxlanName := n.generateVxlanName(s) if restore { if err := n.restoreSubnetSandbox(s, brName, vxlanName); err != nil { return err } } else { if err := n.setupSubnetSandbox(s, brName, vxlanName); err != nil { return err } } s.vxlanName = vxlanName s.brName = brName return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
drivers/overlay/ov_network.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/overlay/ov_network.go#L863-L871
go
train
// Restore a network from the store to the driver if it is present. // Must be called with the driver locked!
func (d *driver) restoreNetworkFromStore(nid string) *network
// Restore a network from the store to the driver if it is present. // Must be called with the driver locked! func (d *driver) restoreNetworkFromStore(nid string) *network
{ n := d.getNetworkFromStore(nid) if n != nil { n.driver = d n.endpoints = endpointTable{} d.networks[nid] = n } return n }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
drivers/ipvlan/ipvlan_network.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/ipvlan/ipvlan_network.go#L18-L76
go
train
// CreateNetwork the network for the specified driver type
func (d *driver) CreateNetwork(nid string, option map[string]interface{}, nInfo driverapi.NetworkInfo, ipV4Data, ipV6Data []driverapi.IPAMData) error
// CreateNetwork the network for the specified driver type func (d *driver) CreateNetwork(nid string, option map[string]interface{}, nInfo driverapi.NetworkInfo, ipV4Data, ipV6Data []driverapi.IPAMData) error
{ defer osl.InitOSContext()() kv, err := kernel.GetKernelVersion() if err != nil { return fmt.Errorf("Failed to check kernel version for %s driver support: %v", ipvlanType, err) } // ensure Kernel version is >= v4.2 for ipvlan support if kv.Kernel < ipvlanKernelVer || (kv.Kernel == ipvlanKernelVer && kv.Major < ipvlanMajorVer) { return fmt.Errorf("kernel version failed to meet the minimum ipvlan kernel requirement of %d.%d, found %d.%d.%d", ipvlanKernelVer, ipvlanMajorVer, kv.Kernel, kv.Major, kv.Minor) } // reject a null v4 network if len(ipV4Data) == 0 || ipV4Data[0].Pool.String() == "0.0.0.0/0" { return fmt.Errorf("ipv4 pool is empty") } // parse and validate the config and bind to networkConfiguration config, err := parseNetworkOptions(nid, option) if err != nil { return err } config.ID = nid err = config.processIPAM(nid, ipV4Data, ipV6Data) if err != nil { return err } // verify the ipvlan mode from -o ipvlan_mode option switch config.IpvlanMode { case "", modeL2: // default to ipvlan L2 mode if -o ipvlan_mode is empty config.IpvlanMode = modeL2 case modeL3: config.IpvlanMode = modeL3 default: return fmt.Errorf("requested ipvlan mode '%s' is not valid, 'l2' mode is the ipvlan driver default", config.IpvlanMode) } // loopback is not a valid parent link if config.Parent == "lo" { return fmt.Errorf("loopback interface is not a valid %s parent link", ipvlanType) } // if parent interface not specified, create a dummy type link to use named dummy+net_id if config.Parent == "" { config.Parent = getDummyName(stringid.TruncateID(config.ID)) // empty parent and --internal are handled the same. Set here to update k/v config.Internal = true } err = d.createNetwork(config) if err != nil { return err } // update persistent db, rollback on fail err = d.storeUpdate(config) if err != nil { d.deleteNetwork(config.ID) logrus.Debugf("encountered an error rolling back a network create for %s : %v", config.ID, err) return err } return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
drivers/ipvlan/ipvlan_network.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/ipvlan/ipvlan_network.go#L79-L121
go
train
// createNetwork is used by new network callbacks and persistent network cache
func (d *driver) createNetwork(config *configuration) error
// createNetwork is used by new network callbacks and persistent network cache func (d *driver) createNetwork(config *configuration) error
{ networkList := d.getNetworks() for _, nw := range networkList { if config.Parent == nw.config.Parent { return fmt.Errorf("network %s is already using parent interface %s", getDummyName(stringid.TruncateID(nw.config.ID)), config.Parent) } } if !parentExists(config.Parent) { // if the --internal flag is set, create a dummy link if config.Internal { err := createDummyLink(config.Parent, getDummyName(stringid.TruncateID(config.ID))) if err != nil { return err } config.CreatedSlaveLink = true // notify the user in logs they have limited communications if config.Parent == getDummyName(stringid.TruncateID(config.ID)) { logrus.Debugf("Empty -o parent= and --internal flags limit communications to other containers inside of network: %s", config.Parent) } } else { // if the subinterface parent_iface.vlan_id checks do not pass, return err. // a valid example is 'eth0.10' for a parent iface 'eth0' with a vlan id '10' err := createVlanLink(config.Parent) if err != nil { return err } // if driver created the networks slave link, record it for future deletion config.CreatedSlaveLink = true } } n := &network{ id: config.ID, driver: d, endpoints: endpointTable{}, config: config, } // add the *network d.addNetwork(n) return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
drivers/ipvlan/ipvlan_network.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/ipvlan/ipvlan_network.go#L124-L170
go
train
// DeleteNetwork the network for the specified driver type
func (d *driver) DeleteNetwork(nid string) error
// DeleteNetwork the network for the specified driver type func (d *driver) DeleteNetwork(nid string) error
{ defer osl.InitOSContext()() n := d.network(nid) if n == nil { return fmt.Errorf("network id %s not found", nid) } // if the driver created the slave interface, delete it, otherwise leave it if ok := n.config.CreatedSlaveLink; ok { // if the interface exists, only delete if it matches iface.vlan or dummy.net_id naming if ok := parentExists(n.config.Parent); ok { // only delete the link if it is named the net_id if n.config.Parent == getDummyName(stringid.TruncateID(nid)) { err := delDummyLink(n.config.Parent) if err != nil { logrus.Debugf("link %s was not deleted, continuing the delete network operation: %v", n.config.Parent, err) } } else { // only delete the link if it matches iface.vlan naming err := delVlanLink(n.config.Parent) if err != nil { logrus.Debugf("link %s was not deleted, continuing the delete network operation: %v", n.config.Parent, err) } } } } for _, ep := range n.endpoints { if link, err := ns.NlHandle().LinkByName(ep.srcName); err == nil { if err := ns.NlHandle().LinkDel(link); err != nil { logrus.WithError(err).Warnf("Failed to delete interface (%s)'s link on endpoint (%s) delete", ep.srcName, ep.id) } } if err := d.storeDelete(ep); err != nil { logrus.Warnf("Failed to remove ipvlan endpoint %.7s from store: %v", ep.id, err) } } // delete the *network d.deleteNetwork(nid) // delete the network record from persistent cache err := d.storeDelete(n.config) if err != nil { return fmt.Errorf("error deleting deleting id %s from datastore: %v", nid, err) } return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
drivers/ipvlan/ipvlan_network.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/ipvlan/ipvlan_network.go#L173-L191
go
train
// parseNetworkOptions parse docker network options
func parseNetworkOptions(id string, option options.Generic) (*configuration, error)
// parseNetworkOptions parse docker network options func parseNetworkOptions(id string, option options.Generic) (*configuration, error)
{ var ( err error config = &configuration{} ) // parse generic labels first if genData, ok := option[netlabel.GenericData]; ok && genData != nil { if config, err = parseNetworkGenericOptions(genData); err != nil { return nil, err } } // setting the parent to "" will trigger an isolated network dummy parent link if _, ok := option[netlabel.Internal]; ok { config.Internal = true // empty --parent= and --internal are handled the same. config.Parent = "" } return config, nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
drivers/ipvlan/ipvlan_network.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/ipvlan/ipvlan_network.go#L194-L214
go
train
// parseNetworkGenericOptions parse generic driver docker network options
func parseNetworkGenericOptions(data interface{}) (*configuration, error)
// parseNetworkGenericOptions parse generic driver docker network options func parseNetworkGenericOptions(data interface{}) (*configuration, error)
{ var ( err error config *configuration ) switch opt := data.(type) { case *configuration: config = opt case map[string]string: config = &configuration{} err = config.fromOptions(opt) case options.Generic: var opaqueConfig interface{} if opaqueConfig, err = options.GenerateFromModel(opt, config); err == nil { config = opaqueConfig.(*configuration) } default: err = types.BadRequestErrorf("unrecognized network configuration format: %v", opt) } return config, err }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
drivers/ipvlan/ipvlan_network.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/ipvlan/ipvlan_network.go#L217-L229
go
train
// fromOptions binds the generic options to networkConfiguration to cache
func (config *configuration) fromOptions(labels map[string]string) error
// fromOptions binds the generic options to networkConfiguration to cache func (config *configuration) fromOptions(labels map[string]string) error
{ for label, value := range labels { switch label { case parentOpt: // parse driver option '-o parent' config.Parent = value case driverModeOpt: // parse driver option '-o ipvlan_mode' config.IpvlanMode = value } } return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
drivers/ipvlan/ipvlan_network.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/drivers/ipvlan/ipvlan_network.go#L232-L252
go
train
// processIPAM parses v4 and v6 IP information and binds it to the network configuration
func (config *configuration) processIPAM(id string, ipamV4Data, ipamV6Data []driverapi.IPAMData) error
// processIPAM parses v4 and v6 IP information and binds it to the network configuration func (config *configuration) processIPAM(id string, ipamV4Data, ipamV6Data []driverapi.IPAMData) error
{ if len(ipamV4Data) > 0 { for _, ipd := range ipamV4Data { s := &ipv4Subnet{ SubnetIP: ipd.Pool.String(), GwIP: ipd.Gateway.String(), } config.Ipv4Subnets = append(config.Ipv4Subnets, s) } } if len(ipamV6Data) > 0 { for _, ipd := range ipamV6Data { s := &ipv6Subnet{ SubnetIP: ipd.Pool.String(), GwIP: ipd.Gateway.String(), } config.Ipv6Subnets = append(config.Ipv6Subnets, s) } } return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
hostdiscovery/hostdiscovery.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/hostdiscovery/hostdiscovery.go#L33-L35
go
train
// NewHostDiscovery function creates a host discovery object
func NewHostDiscovery(watcher discovery.Watcher) HostDiscovery
// NewHostDiscovery function creates a host discovery object func NewHostDiscovery(watcher discovery.Watcher) HostDiscovery
{ return &hostDiscovery{watcher: watcher, nodes: mapset.NewSet(), stopChan: make(chan struct{})} }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
driverapi/ipamdata.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/driverapi/ipamdata.go#L12-L29
go
train
// MarshalJSON encodes IPAMData into json message
func (i *IPAMData) MarshalJSON() ([]byte, error)
// MarshalJSON encodes IPAMData into json message func (i *IPAMData) MarshalJSON() ([]byte, error)
{ m := map[string]interface{}{} m["AddressSpace"] = i.AddressSpace if i.Pool != nil { m["Pool"] = i.Pool.String() } if i.Gateway != nil { m["Gateway"] = i.Gateway.String() } if i.AuxAddresses != nil { am := make(map[string]string, len(i.AuxAddresses)) for k, v := range i.AuxAddresses { am[k] = v.String() } m["AuxAddresses"] = am } return json.Marshal(m) }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
driverapi/ipamdata.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/driverapi/ipamdata.go#L32-L65
go
train
// UnmarshalJSON decodes a json message into IPAMData
func (i *IPAMData) UnmarshalJSON(data []byte) error
// UnmarshalJSON decodes a json message into IPAMData func (i *IPAMData) UnmarshalJSON(data []byte) error
{ var ( m map[string]interface{} err error ) if err := json.Unmarshal(data, &m); err != nil { return err } i.AddressSpace = m["AddressSpace"].(string) if v, ok := m["Pool"]; ok { if i.Pool, err = types.ParseCIDR(v.(string)); err != nil { return err } } if v, ok := m["Gateway"]; ok { if i.Gateway, err = types.ParseCIDR(v.(string)); err != nil { return err } } if v, ok := m["AuxAddresses"]; ok { b, _ := json.Marshal(v) var am map[string]string if err = json.Unmarshal(b, &am); err != nil { return err } i.AuxAddresses = make(map[string]*net.IPNet, len(am)) for k, v := range am { if i.AuxAddresses[k], err = types.ParseCIDR(v); err != nil { return err } } } return nil }
docker/libnetwork
9ff9b57c344df5cd47443ad9e65702ec85c5aeb0
driverapi/ipamdata.go
https://github.com/docker/libnetwork/blob/9ff9b57c344df5cd47443ad9e65702ec85c5aeb0/driverapi/ipamdata.go#L68-L94
go
train
// Validate checks whether the IPAMData structure contains congruent data
func (i *IPAMData) Validate() error
// Validate checks whether the IPAMData structure contains congruent data func (i *IPAMData) Validate() error
{ var isV6 bool if i.Pool == nil { return types.BadRequestErrorf("invalid pool") } if i.Gateway == nil { return types.BadRequestErrorf("invalid gateway address") } isV6 = i.IsV6() if isV6 && i.Gateway.IP.To4() != nil || !isV6 && i.Gateway.IP.To4() == nil { return types.BadRequestErrorf("incongruent ip versions for pool and gateway") } for k, sip := range i.AuxAddresses { if isV6 && sip.IP.To4() != nil || !isV6 && sip.IP.To4() == nil { return types.BadRequestErrorf("incongruent ip versions for pool and secondary ip address %s", k) } } if !i.Pool.Contains(i.Gateway.IP) { return types.BadRequestErrorf("invalid gateway address (%s) does not belong to the pool (%s)", i.Gateway, i.Pool) } for k, sip := range i.AuxAddresses { if !i.Pool.Contains(sip.IP) { return types.BadRequestErrorf("invalid secondary address %s (%s) does not belong to the pool (%s)", k, i.Gateway, i.Pool) } } return nil }