// NetworkConfigsToStateArgs splits the given networkConfig into a slice of
// state.LinkLayerDeviceArgs and a slice of state.LinkLayerDeviceAddress. The
// input is expected to come from MergeProviderAndObservedNetworkConfigs and to
// be sorted.
770118
func NetworkConfigsToStateArgs(networkConfig []params.NetworkConfig) (
	[]state.LinkLayerDeviceArgs,
	[]state.LinkLayerDeviceAddress,
) {
	var devicesArgs []state.LinkLayerDeviceArgs
	var devicesAddrs []state.LinkLayerDeviceAddress

	logger.Tracef("transforming network config to state args: %+v", networkConfig)
	seenDeviceNames := set.NewStrings()
	for _, netConfig := range networkConfig {
		logger.Tracef("transforming device %q", netConfig.InterfaceName)
		if !seenDeviceNames.Contains(netConfig.InterfaceName) {
			// First time we see this, add it to devicesArgs.
			seenDeviceNames.Add(netConfig.InterfaceName)
			var mtu uint
			if netConfig.MTU >= 0 {
				mtu = uint(netConfig.MTU)
			}
			args := state.LinkLayerDeviceArgs{
				Name:        netConfig.InterfaceName,
				MTU:         mtu,
				ProviderID:  network.Id(netConfig.ProviderId),
				Type:        state.LinkLayerDeviceType(netConfig.InterfaceType),
				MACAddress:  netConfig.MACAddress,
				IsAutoStart: !netConfig.NoAutoStart,
				IsUp:        !netConfig.Disabled,
				ParentName:  netConfig.ParentInterfaceName,
			}
			logger.Tracef("state device args for device: %+v", args)
			devicesArgs = append(devicesArgs, args)
		}

		if netConfig.CIDR == "" || netConfig.Address == "" {
			logger.Tracef(
				"skipping empty CIDR %q and/or Address %q of %q",
				netConfig.CIDR, netConfig.Address, netConfig.InterfaceName,
			)
			continue
		}
		_, ipNet, err := net.ParseCIDR(netConfig.CIDR)
		if err != nil {
			logger.Warningf("FIXME: ignoring unexpected CIDR format %q: %v", netConfig.CIDR, err)
			continue
		}
		ipAddr := net.ParseIP(netConfig.Address)
		if ipAddr == nil {
			logger.Warningf("FIXME: ignoring unexpected Address format %q", netConfig.Address)
			continue
		}
		ipNet.IP = ipAddr
		cidrAddress := ipNet.String()

		var derivedConfigMethod state.AddressConfigMethod
		switch method := state.AddressConfigMethod(netConfig.ConfigType); method {
		case state.StaticAddress, state.DynamicAddress,
			state.LoopbackAddress, state.ManualAddress:
			derivedConfigMethod = method
		case "dhcp": // awkward special case
			derivedConfigMethod = state.DynamicAddress
		default:
			derivedConfigMethod = state.StaticAddress
		}

		addr := state.LinkLayerDeviceAddress{
			DeviceName:       netConfig.InterfaceName,
			ProviderID:       network.Id(netConfig.ProviderAddressId),
			ConfigMethod:     derivedConfigMethod,
			CIDRAddress:      cidrAddress,
			DNSServers:       netConfig.DNSServers,
			DNSSearchDomains: netConfig.DNSSearchDomains,
			GatewayAddress:   netConfig.GatewayAddress,
			IsDefaultGateway: netConfig.IsDefaultGateway,
		}
		logger.Tracef("state address args for device: %+v", addr)
		devicesAddrs = append(devicesAddrs, addr)
	}
	logger.Tracef("seen devices: %+v", seenDeviceNames.SortedValues())
	logger.Tracef("network config transformed to state args:\n%+v\n%+v", devicesArgs, devicesAddrs)
	return devicesArgs, devicesAddrs
}
93817
func NewDefaultKubeConnectionArgs() *KubeConnectionArgs {
	config := &KubeConnectionArgs{}

	config.KubernetesAddr = flagtypes.Addr{Value: "localhost:8443", DefaultScheme: "https", DefaultPort: 8443, AllowPrefix: true}.Default()
	config.ClientConfig = clientcmd.NewNonInteractiveDeferredLoadingClientConfig(&config.ClientConfigLoadingRules, &clientcmd.ConfigOverrides{})

	return config
}
934729
func BindNetworkArgs(args *NetworkArgs, flags *pflag.FlagSet, prefix string) {
	flags.StringVar(&args.NetworkPluginName, prefix+"network-plugin", args.NetworkPluginName, "The name of the networking plugin to be used for networking.")
	flags.StringVar(&args.ClusterNetworkCIDR, prefix+"network-cidr", args.ClusterNetworkCIDR, "The CIDR string representing the network that all containers should belong to.")
	flags.Uint32Var(&args.HostSubnetLength, prefix+"host-subnet-length", args.HostSubnetLength, "The length of subnet each host is given from the network-cidr.")
	flags.StringVar(&args.ServiceNetworkCIDR, prefix+"portal-net", args.ServiceNetworkCIDR, "The CIDR string representing the network that portal/service IPs will be assigned from. This must not overlap with any IP ranges assigned to nodes for pods.")
}
598733
func NewDNSProviderConfig(config *Config) (*DNSProvider, error) {
	if config == nil {
		return nil, errors.New("vultr: the configuration of the DNS provider is nil")
	}

	if config.APIKey == "" {
		return nil, fmt.Errorf("vultr: credentials missing")
	}

	options := &vultr.Options{
		HTTPClient: config.HTTPClient,
	}
	client := vultr.NewClient(config.APIKey, options)

	return &DNSProvider{client: client, config: config}, nil
}
618964
func NewArgs(initialArgs ...KeyValuePair) Args {
	args := Args{fields: map[string]map[string]bool{}}
	for _, arg := range initialArgs {
		args.Add(arg.Key, arg.Value)
	}
	return args
}
1309765
func jsonParamsToArgsWS(rpcFunc *RPCFunc, params json.RawMessage, wsCtx types.WSRPCContext) ([]reflect.Value, error) {
	values, err := jsonParamsToArgs(rpcFunc, params, 1)
	if err != nil {
		return nil, err
	}
	return append([]reflect.Value{reflect.ValueOf(wsCtx)}, values...), nil
}
846420
func NetworkOptionLabels(labels map[string]string) NetworkOption {
	return func(n *network) {
		n.labels = labels
	}
}
1004428
func (cniReq *cniServer) configureNetNs(ovsEpDriver *drivers.OperEndpointState,
	mResp *master.CreateEndpointResponse,
	nwState *mastercfg.CfgNetworkState) error {

	os.MkdirAll(netNsDir, 644)

	// link new name space
	if _, err := os.Stat(netNsDir + cniReq.pluginArgs.CniContainerid); err != nil {
		if err := os.Symlink(cniReq.pluginArgs.CniNetns, netNsDir+cniReq.pluginArgs.CniContainerid); err != nil {
			cniLog.Errorf("failed to link pid to namespace : %s", err.Error())
			return err
		}
	}
	cniLog.Infof("linked %s --> %s ", cniReq.pluginArgs.CniNetns, netNsDir+cniReq.pluginArgs.CniContainerid)

	// move interface to new namespace
	if _, err := exec.Command("ip", "link", "set", ovsEpDriver.PortName, "netns",
		cniReq.pluginArgs.CniContainerid).CombinedOutput(); err != nil {
		cniLog.Errorf("failed to move intf %s to namespace %s: %s",
			ovsEpDriver.PortName, cniReq.pluginArgs.CniContainerid, err.Error())
		cniReq.unlinkNetNs()
		return err
	}

	nsCmds := [][]string{
		{"ip", "link", "set", ovsEpDriver.PortName, "name", cniReq.pluginArgs.CniIfname, "up"},
		{"ip", "address", "add", fmt.Sprintf("%s/%d", ovsEpDriver.IPAddress, nwState.SubnetLen), "dev",
			cniReq.pluginArgs.CniIfname},
	}

	cniReq.ipv4Addr = ovsEpDriver.IPAddress
	cniReq.cniSuccessResp.IP4.IPAddress = fmt.Sprintf("%s/%d", ovsEpDriver.IPAddress, nwState.SubnetLen)

	// gateway
	if len(nwState.Gateway) > 0 {
		gwCmd := []string{"ip", "route", "add", "default", "via", fmt.Sprintf("%s", nwState.Gateway)}
		nsCmds = append(nsCmds, gwCmd)
		cniReq.cniSuccessResp.IP4.Gateway = nwState.Gateway
		cniLog.Infof("ipv4 default gateway of endpoint %s", nwState.Gateway)
	}

	// ipv6
	if len(mResp.EndpointConfig.IPv6Address) > 0 {
		ipv6Cmd := []string{"ip", "-6", "addr", "add",
			fmt.Sprintf("%s/%d", mResp.EndpointConfig.IPv6Address, nwState.IPv6SubnetLen),
			"dev", cniReq.pluginArgs.CniIfname}
		nsCmds = append(nsCmds, ipv6Cmd)
		cniReq.cniSuccessResp.IP6.IPAddress = fmt.Sprintf("%s/%d", mResp.EndpointConfig.IPv6Address, nwState.IPv6SubnetLen)
		cniLog.Infof("ipv6 address of endpoint %s", mResp.EndpointConfig.IPv6Address)

	}

	if len(nwState.IPv6Gateway) > 0 {
		ipv6gwCmd := []string{"ip", "-6", "route", "add", "default", "via",
			fmt.Sprintf("%s", nwState.IPv6Gateway)}
		nsCmds = append(nsCmds, ipv6gwCmd)
		cniReq.cniSuccessResp.IP6.Gateway = nwState.IPv6Gateway
		cniLog.Infof("ipv6 gateway of endpoint %s", nwState.IPv6Gateway)
	}

	if _, err := cniReq.ipnsBatchExecute(cniReq.pluginArgs.CniContainerid, nsCmds); err != nil {
		cniLog.Errorf("failed to execute commands in namespace %s: %s",
			cniReq.pluginArgs.CniNetns, err.Error())
		cniReq.unlinkNetNs()
		return err
	}

	return nil
}
165176
func (api *NetworkConfigAPI) SetProviderNetworkConfig(args params.Entities) (params.ErrorResults, error) {
	logger.Tracef("SetProviderNetworkConfig %+v", args)
	result := params.ErrorResults{
		Results: make([]params.ErrorResult, len(args.Entities)),
	}

	for i, arg := range args.Entities {
		m, err := api.getMachineForSettingNetworkConfig(arg.Tag)
		if err != nil {
			result.Results[i].Error = common.ServerError(err)
			continue
		}

		if m.IsContainer() {
			continue
		}

		providerConfig, err := api.getOneMachineProviderNetworkConfig(m)
		if err != nil {
			result.Results[i].Error = common.ServerError(err)
			continue
		} else if len(providerConfig) == 0 {
			continue
		}
		logger.Tracef("provider network config for %q: %+v", m.Id(), providerConfig)

		if err := api.setOneMachineNetworkConfig(m, providerConfig); err != nil {
			result.Results[i].Error = common.ServerError(err)
			continue
		}
	}
	return result, nil
}
207266
func (s *RunTaskInput) SetNetworkConfiguration(v *NetworkConfiguration) *RunTaskInput {
	s.NetworkConfiguration = v
	return s
}
617047
func (c *Config) Args() []string {
	args := []string{}
	for _, p := range c.Params {
		args = append(args, p.Args()...)
	}
	return args
}
440569
func MergeProviderAndObservedNetworkConfigs(
	providerConfigs, observedConfigs []params.NetworkConfig,
) []params.NetworkConfig {

	providerConfigByName := networkConfigsByName(providerConfigs)
	logger.Tracef("known provider config by name: %+v", providerConfigByName)

	providerConfigByAddress := networkConfigsByAddress(providerConfigs)
	logger.Tracef("known provider config by address: %+v", providerConfigByAddress)

	var results []params.NetworkConfig
	for _, observed := range observedConfigs {

		name, ipAddress := observed.InterfaceName, observed.Address
		finalConfig := observed

		providerConfig, known := providerConfigByName[name]
		if known {
			finalConfig = mergeObservedAndProviderInterfaceConfig(finalConfig, providerConfig)
			logger.Debugf("updated observed interface config for %q with: %+v", name, providerConfig)
		}

		providerConfig, known = providerConfigByAddress[ipAddress]
		if known {
			finalConfig = mergeObservedAndProviderAddressConfig(finalConfig, providerConfig)
			logger.Debugf("updated observed address config for %q with: %+v", name, providerConfig)
		}

		results = append(results, finalConfig)
		logger.Debugf("merged config for %q: %+v", name, finalConfig)
	}

	return results
}
561914
func Convert_v1_NetworkPolicyPort_To_networking_NetworkPolicyPort(in *v1.NetworkPolicyPort, out *networking.NetworkPolicyPort, s conversion.Scope) error {
	return autoConvert_v1_NetworkPolicyPort_To_networking_NetworkPolicyPort(in, out, s)
}
611789
func (o *Options) NetworkOptions(mctx libkb.MetaContext, r remote.Remoter) stellar1.NetworkOptions {
	o.Lock()
	defer o.Unlock()

	if time.Since(o.mtime) < 1*time.Hour {
		return o.network
	}

	options, err := r.NetworkOptions(mctx.Ctx())
	if err != nil {
		mctx.Debug("error calling NetworkOptions: %s", err)
	} else {
		mctx.Debug("updating NetworkOptions: %+v", options)
		o.network = options
		o.mtime = time.Now()
	}

	return o.network
}
583242
func (o HostNetworkSystem) UpdateNetworkConfig(ctx context.Context, config types.HostNetworkConfig, changeMode string) (*types.HostNetworkConfigResult, error) {
	req := types.UpdateNetworkConfig{
		This:       o.Reference(),
		Config:     config,
		ChangeMode: changeMode,
	}

	res, err := methods.UpdateNetworkConfig(ctx, o.c, &req)
	if err != nil {
		return nil, err
	}

	return &res.Returnval, nil
}
1058130
func (tf *TemplateFunctions) DnsControllerArgv() ([]string, error) {
	var argv []string

	argv = append(argv, "/usr/bin/dns-controller")

	// @check if the dns controller has custom configuration
	if tf.cluster.Spec.ExternalDNS == nil {
		argv = append(argv, []string{"--watch-ingress=false"}...)

		glog.V(4).Infof("watch-ingress=false set on dns-controller")
	} else {
		// @check if the watch ingress is set
		var watchIngress bool
		if tf.cluster.Spec.ExternalDNS.WatchIngress != nil {
			watchIngress = fi.BoolValue(tf.cluster.Spec.ExternalDNS.WatchIngress)
		}

		if watchIngress {
			glog.Warningln("--watch-ingress=true set on dns-controller")
			glog.Warningln("this may cause problems with previously defined services: https://github.com/kubernetes/kops/issues/2496")
		}
		argv = append(argv, fmt.Sprintf("--watch-ingress=%t", watchIngress))
		if tf.cluster.Spec.ExternalDNS.WatchNamespace != "" {
			argv = append(argv, fmt.Sprintf("--watch-namespace=%s", tf.cluster.Spec.ExternalDNS.WatchNamespace))
		}
	}

	if dns.IsGossipHostname(tf.cluster.Spec.MasterInternalName) {
		argv = append(argv, "--dns=gossip")
		argv = append(argv, "--gossip-seed=127.0.0.1:3999")
	} else {
		switch kops.CloudProviderID(tf.cluster.Spec.CloudProvider) {
		case kops.CloudProviderAWS:
			if strings.HasPrefix(os.Getenv("AWS_REGION"), "cn-") {
				argv = append(argv, "--dns=gossip")
			} else {
				argv = append(argv, "--dns=aws-route53")
			}
		case kops.CloudProviderGCE:
			argv = append(argv, "--dns=google-clouddns")
		case kops.CloudProviderDO:
			argv = append(argv, "--dns=digitalocean")
		case kops.CloudProviderVSphere:
			argv = append(argv, "--dns=coredns")
			argv = append(argv, "--dns-server="+*tf.cluster.Spec.CloudConfig.VSphereCoreDNSServer)

		default:
			return nil, fmt.Errorf("unhandled cloudprovider %q", tf.cluster.Spec.CloudProvider)
		}
	}

	zone := tf.cluster.Spec.DNSZone
	if zone != "" {
		if strings.Contains(zone, ".") {
			// match by name
			argv = append(argv, "--zone="+zone)
		} else {
			// match by id
			argv = append(argv, "--zone=*/"+zone)
		}
	}
	// permit wildcard updates
	argv = append(argv, "--zone=*/*")
	// Verbose, but not crazy logging
	argv = append(argv, "-v=2")

	return argv, nil
}
1124151
func NewDNSProviderConfig(config *Config) (*DNSProvider, error) {
	if config == nil {
		return nil, errors.New("rfc2136: the configuration of the DNS provider is nil")
	}

	if config.Nameserver == "" {
		return nil, fmt.Errorf("rfc2136: nameserver missing")
	}

	if config.TSIGAlgorithm == "" {
		config.TSIGAlgorithm = dns.HmacMD5
	}

	// Append the default DNS port if none is specified.
	if _, _, err := net.SplitHostPort(config.Nameserver); err != nil {
		if strings.Contains(err.Error(), "missing port") {
			config.Nameserver = net.JoinHostPort(config.Nameserver, "53")
		} else {
			return nil, fmt.Errorf("rfc2136: %v", err)
		}
	}

	if len(config.TSIGKey) == 0 && len(config.TSIGSecret) > 0 ||
		len(config.TSIGKey) > 0 && len(config.TSIGSecret) == 0 {
		config.TSIGKey = ""
		config.TSIGSecret = ""
	}

	return &DNSProvider{config: config}, nil
}