예제 #1
0
class HostManagerImpl(HostManager):
    ## constructor
    # @param host The host to connect
    # @param user The login user
    # @param password The login password
    def __init__(self, host=None, user=None, password=None):
        ## remote interface
        self.__interface = RemoteInterfaceImpl(host, user, password)
    ## the implementation of creating bridge
    # @param self The object pointer
    # @param bridge The bridge that will be created
    def createBridgeImpl(self, bridge):
        # create a new bridge
        for cmd in ("brctl addbr " + bridge.getName(), "ip link set " + bridge.getName() + " up"):
            ret = self.__interface.sudo(cmd, True)
            if ret.rc != 0:
                raise RuntimeError("Cannot create bridge(" + str(bridge.getNetworkAddress()) + "): " + ret.stdout + ret.stderr)
    ## the implementation of deleting bridge
    # @param self The object pointer
    # @param bridge The bridge that will be deleted
    def destroyBridgeImpl(self, bridge):
        # destroy the bridge
        for cmd in ("ip link set " + bridge.getName() + " down", "brctl delbr " + bridge.getName()):
            ret = self.__interface.sudo(cmd, True)
            if ret.rc != 0:
                raise RuntimeError("Cannot destroy bridge(" + str(bridge.getNetworkAddress()) + "): " + ret.stdout + ret.stderr)
예제 #2
0
파일: service.py 프로젝트: ynaka81/dockerEE
 def setUp(self):
     arg = {"host": "localhost", "user": "******", "password": "******"}
     stub = "/tmp/service_stub.py"
     ## service interface
     self.__service = ServiceTestUtils("python " + stub, **arg)
     ## remote interface
     self.__interface = RemoteInterfaceImpl(**arg)
     ## env.yml parameter
     self.__parameter = {"servers":[{"name": "s1", "image": "local/centos", "IPs": [{"dev": "eth0", "IP": "192.168.0.1/24", "gw": "192.168.0.254/24"}]}, {"name": "s2", "image": "local/centos", "IPs": [{"dev": "eth0", "IP": "192.168.0.2/24"}, {"dev": "eth1", "IP": "192.168.1.2/24", "gw": "192.168.1.254/24"}]}]}
     ## test utils
     self.__utils = DockerContainerTestUtils(**arg)
     ## environment definition file
     self.__filename = "/tmp/env.yml"
     # make service stub script
     f = open(stub, "w")
     f.write("import sys\n")
     f.write("sys.path.append('/vagrant')\n")
     f.write("from dockerEE.service import EnvironmentEmulationService\n")
     f.write("service = EnvironmentEmulationService('localhost', 'vagrant', 'vagrant')\n")
     f.write("service.action()")
     f.close()
     # make env.yml
     f = open(self.__filename, "w")
     f.write("---\n")
     f.write("servers:\n")
     for p in self.__parameter["servers"]:
         f.write("        - name: " + p["name"] + "\n")
         f.write("          image: " + p["image"] + "\n")
         f.write("          IPs:\n")
         for n in p["IPs"]:
             f.write("                  - dev: " + n["dev"] + "\n")
             f.write("                    IP: " + n["IP"] + "\n")
             if "gw" in n:
                 f.write("                    gw: " + n["gw"] + "\n")
     f.close()
예제 #3
0
파일: core.py 프로젝트: ynaka81/dockerEE
 def setUp(self):
     arg = {"host": "localhost", "user": "******", "password": "******"}
     ## remote interface
     self.__interface = RemoteInterfaceImpl(**arg)
     ## container_manager
     self.__manager = ContainerManagerImpl(**arg)
     ## test utils
     self.__utils = DockerContainerTestUtils(**arg)
예제 #4
0
class TestServiceDaemon(unittest.TestCase):
    ## init test case
    # @param self The object pointer
    def setUp(self):
        arg = {"host": "localhost", "user": "******", "password": "******"}
        ## service test utils
        self.__service = ServiceTestUtils("python /vagrant/test/test_case/service_service_daemon_stub.py", **arg)
        ## remote interface
        self.__interface = RemoteInterfaceImpl(**arg)
        ## starting file name
        self.__filename = "/tmp/service_service_daemon"
        open(self.__filename, "w")
    ## test "python service.py start/stop"
    # @param self The object pointer
    def testStartStop(self):
        ret = self.__service.start(self.__filename, 10)
        self.assertEqual(ret.rc, 0)
        ret = self.__interface.sudo("test -f ~/.dockerEE/test_service_service_daemon.check", True)
        self.assertEqual(ret.rc, 0)
        ret = self.__service.stop(10)
        self.assertEqual(ret.rc, 0)
        ret = self.__interface.sudo("test -f ~/.dockerEE/test_service_service_daemon.check", True)
        self.assertNotEqual(ret.rc, 0)
    ## test ServiceDaemon._getInstance(self)
    # @param self The object pointer
    def testGetInstance(self):
        self.__service.start(self.__filename, 10)
        service = TestService()
        self.assertEqual(service._getInstance().getCount(), 0)
        self.__service.stop(10)
    ## test "python service.py status"
    # @param self The object pointer
    def testStatus(self):
        self.__service.start(self.__filename, 10)
        ret = self.__service.status()
        self.assertIn("counter = 0", ret.stdout)
        self.__service.stop(10)
    ## test "python service.py reload"
    # @param self The object pointer
    def testReload(self):
        self.__service.start(self.__filename, 10)
        self.__service.reload()
        ret = self.__service.status()
        self.assertIn("counter = 1", ret.stdout)
        self.__service.stop(10)
예제 #5
0
파일: host.py 프로젝트: ynaka81/dockerEE
class TestHostManagerImpl(unittest.TestCase):
    ## init test case
    # @param self The object pointer
    def setUp(self):
        arg = {"host": "localhost", "user": "******", "password": "******"}
        ## remote interface
        self.__interface = RemoteInterfaceImpl(**arg)
        ## host OS manager
        self.__manager = HostManagerImpl(**arg)
    ## check if the bridge exists
    # @param self The object pointer
    # @param network_address The network address of the bridge
    # @return Whether the bridge exists
    def __checkBridgeExist(self, network):
        return self.__interface.sudo("ip addr show | grep br_" + str(network).split("/")[0], True).rc == 0
    ## test HostManager.createBridge(network_address)
    # @param self The object pointer
    def testCreateBridge(self):
        ip = ip_interface(u"192.168.33.10/24")
        b = self.__manager.createBridge(ip.network)
        self.assertTrue(self.__checkBridgeExist(ip.network))
        del b
        self.assertFalse(self.__checkBridgeExist(ip.network))

    ## test HostManager.createBridge(network_address) fail because the bridge already exists
    # @param self The object pointer
    def testFailCreateBridge(self):
        ip = ip_interface(u"192.168.33.10/24")
        self.__interface.sudo("brctl addbr br_" + str(ip.network).split("/")[0])
        with self.assertRaises(RuntimeError):
            b = self.__manager.createBridge(ip.network)
        self.__interface.sudo("ip link set br_" + str(ip.network).split("/")[0] + " down")
        self.__interface.sudo("brctl delbr br_" + str(ip.network).split("/")[0])
예제 #6
0
 def setUp(self):
     arg = {"host": "localhost", "user": "******", "password": "******"}
     ## service test utils
     self.__service = ServiceTestUtils("python /vagrant/test/test_case/service_service_daemon_stub.py", **arg)
     ## remote interface
     self.__interface = RemoteInterfaceImpl(**arg)
     ## starting file name
     self.__filename = "/tmp/service_service_daemon"
     open(self.__filename, "w")
예제 #7
0
class ServiceTestUtils(object):
    ## delta time for waiting
    __dt = 0.1
    ## constructor
    # @param service_name The service name
    # @param host The host to connect
    # @param user The login user
    # @param password The login password
    def __init__(self, service_name, host=None, user=None, password=None): 
        ## service name
        self.__name = service_name
        ## remote interface
        self.__interface = RemoteInterfaceImpl(host, user, password, pty=False)
    ## display service usage
    # @param self The object pointer
    # @return CommandResult
    def usage(self):
        return self.__interface.sudo(self.__name, True)
    ## start service and wait for starting
    # @param self The object pointer
    # @param start_file The service starting file
    # @param timeout The timeout of waiting for service. When timeout is -1, timeout does not work
    # @return CommandResult
    def start(self, start_file, timeout=-1):
        ret = self.__interface.sudo(self.__name + " start " + start_file, True)
        while timeout > 0 and "active (running)" not in self.__interface.sudo(self.__name + " status").stdout:
            time.sleep(self.__dt)
            timeout -= self.__dt
            if timeout < 0:
                raise RuntimeError("The service (" + self.__name + ") can not be started.")
        return ret
    ## stop service and wait for stopping
    # @param self The object pointer
    # @param timeout The timeout of waiting for service. When timeout is -1, timeout does not work
    # @return CommandResult
    def stop(self, timeout=-1):
        ret = self.__interface.sudo(self.__name + " stop", True)
        while timeout > 0 and "inactive (dead)" not in self.__interface.sudo(self.__name + " status").stdout:
            time.sleep(self.__dt)
            timeout -= self.__dt
            if timeout < 0:
                raise RuntimeError("The service (" + self.__name + ") can not be stopped.")
        return ret
    ## get service status
    # @param self The object pointer
    # @return CommandResult
    def status(self):
        return self.__interface.sudo(self.__name + " status", True)
    ## reload service
    # @param self The object pointer
    # @param argv The reload options
    # @return CommandResult
    def reload(self, argv=[]):
        return self.__interface.sudo(self.__name + " reload " + " ".join(argv), True)
예제 #8
0
파일: remote.py 프로젝트: ynaka81/dockerEE
class TestRemoteInterfaceInmpl(unittest.TestCase):
    ## init test case
    def setUp(self):
        arg = {"host": "localhost", "user": "******", "password": "******"}
        ## remote_interface
        self.__interface = RemoteInterfaceImpl(**arg)
    ## test RemoteInterfaceImpl.sudo(command)
    # @param self The object pointer
    def testSudo(self):
        word = "HelloWold!"
        command = "echo " + word
        ret = self.__interface.sudo(command)
        self.assertEqual(ret.command, command)
        self.assertEqual(ret.rc, 0)
        self.assertEqual(ret.stdout, word)
        self.assertEqual(ret.stderr, "")
    ## test RemoteInterfaceImpl.sudo(command, True)
    # @param self The object pointer
    def testSudoIgnoreError(self):
        command = "cat hoge"
        ret = self.__interface.sudo(command, True)
        self.assertEqual(ret.command, command)
        self.assertEqual(ret.rc, 1)
class DockerContainerTestUtils(object):
    ## constructor
    # @param host The host to connect
    # @param user The login user
    # @param password The login password
    def __init__(self, host=None, user=None, password=None): 
        ## remote interface
        self.__interface = RemoteInterfaceImpl(host, user, password)
    ## inner function of checking whether the container exists
    # @param self The object pointer
    # @param containers The name of containers
    # @param all_exist True:all containers exist, False:all containers does not exist
    def __checkContainerExist(self, containers, all_exist):
        if not isinstance(containers, list):
            containers = [containers]
        ret = self.__interface.sudo("docker ps -a")
        lines = ret.stdout.splitlines()[1:]
        for c in containers:
            try:
                (l for l in lines if c in l).next()
                if not all_exist:
                    return False
            except StopIteration:
                if all_exist:
                    return False
        return len(lines) == len(containers) if all_exist else len(lines) == 0
    ## check whether all containers exist
    # @param self The object pointer
    # @param containers The name of containers
    def checkContainerExist(self, containers):
        return self.__checkContainerExist(containers, True)
    ## check whether all containers does not exist
    # @param self The object pointer
    # @param containers The name of containers
    def checkContainerNotExist(self, containers):
        return self.__checkContainerExist(containers, False)
 def __init__(self, host=None, user=None, password=None): 
     ## remote interface
     self.__interface = RemoteInterfaceImpl(host, user, password)
예제 #11
0
 def __init__(self, host=None, user=None, password=None):
     ## remote interface
     self.__interface = RemoteInterfaceImpl(host, user, password)
     # check if docker service is running
     if self.__interface.sudo("docker info", True).rc != 0:
         raise RuntimeError("The docker service is not running at " + host)
예제 #12
0
파일: service.py 프로젝트: ynaka81/dockerEE
class TestEnvironmentEmulationService(unittest.TestCase):
    ## init test case
    # @param self The object pointer
    def setUp(self):
        arg = {"host": "localhost", "user": "******", "password": "******"}
        stub = "/tmp/service_stub.py"
        ## service interface
        self.__service = ServiceTestUtils("python " + stub, **arg)
        ## remote interface
        self.__interface = RemoteInterfaceImpl(**arg)
        ## env.yml parameter
        self.__parameter = {"servers":[{"name": "s1", "image": "local/centos", "IPs": [{"dev": "eth0", "IP": "192.168.0.1/24", "gw": "192.168.0.254/24"}]}, {"name": "s2", "image": "local/centos", "IPs": [{"dev": "eth0", "IP": "192.168.0.2/24"}, {"dev": "eth1", "IP": "192.168.1.2/24", "gw": "192.168.1.254/24"}]}]}
        ## test utils
        self.__utils = DockerContainerTestUtils(**arg)
        ## environment definition file
        self.__filename = "/tmp/env.yml"
        # make service stub script
        f = open(stub, "w")
        f.write("import sys\n")
        f.write("sys.path.append('/vagrant')\n")
        f.write("from dockerEE.service import EnvironmentEmulationService\n")
        f.write("service = EnvironmentEmulationService('localhost', 'vagrant', 'vagrant')\n")
        f.write("service.action()")
        f.close()
        # make env.yml
        f = open(self.__filename, "w")
        f.write("---\n")
        f.write("servers:\n")
        for p in self.__parameter["servers"]:
            f.write("        - name: " + p["name"] + "\n")
            f.write("          image: " + p["image"] + "\n")
            f.write("          IPs:\n")
            for n in p["IPs"]:
                f.write("                  - dev: " + n["dev"] + "\n")
                f.write("                    IP: " + n["IP"] + "\n")
                if "gw" in n:
                    f.write("                    gw: " + n["gw"] + "\n")
        f.close()
    ## test "python service.py start/stop"
    # @param self The object pointer
    def testStartStop(self):
        servers = [x["name"] for x in self.__parameter["servers"]]
        ret = self.__service.start(self.__filename, 10)
        self.assertTrue(self.__utils.checkContainerExist(servers))
        for p in self.__parameter["servers"]:
            for n in p["IPs"]:
                ret = self.__interface.sudo("docker exec -i " + p["name"] + " ip addr show")
                self.assertTrue(re.search(r"inet " + n["IP"] + ".*" + n["dev"], ret.stdout))
                if "gw" in n:
                    ret = self.__interface.sudo("docker exec -i " + p["name"] + " ip route show")
                    self.assertIn("default via " + n["gw"].split("/")[0] + " dev " + n["dev"], ret.stdout)
        self.__service.stop(10)
        self.assertTrue(self.__utils.checkContainerNotExist(servers))
    ## test "python service.py status"
    # @param self The object pointer
    def testStatus(self):
        servers = [x["name"] for x in self.__parameter["servers"]]
        self.__service.start(self.__filename, 10)
        ret = self.__service.status()
        status =  "servers\n"
        for p in self.__parameter["servers"]:
            status += "\t" + p["name"] + "\n"
            for n in p["IPs"]:
                status += "\t\t" + n["dev"] + " : " + n["IP"]
                if "gw" in n:
                    status += " via " + n["gw"] + "\n"
                else:
                    status += "\n"
        ret.stdout += "\n"
        self.assertIn(status, ret.stdout)
        self.__service.stop(10)
        ret = self.__service.status()
        self.assertEqual(ret.rc, 0)
    ## test "python service.py reload"
    # @param self The object pointer
    def testReload(self):
        servers = [x["name"] for x in self.__parameter["servers"]]
        self.__service.start(self.__filename, 10)
        for s in servers:
            self.__interface.sudo("docker exec -i " + s + " touch /tmp/hello_dockerEE")
        for s in servers:
            ret = self.__interface.sudo("docker exec -i " + s + " test -f /tmp/hello_dockerEE", True)
            self.assertEqual(ret.rc, 0)
        self.__service.reload(servers[1:])
        ret = self.__interface.sudo("docker exec -i " + servers[0] + " test -f /tmp/hello_dockerEE", True)
        self.assertEqual(ret.rc, 0)
        ret = self.__interface.sudo("docker exec -i " + servers[1] + " test -f /tmp/hello_dockerEE", True)
        self.assertEqual(ret.rc, 1)
        for p in self.__parameter["servers"]:
            for n in p["IPs"]:
                ret = self.__interface.sudo("docker exec -i " + p["name"] + " ip addr show")
                self.assertTrue(re.search(r"inet " + n["IP"] + ".*" + n["dev"], ret.stdout))
                if "gw" in n:
                    ret = self.__interface.sudo("docker exec -i " + p["name"] + " ip route show")
                    self.assertIn("default via " + n["gw"].split("/")[0] + " dev " + n["dev"], ret.stdout)
        self.__service.stop(10)
예제 #13
0
파일: core.py 프로젝트: ynaka81/dockerEE
class TestContainerManagerImpl(unittest.TestCase):
    ## init test case
    # @param self The object pointer
    def setUp(self):
        arg = {"host": "localhost", "user": "******", "password": "******"}
        ## remote interface
        self.__interface = RemoteInterfaceImpl(**arg)
        ## container_manager
        self.__manager = ContainerManagerImpl(**arg)
        ## test utils
        self.__utils = DockerContainerTestUtils(**arg)
    ## test ContainerManagerImpl.create(name)
    # @param self The object pointer
    def testCreate(self):
        container = "c1"
        c = self.__manager.create(container)
        self.assertTrue(self.__utils.checkContainerExist(container))
    ## test ContainerManagerImpl.create(name. privilege)
    # @param self The object pointer
    def testCreateWithPrivilege(self):
        container = "c1"
        c = self.__manager.create(container, privilege=["NET_ADMIN", "SYS_ADMIN"])
        ret = self.__interface.sudo("docker exec -i " + container + " umount /etc/hosts")
        self.assertEqual(ret.rc, 0)
    ## test ContainerManagerImpl.create(name, hosts)
    # @param self The object pointer
    def testCreateWithHosts(self):
        container = "c1"
        hosts = [{"name": "c1", "IP": "1.0.1.10"}, {"name": "c2", "IP": "1.0.1.11"}]
        c = self.__manager.create(container, hosts=hosts)
        ret = self.__interface.sudo("docker exec -i " + container + " cat /etc/hosts")
        container_hosts = ret.stdout.splitlines()[-len(hosts):]
        for i in range(len(hosts)):
            container_host = container_hosts[i].split()
            host = hosts[i]
            self.assertEqual(container_host[1], host["name"])
            self.assertEqual(container_host[0], host["IP"])
    ## test ContainerManagerImpl.create(name, image)
    # @param self The object pointer
    def testCreateWithImage(self):
        container = "c1"
        image = "centos:6"
        c = self.__manager.create(container, image=image)
        ret = self.__interface.sudo("docker ps -a")
        lines = ret.stdout.splitlines()
        self.assertIn(image, lines[1].split())
    ## test ContainerManagerImpl.destroyContainerImpl(container)
    # @param self The object pointer
    def testDestroy(self):
        container = "c1"
        c = self.__manager.create(container)
        self.assertTrue(self.__utils.checkContainerExist(container))
        del c
        self.assertTrue(self.__utils.checkContainerNotExist(container))
    ## test ContainerManagerImpl.command(container, command)
    # @param self The object pointer
    def testCommand(self):
        container = "c1"
        c = self.__manager.create(container)
        ret = c.command("uname -n")
        self.assertEqual(ret.stdout, container)
    ## test ContainerManagerImpl.attachIP(container, segment, dev, IP, gw)
    # @param self The object pointer
    def testAttachIP(self):
        bridge = "br1"
        self.__interface.sudo("brctl addbr " + bridge)
        self.__interface.sudo("ip link set " + bridge + " up")
        container = "c1"
        c = self.__manager.create(container)
        ip1 = ip_interface(u"192.168.0.1/24")
        dev1 = "eth0"
        c.attachIP(bridge, dev1, ip1)
        ret = c.command("ip addr show")
        self.assertTrue(re.search(r"inet " + str(ip1) + ".*" + dev1, ret.stdout))
        ip2 = ip_interface(u"192.168.1.1/24")
        dev2 = "eth1"
        gw = ip_interface(u"192.168.1.254/24")
        c.attachIP(bridge, dev2, ip2, gw)
        ret = c.command("ip addr show")
        self.assertTrue(re.search(r"inet " + str(ip2) + ".*" + dev2, ret.stdout))
        ret = c.command("ip route show")
        self.assertIn("default via " + str(gw.ip) + " dev " + dev2, ret.stdout)
        self.__interface.sudo("ip link set " + bridge + " down")
        self.__interface.sudo("brctl delbr " + bridge)

    ## test ContainerManagerImpl.__init__(host, user, password) fails because docker service is not running
    # @param self The object pointer
    def testFailInit(self):
        self.__interface.sudo("service docker stop")
        with self.assertRaises(RuntimeError):
            self.setUp()
        self.__interface.sudo("service docker start")
    ## test ContainerManagerImpl.create(name) fails because docker service is not running
    # @param self The object pointer
    def testFailCreate(self):
        self.__interface.sudo("service docker stop")
        with self.assertRaises(RuntimeError):
            self.__manager.create("c1")
        self.__interface.sudo("service docker start")
    ## test ContainerManagerImpl.command(container, command) fails because the command does not exist
    # @param self The object pointer
    def testFailCommand(self):
        container = "c1"
        c = self.__manager.create(container)
        with self.assertRaises(RuntimeError):
            c.command("fail")
    ## test ContainerManagerImpl.attachIP(container, segment, dev, IP) fails bacause the same dev is already attached
    # @param self The object pointer
    def testFailAttachIP(self):
        bridge = "br1"
        self.__interface.sudo("brctl addbr " + bridge)
        self.__interface.sudo("ip link set " + bridge + " up")
        container = "c1"
        c = self.__manager.create(container)
        ip = ip_interface(u"192.168.0.1/24")
        dev = "eth0"
        c.attachIP(bridge, dev, ip)
        with self.assertRaises(RuntimeError):
            c.attachIP(bridge, dev, ip)
        self.__interface.sudo("ip link set " + bridge + " down")
        self.__interface.sudo("brctl delbr " + bridge)
예제 #14
0
 def __init__(self, service_name, host=None, user=None, password=None): 
     ## service name
     self.__name = service_name
     ## remote interface
     self.__interface = RemoteInterfaceImpl(host, user, password, pty=False)
예제 #15
0
파일: remote.py 프로젝트: ynaka81/dockerEE
 def setUp(self):
     arg = {"host": "localhost", "user": "******", "password": "******"}
     ## remote_interface
     self.__interface = RemoteInterfaceImpl(**arg)
예제 #16
0
파일: element.py 프로젝트: ynaka81/dockerEE
class TestServer(unittest.TestCase):
    ## init test case
    # @param self The object pointer
    def setUp(self):
        arg = {"host": "localhost", "user": "******", "password": "******"}
        ## remote interface
        self.__interface = RemoteInterfaceImpl(**arg)
        ## container manager
        self.__container_manager = ContainerManagerImpl(**arg)
        ## host OS manager
        self.__host_manager = HostManagerImpl(**arg)
        ## test utils
        self.__utils = DockerContainerTestUtils(**arg)
    ## test Server.__init__(self, container_manager, name)
    # @param self The object pointer
    def testInit(self):
        server = "s1"
        s1 = Server(self.__container_manager, server)
        self.assertTrue(self.__utils.checkContainerExist(server))
    ## test Server.__del__(self)
    # @param self The object pointer
    def testDel(self):
        servers = ["s1", "s2"]
        s = [Server(self.__container_manager, _s) for _s in servers]
        self.assertTrue(self.__utils.checkContainerExist(servers))
        del s[:]
        self.assertFalse(self.__utils.checkContainerExist(servers))
    ## test Server.__del__(self) with IP
    # @param self The object pointer
    def testDestroyIP(self):
        server_info = [{"name": "s1", "ip": ip_interface(u"192.168.0.1/24")}, {"name": "s2", "ip": ip_interface(u"192.168.0.2/24")}]
        servers = []
        for s in server_info:
            servers.append(Server(self.__container_manager, s["name"]))
            servers[-1].attachIP(self.__host_manager, "eth0", s["ip"])
        self.assertTrue(self.__utils.checkContainerExist([s["name"] for s in server_info]))
        self.assertIn("br_192.168.0.0", self.__interface.sudo("ip addr show").stdout)
        del servers[0]
        self.assertIn("br_192.168.0.0", self.__interface.sudo("ip addr show").stdout)
        del servers[0]
        self.assertNotIn("br_192.168.0.0", self.__interface.sudo("ip addr show").stdout)
    ## test Server.getNetworkInfo(self)
    # @param self The object pointer
    def testGetNetworkInfo(self):
        network = [{"dev": "eth0", "IP": ip_interface(u"192.168.0.1/24"), "gw": None}, {"dev": "eth1", "IP": ip_interface(u"192.168.1.2/24"), "gw": ip_interface(u"192.168.1.254/24")}]
        s1 = Server(self.__container_manager, "s1")
        for n in network:
            if n["gw"] is not None:
                s1.attachIP(self.__host_manager, n["dev"], n["IP"], n["gw"])
            else:
                s1.attachIP(self.__host_manager, n["dev"], n["IP"])
        self.assertEqual(s1.getNetworkInfo(), network)
    ## test Server.command(command)
    # @param self The object pointer
    def testCommand(self):
        server = "s1"
        s1 = Server(self.__container_manager, server)
        ret = s1.command("uname -n")
        self.assertEqual(s1.command("uname -n").stdout, server)
    ## test Server.attachIP(host_manager, dev, IP, gw)
    # @param self The object pointer
    def testAttachIP(self):
        network = [{"dev": "eth0", "IP": ip_interface(u"192.168.0.1/24"), "gw": None}, {"dev": "eth1", "IP": ip_interface(u"192.168.1.2/24"), "gw": ip_interface(u"192.168.1.254/24")}]
        s1 = Server(self.__container_manager, "s1")
        for n in network:
            if n["gw"] is not None:
                s1.attachIP(self.__host_manager, n["dev"], n["IP"], n["gw"])
            else:
                s1.attachIP(self.__host_manager, n["dev"], n["IP"])
        ret = s1.command("ip addr show")
        for n in network:
            self.assertTrue(re.search(r"inet " + str(n["IP"]) + ".*" + n["dev"], ret.stdout))
        ret = s1.command("ip route show")
        for n in network:
            if n["gw"] is not None:
                self.assertIn("default via " + str(n["gw"].ip) + " dev " + n["dev"], ret.stdout)
    ## test Server.reload(self)
    # @param self The object pointer
    def testReload(self):
        s1 = Server(self.__container_manager, "s1")
        ret = s1.command("touch /tmp/hello_dockerEE")
        self.assertEqual(ret.rc, 0)
        ret = s1.command("test -f /tmp/hello_dockerEE")
        self.assertEqual(ret.rc, 0)
        s1.reload(self.__container_manager, self.__host_manager)
        with self.assertRaises(RuntimeError):
            ret = s1.command("test -f /tmp/hello_dockerEE")
    ## test Server.reload(self, options)
    # @param self The object pointer
    def testReloadOptions(self):
        image = "centos:6"
        s1 = Server(self.__container_manager, "s1", source=image)
        s1.reload(self.__container_manager, self.__host_manager)
        self.assertIn(image, self.__interface.sudo("docker ps -a").stdout.splitlines()[1].split())
    ## test Server.reload(self) with IP
    # @param self The object pointer
    def testReloadIP(self):
        network = [{"dev": "eth0", "IP": ip_interface(u"192.168.0.1/24"), "gw": None}, {"dev": "eth1", "IP": ip_interface(u"192.168.1.2/24"), "gw": ip_interface(u"192.168.1.254/24")}]
        s1 = Server(self.__container_manager, "s1")
        for n in network:
            if n["gw"] is not None:
                s1.attachIP(self.__host_manager, n["dev"], n["IP"], n["gw"])
            else:
                s1.attachIP(self.__host_manager, n["dev"], n["IP"])
        s1.reload(self.__container_manager, self.__host_manager)
        ret = s1.command("ip addr show")
        for n in network:
            self.assertTrue(re.search(r"inet " + str(n["IP"]) + ".*" + n["dev"], ret.stdout))
        ret = s1.command("ip route show")
        for n in network:
            if n["gw"] is not None:
                self.assertIn("default via " + str(n["gw"].ip) + " dev " + n["dev"], ret.stdout)
예제 #17
0
class ContainerManagerImpl(ContainerManager):
    ## constructor
    # @param host The host to connect
    # @param user The login user
    # @param password The login password
    def __init__(self, host=None, user=None, password=None):
        ## remote interface
        self.__interface = RemoteInterfaceImpl(host, user, password)
        # check if docker service is running
        if self.__interface.sudo("docker info", True).rc != 0:
            raise RuntimeError("The docker service is not running at " + host)
    ## create container
    # @param self The object pointer
    # @param container The container that will be created
    # @param privilege The privilege attached to docker container
    # @param image The image of container
    def createContainerImpl(self, container, privilege=["NET_ADMIN"], hosts=[], image="local/centos"):
        cmd = "docker run --name=" + container.getName() + " --hostname=" + container.getName() + " --net=none"
        # add privilege
        for p in privilege:
            cmd += " --cap-add " + p
        # add hosts
        for h in hosts:
            cmd += " --add-host " + h["name"] + ":" + h["IP"]
        # create a new containter
        cmd += " -itd " + image + " /bin/bash"
        ret = self.__interface.sudo(cmd, True)
        if ret.rc != 0:
            raise RuntimeError("Cannot create container(" + container.getName() + "): " + ret.stderr)
    ## delete container
    # @param self The object pointer
    # @param container The container that will be created
    def destroyContainerImpl(self, container):
        # destroy the container
        ret = self.__interface.sudo("docker rm -f " + container.getName(), True)
        if ret.rc != 0:
            raise RuntimeError("Cannot destroy container(" + container.getName() + "): " + ret.stderr)
    ## execute command on container
    # @param self The object pointer
    # @param container The container that will be created
    # @param command The command to execute on container
    # @param tty Whether allocate pseudo tty
    # @return CommandResult
    def command(self, container, command, tty):
        # execute command on container
        ret = self.__interface.sudo("docker exec -i" + ("t " if tty else " ")  + container.getName() + " " + command, True)
        if ret.rc != 0:
            raise RuntimeError("Failed to execute command(\"" + command + "\") on container(" + container.getName() + "): " + ret.stderr)
        return ret
    ## attach IP to container
    # @param self The object pointer
    # @param container The container that will be created
    # @param segment The name of the segment which the IP is attached on
    # @param dev The device name of container
    # @param IP The IP attached to the container
    # @param gw The gateway address if the device is default gateway
    def attachIP(self, container, segment, dev, IP, gw):
        # execute pipework to attach IP to container
        cmd = "/usr/local/bin/pipework " + segment + " -i " + dev + " " + container.getName() + " " + str(IP)
        if gw:
            cmd += "@" + str(gw.ip)
        ret = self.__interface.sudo(cmd, True)
        if ret.rc != 0:
            raise RuntimeError("Failed to attach IP(" + str(IP) + ") to the container(" + container.getName() + "): " + ret.stdout + ret.stderr)
예제 #18
0
파일: host.py 프로젝트: ynaka81/dockerEE
 def setUp(self):
     arg = {"host": "localhost", "user": "******", "password": "******"}
     ## remote interface
     self.__interface = RemoteInterfaceImpl(**arg)
     ## host OS manager
     self.__manager = HostManagerImpl(**arg)