func createVethPair(handle string, wshdPID int, containerIP string, containerIPAddressMask int, containerMTU int) (string, error) {
	hostIfName := fmt.Sprintf("o-%s-0", handle)
	containerIfName := fmt.Sprintf("o-%s-1", handle)

	vethCreator := devices.VethCreator{}
	hostIf, containerIf, err := vethCreator.Create(hostIfName, containerIfName)
	if err != nil {
		if !strings.Contains(err.Error(), "Network interface already exists") {
			return "", err
		}

		hostIf, err = net.InterfaceByName(hostIfName)
		if err != nil {
			return "", err
		}

		containerIf, err = net.InterfaceByName(containerIfName)
		if err != nil && !strings.Contains(err.Error(), "no such network interface") {
			return "", err
		}
	}

	link := devices.Link{}

	if containerIf != nil {
		err = link.SetNs(containerIf, wshdPID)
		if err != nil {
			return "", err
		}
		fmt.Printf("container if: %+v\n", containerIf)
	}

	if hostIf != nil {
		fmt.Printf("host if: %+v\n", hostIf)
	}

	err = runInNamespace(handle, fmt.Sprintf("ip addr add %s/%d dev %s", containerIP, containerIPAddressMask, containerIfName))
	if err != nil && !strings.Contains(err.Error(), "RTNETLINK answers: File exists") {
		return "", err
	}

	err = runInNamespace(handle, fmt.Sprintf("ip link set %s up", containerIfName))
	if err != nil {
		return "", err
	}

	err = runInNamespace(handle, fmt.Sprintf("ip link set dev %s mtu %d", containerIfName, containerMTU))
	if err != nil {
		return "", err
	}

	return hostIfName, nil
}
Example #2
0
		It("moves the interface in to the given namespace by pid", func() {
			// look at this perfectly ordinary hat
			netns, err := gexec.Start(exec.Command("ip", "netns", "exec", "gdnsetnstest", "sleep", "6312736"), GinkgoWriter, GinkgoWriter)
			Expect(err).ToNot(HaveOccurred())
			defer netns.Kill()

			// (it has the following pid)
			ps, err := gexec.Start(exec.Command("sh", "-c", "ps -A -opid,command | grep 'sleep 6312736' | head -n 1 | awk '{print $1}'"), GinkgoWriter, GinkgoWriter) // look at my hat
			Expect(err).ToNot(HaveOccurred())
			Eventually(ps).Should(gexec.Exit(0))
			pid, err := strconv.Atoi(strings.TrimSuffix(string(ps.Out.Contents()), "\n"))
			Expect(err).ToNot(HaveOccurred())

			// I wave the magic wand
			Expect(l.SetNs(intf, pid)).To(Succeed())

			// the bunny has vanished! where is the bunny?
			intfs, _ := net.Interfaces()
			Expect(intfs).ToNot(ContainElement(intf))

			// oh my word it's in the hat!
			session, err := gexec.Start(exec.Command("sh", "-c", fmt.Sprintf("ip netns exec gdnsetnstest ifconfig %s", name)), GinkgoWriter, GinkgoWriter)
			Expect(err).ToNot(HaveOccurred())
			Eventually(session).Should(gexec.Exit(0))

		})
	})

	Describe("InterfaceByName", func() {
		Context("when the interface exists", func() {