// NetNsPath returns the path to the network namespace of the sandbox.
// If the sandbox uses the host namespace, nil is returned
543724
func (s *Sandbox) NetNsPath() string {
	if s.netns == nil || s.netns.Get() == nil ||
		s.netns.Get().symlink == nil {
		if s.infraContainer != nil {
			return fmt.Sprintf("/proc/%v/ns/net", s.infraContainer.State().Pid)
		}
		return ""
	}

	return s.netns.Get().symlink.Name()
}
774062
func (dns *dnsControl) GetNamespaceByName(name string) (*api.Namespace, error) {
	os := dns.nsLister.List()
	for _, o := range os {
		ns, ok := o.(*api.Namespace)
		if !ok {
			continue
		}
		if name == ns.ObjectMeta.Name {
			return ns, nil
		}
	}
	return nil, fmt.Errorf("namespace not found")
}
1015471
func (s *Sandbox) NetNs() *NetNs {
	if s.netns == nil {
		return nil
	}
	return s.netns.Get()
}
576687
func networkDir(dataDir string, chainParams *chaincfg.Params) string {
	netname := chainParams.Name

	// For now, we must always name the testnet data directory as "testnet"
	// and not "testnet3" or any other version, as the chaincfg testnet3
	// paramaters will likely be switched to being named "testnet3" in the
	// future.  This is done to future proof that change, and an upgrade
	// plan to move the testnet3 data directory can be worked out later.
	if chainParams.Net == wire.TestNet3 {
		netname = "testnet"
	}

	return filepath.Join(dataDir, netname)
}
837884
func (al *aliasList) aliasPath(nm string) (string, error) {
	for ind, name := range al.namesList {
		if nm == name {
			return fmt.Sprintf("#%d", ind), nil
		}
	}
	al.namesList = append(al.namesList, nm)
	return fmt.Sprintf("#%d", len(al.namesList)-1), nil
}
756734
func (d *driver) getNFSPath(v *api.Volume) (string, error) {
	locator := v.GetLocator()
	server, ok := locator.VolumeLabels["server"]
	if !ok {
		logrus.Warnf("No server label found on volume")
		return "", fmt.Errorf("No server label found on volume: " + v.Id)
	}

	return path.Join(nfsMountPath, server), nil
}
773875
func (s *Sandbox) NetNsJoin(nspath, name string) error {
	if s.netns != nil {
		return fmt.Errorf("sandbox already has a network namespace, cannot join another")
	}

	netNS, err := s.NetNsGet(nspath, name)
	if err != nil {
		return err
	}

	s.netns = netNS

	return nil
}
553495
func (n *NetNs) Path() string {
	if n == nil || n.netNS == nil {
		return ""
	}
	return n.netNS.Path()
}
262563
func GetHostsPath() string {
	path := os.Getenv("HOSTESS_PATH")
	if path == "" {
		if runtime.GOOS == "windows" {
			path = "C:\\Windows\\System32\\drivers\\etc\\hosts"
		} else {
			path = "/etc/hosts"
		}
	}
	return path
}
740609
func (s *Service) NetworkConnect(ctx context.Context, c *container.Container, net *yaml.Network, oneOff bool) error {
	containerID := c.ID()
	client := s.clientFactory.Create(s)
	internalLinks, err := s.getLinks()
	if err != nil {
		return err
	}
	links := []string{}
	// TODO(vdemeester) handle link to self (?)
	for k, v := range internalLinks {
		links = append(links, strings.Join([]string{v, k}, ":"))
	}
	for _, v := range s.serviceConfig.ExternalLinks {
		links = append(links, v)
	}
	aliases := []string{}
	if !oneOff {
		aliases = []string{s.Name()}
	}
	aliases = append(aliases, net.Aliases...)
	if len(net.Aliases) >= 1 {
		logrus.Infof("connect")
		client.NetworkConnect(ctx, net.RealName, containerID, &network.EndpointSettings{
			Aliases:   aliases,
			Links:     links,
			IPAddress: net.IPv4Address,
			IPAMConfig: &network.EndpointIPAMConfig{
				IPv4Address: net.IPv4Address,
				IPv6Address: net.IPv6Address,
			},
		})
		logrus.Infof("disconnect")
		client.NetworkDisconnect(ctx, net.RealName, containerID, true)
	}
	return client.NetworkConnect(ctx, net.RealName, containerID, &network.EndpointSettings{
		Aliases:   aliases,
		Links:     links,
		IPAddress: net.IPv4Address,
		IPAMConfig: &network.EndpointIPAMConfig{
			IPv4Address: net.IPv4Address,
			IPv6Address: net.IPv6Address,
		},
	})
}
1081351
func (env *maasEnviron) NetworkInterfaces(ctx context.ProviderCallContext, instId instance.Id) ([]network.InterfaceInfo, error) {
	inst, err := env.getInstance(ctx, instId)
	if err != nil {
		return nil, errors.Trace(err)
	}
	subnetsMap, err := env.subnetToSpaceIds(ctx)
	if err != nil {
		return nil, errors.Trace(err)
	}
	if env.usingMAAS2() {
		dnsSearchDomains, err := env.Domains(ctx)
		if err != nil {
			return nil, errors.Trace(err)
		}
		return maas2NetworkInterfaces(ctx, inst.(*maas2Instance), subnetsMap, dnsSearchDomains...)
	} else {
		mi := inst.(*maas1Instance)
		return maasObjectNetworkInterfaces(ctx, mi.maasObject, subnetsMap)
	}
}
914290
func (s *Sandbox) UserNsPath() string {
	if s.infraContainer != nil {
		return fmt.Sprintf("/proc/%v/ns/user", s.infraContainer.State().Pid)
	}
	return ""
}
706813
func (e *environ) NetworkInterfaces(ctx context.ProviderCallContext, instId instance.Id) ([]network.InterfaceInfo, error) {
	insts, err := e.Instances(ctx, []instance.Id{instId})
	if err != nil {
		return nil, errors.Trace(err)
	}
	envInst, ok := insts[0].(*environInstance)
	if !ok {
		// This shouldn't happen.
		return nil, errors.Errorf("couldn't extract google instance for %q", instId)
	}
	// In GCE all the subnets are in all AZs.
	zones, err := e.zoneNames(ctx)
	if err != nil {
		return nil, errors.Trace(err)
	}
	networks, err := e.networksByURL(ctx)
	if err != nil {
		return nil, errors.Trace(err)
	}
	googleInst := envInst.base
	ifaces := googleInst.NetworkInterfaces()

	var subnetURLs []string
	for _, iface := range ifaces {
		if iface.Subnetwork != "" {
			subnetURLs = append(subnetURLs, iface.Subnetwork)
		}
	}
	subnets, err := e.subnetsByURL(ctx, subnetURLs, networks, zones)
	if err != nil {
		return nil, errors.Trace(err)
	}
	// We know there'll be a subnet for each url requested, otherwise
	// there would have been an error.

	var results []network.InterfaceInfo
	for i, iface := range ifaces {
		details, err := findNetworkDetails(iface, subnets, networks)
		if err != nil {
			return nil, errors.Annotatef(err, "instance %q", instId)
		}
		results = append(results, network.InterfaceInfo{
			DeviceIndex: i,
			CIDR:        details.cidr,
			// The network interface has no id in GCE so it's
			// identified by the machine's id + its name.
			ProviderId:        network.Id(fmt.Sprintf("%s/%s", instId, iface.Name)),
			ProviderSubnetId:  details.subnet,
			ProviderNetworkId: details.network,
			AvailabilityZones: copyStrings(zones),
			InterfaceName:     iface.Name,
			Address:           network.NewScopedAddress(iface.NetworkIP, network.ScopeCloudLocal),
			InterfaceType:     network.EthernetInterface,
			Disabled:          false,
			NoAutoStart:       false,
			ConfigType:        network.ConfigDHCP,
		})
	}
	return results, nil
}
151790
func (veth *VethPair) SetPeerLinkNsFd(nspath string) error {
	fd, err := syscall.Open(nspath, syscall.O_RDONLY, 0)
	if err != nil {
		return fmt.Errorf("Could not attach to Network namespace: %s", err)
	}

	return netlink.NetworkSetNsFd(veth.peerIfc, fd)
}
954984
func (n *networkNamespace) Restore(ifsopt map[string][]IfaceOption, routes []*types.StaticRoute, gw net.IP, gw6 net.IP) error {
	// restore interfaces
	for name, opts := range ifsopt {
		if !strings.Contains(name, "+") {
			return fmt.Errorf("wrong iface name in restore osl sandbox interface: %s", name)
		}
		seps := strings.Split(name, "+")
		srcName := seps[0]
		dstPrefix := seps[1]
		i := &nwIface{srcName: srcName, dstName: dstPrefix, ns: n}
		i.processInterfaceOptions(opts...)
		if i.master != "" {
			i.dstMaster = n.findDst(i.master, true)
			if i.dstMaster == "" {
				return fmt.Errorf("could not find an appropriate master %q for %q",
					i.master, i.srcName)
			}
		}
		if n.isDefault {
			i.dstName = i.srcName
		} else {
			links, err := n.nlHandle.LinkList()
			if err != nil {
				return fmt.Errorf("failed to retrieve list of links in network namespace %q during restore", n.path)
			}
			// due to the docker network connect/disconnect, so the dstName should
			// restore from the namespace
			for _, link := range links {
				addrs, err := n.nlHandle.AddrList(link, netlink.FAMILY_V4)
				if err != nil {
					return err
				}
				ifaceName := link.Attrs().Name
				if strings.HasPrefix(ifaceName, "vxlan") {
					if i.dstName == "vxlan" {
						i.dstName = ifaceName
						break
					}
				}
				// find the interface name by ip
				if i.address != nil {
					for _, addr := range addrs {
						if addr.IPNet.String() == i.address.String() {
							i.dstName = ifaceName
							break
						}
						continue
					}
					if i.dstName == ifaceName {
						break
					}
				}
				// This is to find the interface name of the pair in overlay sandbox
				if strings.HasPrefix(ifaceName, "veth") {
					if i.master != "" && i.dstName == "veth" {
						i.dstName = ifaceName
					}
				}
			}

			var index int
			indexStr := strings.TrimPrefix(i.dstName, dstPrefix)
			if indexStr != "" {
				index, err = strconv.Atoi(indexStr)
				if err != nil {
					return err
				}
			}
			index++
			n.Lock()
			if index > n.nextIfIndex[dstPrefix] {
				n.nextIfIndex[dstPrefix] = index
			}
			n.iFaces = append(n.iFaces, i)
			n.Unlock()
		}
	}

	// restore routes
	for _, r := range routes {
		n.Lock()
		n.staticRoutes = append(n.staticRoutes, r)
		n.Unlock()
	}

	// restore gateway
	if len(gw) > 0 {
		n.Lock()
		n.gw = gw
		n.Unlock()
	}

	if len(gw6) > 0 {
		n.Lock()
		n.gwv6 = gw6
		n.Unlock()
	}

	return nil
}
473978
func (s *StanServer) createNatsClientConn(name string) (*nats.Conn, error) {
	var err error
	ncOpts := nats.DefaultOptions

	for _, o := range s.opts.NATSClientOpts {
		o(&ncOpts)
	}

	ncOpts.Servers, err = s.buildServerURLs()
	if err != nil {
		return nil, err
	}
	ncOpts.User = s.natsOpts.Username
	ncOpts.Password = s.natsOpts.Password
	ncOpts.Token = s.natsOpts.Authorization

	ncOpts.Name = fmt.Sprintf("_NSS-%s-%s", s.opts.ID, name)

	if err = nats.ErrorHandler(s.stanErrorHandler)(&ncOpts); err != nil {
		return nil, err
	}
	if err = nats.ReconnectHandler(s.stanReconnectedHandler)(&ncOpts); err != nil {
		return nil, err
	}
	if err = nats.ClosedHandler(s.stanClosedHandler)(&ncOpts); err != nil {
		return nil, err
	}
	if err = nats.DisconnectHandler(s.stanDisconnectedHandler)(&ncOpts); err != nil {
		return nil, err
	}
	if s.opts.Secure {
		if err = nats.Secure()(&ncOpts); err != nil {
			return nil, err
		}
	}
	if s.opts.ClientCA != "" {
		if err = nats.RootCAs(s.opts.ClientCA)(&ncOpts); err != nil {
			return nil, err
		}
	}
	if s.opts.ClientCert != "" {
		if err = nats.ClientCert(s.opts.ClientCert, s.opts.ClientKey)(&ncOpts); err != nil {
			return nil, err
		}
	}
	// Shorten the time we wait to try to reconnect.
	// Don't make it too often because it may exhaust the number of FDs.
	ncOpts.ReconnectWait = 250 * time.Millisecond
	// Make it try to reconnect for ever.
	ncOpts.MaxReconnect = -1
	// To avoid possible duplicate redeliveries, etc.., set the reconnect
	// buffer to -1 to avoid any buffering in the nats library and flush
	// on reconnect.
	ncOpts.ReconnectBufSize = -1

	var nc *nats.Conn
	if nc, err = ncOpts.Connect(); err != nil {
		return nil, err
	}
	return nc, err
}
1323338
func (r *Request) Namespace(s string) *Request {
	r.namespace = s
	return r
}