Beispiel #1
0
    def test_stop_test_environment_task(self):
        """
        Test that stop task stops a running test environment
        """

        test_id = '34fe32fdsfdsxxx'
        docker = Client(version='auto')
        image = 'adsabs/pythonsimpleserver:v1.0.0'

        try:
            container = docker.create_container(
                image=image,
                name='livetest-pythonserver-{}'.format(test_id),
            )
        except errors.NotFound:
            docker.pull(image)
            container = docker.create_container(
                image='adsabs/pythonsimpleserver:v1.0.0',
                name='livetest-pythonserver-{}'.format(test_id),
            )
        except Exception as error:
            self.fail('Unknown exception: {}'.format(error))

        docker.start(container=container['Id'])

        stop_test_environment(test_id=test_id)

        self.assertFalse([i for i in docker.containers() if [j for j in i['Names'] if test_id in j]])
Beispiel #2
0
def CreateContainer():
    cli = Client()
    # FIXME check if existing
    print "Pulling docking image, first run should take long"
    cli.pull('regit/suri-buildbot')
    cli.create_container(name='suri-buildbot', image='regit/suri-buildbot', ports=[8010, 22], volumes=['/data/oisf', '/data/buildbot/master/master.cfg'])
    sys.exit(0)
Beispiel #3
0
def start_opendcre():
    """ Start the OpenDCRE container, with the appropriate ports exposed and files propped in.  At a minimum, port
    5000 must be opened, and the bmc_info.json file should be propped in as well.

    Returns: True if successful, False otherwise.

    """
    print "Starting OpenDCRE... "
    try:
        cli = Client(base_url='unix://var/run/docker.sock')
        cli.create_container(
            image='vaporio/opendcre:v1.2.2',
            detach=True,
            ports=[5000],
            volumes=['/opendcre/bmc_config.json', '/logs'],
            name='opendcre',
            command='./start_opendcre_plc_emulator.sh',
            host_config=cli.create_host_config(binds=[
                '/tmp/bmc_config.json:/opendcre/bmc_config.json', '/tmp:/logs'
            ],
                                               port_bindings={5000: [5000]}))
        cli.start('opendcre')

        # pause briefly to allow bmc scan to complete
        time.sleep(3)

        print "OpenDCRE started successfully."
        return True
    except Exception, e:
        print "Error starting OpenDCRE: {}".format(e)
        return False
Beispiel #4
0
    def setup(self):
        data_obj = data.Data()
        path = data_obj.get_work_path()

        docker = Client()

        print('Setting up environment, please wait...')

        volume = os.getcwd()

        container_name = data_obj.get_path_hash()

        docker.create_container(
            'nimbusoft/appimager',
            tty=True,
            command="/bin/bash",
            name=container_name,
            volumes=['/mnt/appimager'],
            host_config=docker.create_host_config(binds={
                os.getcwd(): {
                    'bind': '/mnt/appimager',
                    'mode': 'rw',
                }
            }))

        docker.start(container_name)
        print('Setup Complete')
Beispiel #5
0
    def test_stop_test_environment_task(self):
        """
        Test that stop task stops a running test environment
        """

        test_id = '34fe32fdsfdsxxx'
        docker = Client(version='auto')
        image = 'adsabs/pythonsimpleserver:v1.0.0'

        try:
            container = docker.create_container(
                image=image,
                name='livetest-pythonserver-{}'.format(test_id),
            )
        except errors.NotFound:
            docker.pull(image)
            container = docker.create_container(
                image='adsabs/pythonsimpleserver:v1.0.0',
                name='livetest-pythonserver-{}'.format(test_id),
            )
        except Exception as error:
            self.fail('Unknown exception: {}'.format(error))

        docker.start(container=container['Id'])

        stop_test_environment(test_id=test_id)

        self.assertFalse([
            i for i in docker.containers()
            if [j for j in i['Names'] if test_id in j]
        ])
Beispiel #6
0
 def handle(self, request, data):
     try:
         cli = Client(base_url='unix://var/run/docker.sock')
         cli.create_container(image=data['image'], name=data['name'])
     except Exception:
         exceptions.handle(request, _('Unable to create container.'))
         return False
     return True
Beispiel #7
0
class dockerAgent(object):
    """Class for manipulating the docker client."""

    host = None
    client = None
    ctr = None
    current_ctr = None

    def __init__(self):
        """Loading docker environments"""
        if platform.system() == 'Darwin' or platform.system() == 'Windows':
            try:
                # TLS problem, can be referenced from
                # https://github.com/docker/machine/issues/1335
                from docker.utils import kwargs_from_env
                self.host = '{0}'.format(urlparse.urlparse(
                    os.environ['DOCKER_HOST']).netloc.split(':')[0])
                self.client = Client(
                    base_url='{0}'.format(os.environ['DOCKER_HOST']))
                kwargs = kwargs_from_env()
                kwargs['tls'].assert_hostname = False
                self.client = Client(**kwargs)
            except KeyError:
                self.host = '127.0.0.1'
                self.client = Client(base_url='unix://var/run/docker.sock')
        else:
            self.host = '127.0.0.1'
            self.client = Client(base_url='unix://var/run/docker.sock')

    def createHostConfig(self, port_bindings, binds, links):
        """Create host config for containers"""
        return self.client.create_host_config(port_bindings=port_bindings, binds=binds, links=links)

    def startContainer(self, image, name, ports=None, volumes=None, environment=None, host_config=None):
        """Start containers"""
        try:
            self.ctr = self.client.create_container(
                image=image, name=name, ports=ports, volumes=volumes, environment=environment, host_config=host_config)
        except (TypeError, APIError), e:
            Logger.logError("\n" + "[ERROR] " + str(e.explanation))
            for line in self.client.pull(image, stream=True):
                for iterElement in list(jsoniterparse(line)):
                    Logger.logInfo(
                        "[INFO] " + json.dumps(iterElement, indent=4))
            self.ctr = self.client.create_container(
                image=image, name=name, ports=ports, volumes=volumes, environment=environment, host_config=host_config)
        except NullResource:
            pass
Beispiel #8
0
    def create_docker(self, domain, password, public_ip):
        print "create docker client"
        client = Client(base_url='unix://var/run/docker.sock', version='1.6', timeout=10)
        print "create container"
        container = client.create_container("yunohost", tty=True, detach=True, command="/sbin/init")
        print "start container"
        client.start(container["Id"])
        print "get ip"
        ip = client.inspect_container(container["Id"])["NetworkSettings"]["IPAddress"]
        print "the ip", ip

        check_container_is_ready_to_be_installed(ip)

        print "Post on the api"
        try:
            response = requests.post("https://%s/ynhapi/postinstall" % ip, data={"domain": domain, "password": password}, verify=False)
        except requests.ConnectionError as e:
            # check that the response is empty because in YUNOHOST world, a success
            # is indicated by an empty response that doesn't even respect HTTP
            # standard because YOLO SWAG
            if e.args[0].reason.line != "''":
                raise e
        else:
            if response.status_code != 200:
                print response.content
                print response.json()
                # TODO raise
                #return HttpResponse(u"Sa mère ça a merdé")

        os.system("iptables -t nat -A PREROUTING -d %s -j DNAT --to-destination %s" % (public_ip, ip))
        os.system("iptables -t nat -A POSTROUTING -s '%s/32' -o eth0 -j SNAT --to-source %s" % (ip, public_ip))

        return container["Id"]
Beispiel #9
0
def create_container(args):
    try:
        docker_cli = Client(base_url=docker_socket)
        container = docker_cli.create_container(**args)
    except Exception, e:
        log.exception('failed', e=e)
        raise
Beispiel #10
0
class docker_driver():
    def __init__(self, socket, image, launch_cmd, hostname):
        self.socket = socket
        self.image = image
        self.hostname = hostname
        self.launch_cmd = launch_cmd
        self.make_connection()

    def make_connection(self):
        self.connection = Client(self.socket)

    def launch_container(self):
        self.container_id = self.connection.create_container(
            image=self.image, tty=True, hostname=self.hostname)['Id']
        self.connection.start(self.container_id)
        exec_id = self.connection.exec_create(self.container_id,
                                              self.launch_cmd)['Id']
        self.connection.exec_start(exec_id, tty=True)
        self.container_data = self.connection.inspect_container(
            self.container_id)
        return {
            "id":
            self.container_id,
            "ip":
            self.container_data['NetworkSettings']['Networks']['bridge']
            ['IPAddress']
        }

    def teardown_container(self):
        self.connection.stop(self.container_id)
Beispiel #11
0
class ContainerServer(Server):
    def __init__(self,
                 repository=constants.DOCKER_IMAGE_NAME,
                 tag=LATEST_DOCKER_TAG_NAME):
        Server.__init__(self)
        docker_image = constants.DOCKER_IMAGE_NAME
        self.docker = Client(base_url='unix:///var/run/docker.sock')
        self.docker.pull(repository=repository, tag=tag, stream=False)
        image = '%s:%s' % (repository, tag)
        self.container = self.docker.create_container(
            image=image,
            ports=[constants.DEFAULT_NODE_BIND_PORT],
            host_config=self.docker.create_host_config(port_bindings={
                constants.DEFAULT_NODE_BIND_PORT:
                constants.DEFAULT_NODE_BIND_PORT
            }),
            command='/bin/sleep 1')
        print(self.container)

    def __del__(self):
        self.docker.remove_container(container=self.container.get('Id'))
        Server.__del__(self)

    def start(self, n=1):
        res = self.docker.start(container=self.container.get('Id'))
        print(res)
        return True

    def stop(self):
        res = self.docker.stop(container=self.container.get('Id'))
        print(res)
        return True
Beispiel #12
0
def contra_container(cli):
    cli = Client(base_url='unix://var/run/docker.sock')
    cid = None
    if cli:
        container = cli.create_container(
        image="contra:latest",
        #name="contra",
        user="******",
        working_dir="/home/contra/files",
        #command="/usr/bin/run.sh",
        stdin_open=True,
        tty=True,
        volumes=['/home/contra/artifacts'],
        host_config=cli.create_host_config(
            binds={
                appdir + '/static/artifacts': {
                        'bind': '/home/contra/artifacts',
                        'mode': 'rw',
                    },
            },
            privileged=True,
            ),
        )
        cid = container.get('Id')

    return cid
Beispiel #13
0
def node_exit_handler(addr):
    collection = db.containers
    containers = collection.find()
    resource_shares = {'high':{'cpu_shares' : 1000, 'mem_limit' : '600m'}, 'medium':{'cpu_shares' : 100, 'mem_limit' : '400m'}, 'low':{'cpu_shares' : 10, 'mem_limit' : '200m'}}
    for container in containers:
    	if container['host_ip'] == addr and container['checkpointed'] == "true":
            host_ip = choose_least_loaded(container['privelege_level'])
            cli = Client(base_url=host_ip+":2375")
            cli.pull(repository=registry+"/"+container['source_image'], tag=container['username']+"_"+container['container_name'], stream=False)
            #Create
            image_name = registry+"/"+container['source_image']+":"+container['username']+"_"+container['container_name']
            privelege_level = container['privelege_level']
            portlist = []
            portmap = {}
            if container['source_image'] == "tomcat":
                portlist.append(22)
                portmap[22] = container['ssh_port']

            host_config = cli.create_host_config(mem_limit=resource_shares[privelege_level]['mem_limit'], port_bindings=portmap)
            container_new = cli.create_container(image=image_name,cpu_shares=resource_shares[privelege_level]['cpu_shares'],host_config=host_config,ports=portlist)

            original_load = host_collection.find({"ip":host_ip})[0][privelege_level]
            host_collection.update_one({"ip":host_ip},{"$set":{privelege_level:original_load+1}})
            collection.update_one({"container_id":container['container_id']},{"$set":{"host_ip":host_ip}})
            collection.update_one({"container_id":container['container_id']},{"$set":{"container_id":container_new['Id']}})
            #Start
            if container['status'] == "Started":
                container_id = container_new['Id']
                response = cli.start(container=container_id)
                executor = cli.exec_create(container=container_id,cmd="bash service ssh start")
                response = cli.exec_start(executor.get('Id'))
    print "Failure handler called"
class Docker(object):

    def __init__(self,base_url = ''):
        self.cli = Client(base_url=base_url)
        self.containers = []
        self.images = 'docker/whalesay'

    def build(self):
        self.cli.build(path='../../dockfiles/'+self.images,rm=True,tag=self.images)

    def create(self):
        container = self.cli.create_container(image=self.images + ':latest',
                                              command='cowsay boo',detach=True,
                                              name=(self.images + ": " + (len(self.containers)-1).__str__()))
        self.containers.append(container)
        return len(self.containers) - 1

    def remove(self,num):
        self.stop(num)
        container = self.containers[num]
        self.cli.remove_container(container=container)
        self.containers.remove(num)

    def start(self,num):
        self.cli.start(container=self.containers[num])

    def stop(self,num):
        self.cli.stop(container=self.containers[num])
def run_test_container_check():
    docker_client = Client(version='auto')

    filtered_images = [i for i in docker_client.images()
                       if TEST_DOCKER_IMAGE in i['RepoTags']]

    if not filtered_images:
        LOGGER.error('Testing image not present. Pulling.')
        docker_client.pull(TEST_DOCKER_IMAGE)

    container_info = docker_client.create_container(
        image=TEST_DOCKER_IMAGE,
        command='echo "hello"'
    )
    container_id = container_info['Id']
    docker_client.start(container_id)
    return_code = docker_client.wait(container_id, timeout=TEST_RUN_TIMEOUT)
    docker_client.remove_container(container_id)
    is_ok = return_code == 0

    if not is_ok:
        LOGGER.error('Cannot run container.')
    else:
        LOGGER.info('Running test container succeeded.')
    return is_ok
Beispiel #16
0
def search(distro, package=None, binary=None):

    docker = Client(base_url='unix://var/run/docker.sock')
    search_pkgcmd = {
        'fedora': 'dnf search',
        'centos': 'dnf search',
        'ubuntu': 'apt-cache search',
        'debian': 'apt-cache search',
    }
    search_binarycmd = {
        'fedora': 'yum whatprovides',
        'centos': 'yum whatprovides',
        # XX: broken since apt-file is not
        # installed
        'ubuntu': 'apt-file search',
        'debian': 'apt-file search',
    }

    if package:
        cmd = search_pkgcmd[distro.split(':')[0]]
        search_for = package
    if binary:
        cmd = search_binarycmd[distro.split(':')[0]]
        search_for = binary

    docker.pull(distro)
    contid = docker.create_container(image='{0}'.format(distro),
                                     command='{0} {1}'.format(cmd, search_for))
    docker.start(contid)
    docker.wait(contid)
    return str(docker.logs(contid))
class DockerController():

    def __init__(self, root):
        self.workingDirectory = Path('/host')
        self.projectDirectory = Path(self.workingDirectory,
                                     Path().resolve().relative_to(root))

        self.client = Client(base_url='tcp://127.0.0.1:2375')

        binds = ['{0}:{1}'.format(root, self.workingDirectory.as_posix())]

        self.hostConfig = self.client.create_host_config(binds=binds)

    def prepare(self, image, command):
        self.container = self.client.create_container(
            image=image,
            command=command,
            volumes=self.workingDirectory.as_posix(),
            working_dir=self.projectDirectory.as_posix(),
            host_config=self.hostConfig)

    def run(self):
        self.client.start(self.container)

        logs = self.client.logs(self.container, stream=True)

        for line in logs:
            sys.stdout.write(str(line, encoding='UTF-8'))

        self.client.wait(self.container)
Beispiel #18
0
def contra_container(cli):
    cli = Client(base_url='unix://var/run/docker.sock')
    cid = None
    if cli:
        container = cli.create_container(
            image="contra:latest",
            #name="contra",
            user="******",
            working_dir="/home/contra/files",
            #command="/usr/bin/run.sh",
            stdin_open=True,
            tty=True,
            volumes=['/home/contra/artifacts'],
            host_config=cli.create_host_config(
                binds={
                    appdir + '/static/artifacts': {
                        'bind': '/home/contra/artifacts',
                        'mode': 'rw',
                    },
                },
                privileged=True,
            ),
        )
        cid = container.get('Id')

    return cid
Beispiel #19
0
class DockerTest(object):
    def __init__(self):
        self.cli = Client(base_url='unix://var/run/docker.sock')

    def build(self, dockerfile):
        dockerfile = Path(dockerfile)
        tag = 'rf-' + dockerfile.basename().replace('.dkf', '')
        dockerfile.copy('redfish-client/tests/Dockerfile')
        response = [line for line in self.cli.build(
            path='redfish-client/tests',
            tag=tag,
            rm=True)]
        return(response)

    def run(self, image, command):
        container = self.cli.create_container(image=image,
                                              command=command,
                                              tty=True,
                                              stdin_open=True)
        self.cli.start(container=container.get('Id'))
        self.cli.wait(container=container.get('Id'))
        response = self.cli.logs(container=container.get('Id'),
                                 stdout=True)
        self.cli.remove_container(container=container.get('Id'))
        return(response.decode('utf8'))
Beispiel #20
0
def run():
    code = request.form.get("code")
    runner = request.form.get("runner")

    if not code:
        return "you should send a code!", 500

    f = open("code", "w")
    f.write(code)
    f.close()
    d = Client(base_url=DOCKER_ADDRESS)
    test_connection = d.ping()
    if test_connection != "OK":
        return "docker unavaileble", 500
    container = d.create_container(image=IMAGE_NAME, command="tail -f /dev/null", detach=True)
    response = d.start(container)
    with tarfile.open("code.tar.gz", "w:gz") as tar:
        tar.add(f.name, arcname=os.path.basename(f.name))
    t = open("code.tar.gz", "rb")
    works = d.put_archive(container=container["Id"], path="/root", data=t)
    t.close()
    if not works:
        return "Can't create file in container", 500
    run = RUNNERS.get(runner, None)
    if not run:
        return "Invalid runner", 500
    exe = d.exec_create(container=container["Id"], cmd="{0} /root/code".format(run))
    gen = d.exec_start(exec_id=exe["Id"], stream=True)
    return Response(gen, mimetype="text/plain")
Beispiel #21
0
class ContainerServer(Server):
    def __init__(self, repository=constants.DOCKER_IMAGE_NAME, tag=LATEST_DOCKER_TAG_NAME):
        Server.__init__(self)
        docker_image = constants.DOCKER_IMAGE_NAME
        self.docker = Client(base_url='unix:///var/run/docker.sock')
        self.docker.pull(
            repository=repository,
            tag=tag,
            stream=False)
        image = '%s:%s' % (repository, tag)
        self.container = self.docker.create_container(
            image=image,
            ports=[constants.DEFAULT_NODE_BIND_PORT],
            host_config=self.docker.create_host_config(port_bindings={constants.DEFAULT_NODE_BIND_PORT:constants.DEFAULT_NODE_BIND_PORT}),
            command='/bin/sleep 1')
        print(self.container)

    def __del__(self):
        self.docker.remove_container(container=self.container.get('Id'))
        Server.__del__(self)

    def start(self, n=1):
        res = self.docker.start(container=self.container.get('Id'))
        print(res)
        return True

    def stop(self):
        res = self.docker.stop(container=self.container.get('Id'))
        print(res)
        return True
    def container_peripherelAccess(self, **kwargs):
        """
        - API creates container and also provides peripherel access.
        - API is equivalent to create container with host configurations added to it.
        - Response
        """
        host_config = {}
        # image = kwargs['image']
        # network_disabled = kwargs['network_disabled']
        # host_config = {'devices': '/sys/class/leds:/:rwm'}

        # print image,host_config
        invoke_clientAPI = Client(base_url='unix://var/run/docker.sock',
                                  version='1.18')

        containerID = invoke_clientAPI.create_container(
            'ubuntu',
            'true',
            stdin_open=bool('True'),
            command=list['/bin/bash'],
            host_config=invoke_clientAPI.create_host_config(
                devices=['/dev/sda:rwm']))

        # containerID = invoke_clientAPI.create_container(image)
        return containerID
def main():
    # Fetch EC2 instance tags
    tags = get_ec2_instance_tags()

    # Set IpAddress tag to instance IP address
    tags['IpAddress'] = get_ip_address()

    # Override tags using environment variables
    tags = override_tags(tags)

    # Docker Swarm join command
    commands = [
        'join', '--advertise={{ IpAddress }}:{{ Port }}', '{{ Options }}',
        '{{ DiscoveryBackend }}'
    ]

    commands = [render(x, tags) for x in commands]

    # Docker settings
    docker_api_version = render(tags.get('DockerApiVersion'), tags)
    docker_host = render(tags.get('DockerHost'), tags)

    # Default of None will cause container name to be auto-generated
    container_name = tags.get('ContainerName')

    # Start Swarm container
    cli = Client(base_url=docker_host, version=docker_api_version)

    cli.pull('swarm', tag='latest')

    container = cli.create_container(image='swarm',
                                     name=container_name,
                                     command=[x for x in commands if x])

    cli.start(container=container.get('Id'))
Beispiel #24
0
def updateBuild(strURL):
    processBuild(strURL)
    cli = Client('unix://var/run/docker.sock')
    containers = cli.containers()
    images = cli.images()
    pContID = SERVER_CONFIG.get('PRIMARY_CONTAINER', 'id')
    pCmnd = SERVER_CONFIG.get('PRIMARY_CONTAINER', 'command')
    sContID = SERVER_CONFIG.get('SECONDARY_CONTAINER', 'id')
    for container in containers:
        if container["Id"] == pContID:
            createdCont = cli.create_container(image=container["Image"],
                                               command=str(pCmnd),
                                               tty=True)
            response = cli.start(container=createdCont.get('Id'))
            sContID = str(createdCont.get('Id'))
            print " Started copy of primary container " + str(
                createdCont.get('Id')) + " Now going to redirect traffic! "
            continue
    secIP = cli.inspect_container(sContID)
    lJsecIp = secIP['NetworkSettings']['IPAddress']
    #dJsecIp = secIP.pop(0)
    print str(lJsecIp)
    #redirecSecTraffic()
    #scriptExecutor(pContID)
    #redirecPriTraffic()
    print " Stopping and removing secondary container created "
    cli.stop(sContID)
    remRsp = cli.remove_container(sContID, force=True)
    print str(remRsp)
    return "Hello World" + str("\n") + str(containers) + str(pContID) + str(
        sContID) + str(response)
Beispiel #25
0
def updateBuild(strURL):
	processBuild(strURL)
	cli = Client('unix://var/run/docker.sock')
	containers = cli.containers()
	images = cli.images()
	pContID = SERVER_CONFIG.get('PRIMARY_CONTAINER','id')
	pCmnd = SERVER_CONFIG.get('PRIMARY_CONTAINER','command')
	sContID = SERVER_CONFIG.get('SECONDARY_CONTAINER','id')
	for container in containers:
		if container["Id"] == pContID:
			createdCont = cli.create_container(image=container["Image"], command=str(pCmnd), tty=True)
			response = cli.start(container=createdCont.get('Id'))
			sContID = str(createdCont.get('Id'))
			print " Started copy of primary container " + str(createdCont.get('Id')) + " Now going to redirect traffic! "
			continue
	secIP = cli.inspect_container(sContID)
	lJsecIp = secIP['NetworkSettings']['IPAddress']
	#dJsecIp = secIP.pop(0)
	print str(lJsecIp)
	#redirecSecTraffic()
	#scriptExecutor(pContID)
	#redirecPriTraffic()
	print " Stopping and removing secondary container created "
	cli.stop(sContID)
	remRsp = cli.remove_container(sContID, force=True)
	print str(remRsp)
	return "Hello World" + str("\n")  + str(containers) + str(pContID) + str(sContID) + str(response)
Beispiel #26
0
class DockerModule:
    def __init__(self):
        try:
            self.client = Client("tcp://10.100.0.165:2376", version="auto")
        except Exception as e:
            print('Falhou ao conectar no docker: ', e)

    def list_containers(self):
        containers = self.client.containers(all=True)
        return containers

    def start_container(self, id):
        res = self.client.start(container=id)
        return res

    def stop_container(self, id):
        res = self.client.stop(container=id)
        return res

    def delete_container(self, container):
        self.stop_container(container)
        self.client.remove_container(container=container)
        return "Container removido com sucesso"

    def create_container(self, **kwargs):
        self.client.pull(kwargs.get("image"))
        res = self.client.create_container(name=kwargs.get("name"),
                                           image=kwargs.get("image"),
                                           command=kwargs.get("command"),
                                           stdin_open=True,
                                           detach=True,
                                           tty=True)
        return res
Beispiel #27
0
def run(Name, Mail, CPU, Mem):
    if 'username' in session:
        import hashlib
        import random
        ans = random.uniform(1, 10)
        hashpass = hashlib.sha1(str(ans).replace('\n',
                                                 '').encode()).hexdigest()
        print(hashpass)
        User.addIns(Name, hashpass)
        subprocess.call('useradd ' + Name + ' -m -p ' + str(hashpass) +
                        ' -s /bin/hshell',
                        shell=True)
        subprocess.call('gpasswd -a ' + Name + ' docker', shell=True)
        clir = Client(base_url='unix://var/run/docker.sock')
        clirt = clir.create_container(hostname=str(Name + '-dind'),
                                      tty=True,
                                      detach=True,
                                      image='hakurei-dind',
                                      name=str(Name),
                                      cpu_shares=int(CPU),
                                      host_config=clir.create_host_config(
                                          mem_limit=str(Mem), privileged=True))
        clir.start(clirt.get('Id'))
        print(clirt.get('Id'))
        print(Mail)
        return redirect(url_for('userview'))
    else:
        return redirect(url_for('main.index'))
Beispiel #28
0
class DockerManager:
    def __init__(self):
        try:
            self.cli = Client(base_url="tcp://0.0.0.0:2376", version='auto')
        except Exception as e:
            raise Exception(e)

    def getContainers(self, todos=True):
        try:
            return [c for c in self.cli.containers(all=todos)]
        except Exception as e:
            raise Exception(e)

    def createContainer(self, nome, hn):
        try:
            container = self.cli.create_container(name=nome,
                                                  hostname=hn,
                                                  image="debian",
                                                  detach=True,
                                                  stdin_open=True,
                                                  tty=True)
            self.cli.start(container=container.get('Id'))
            return container
        except Exception as e:
            raise Exception(e)

    def inspectContainer(self, container_id):
        try:
            container = self.cli.inspect_container(container_id)
            return container
        except Exception as e:
            raise Exception(e)
Beispiel #29
0
class DockerClient(object):
    def __init__(self):
        self.client = Client(base_url='unix://var/run/docker.sock')

    def build_images(self, dockerfile: str, tag: str):
        with open(dockerfile) as file:
            dkfile = BytesIO(file.read().encode('utf-8'))
        response = [line for line in self.client.build(
            fileobj=dkfile, rm=True, tag=tag)]
        return response

    def run_container(self, image, mem_limit=None, volume_binds: list = None, command=None):
        container = self.client.create_container(image=image,
                                                 host_config=self.client.create_host_config(
                                                     binds=volume_binds, mem_limit=mem_limit), command=command)
        self.client.start(container)
        try:
            self.client.wait(container, timeout=3)
        except ReadTimeout:
            print('time out')
        self.client.stop(container)
        self.client.remove_container(container)

    def exec_container(self, container, cmd):
        container_id = self.client.exec_create(container, cmd)['Id']
        return self.client.exec_start(container_id)
Beispiel #30
0
def reset_container(client: docker.Client, session, n=0, image='noodles-remote'):
    host_config = client.create_host_config(port_bindings={22: (10022 + n*100)})
    container = client.create_container(
        image=image, host_config=host_config, labels={'noodles': str(n), 'session': session})
    client.start(container)
    time.sleep(0.5)
    return container
Beispiel #31
0
class DexterModule(SSHModule):
    def __init__(self):
        try:
            self.cli = Client(base_url="tcp://192.168.0.2:2376",
                              version="auto")
            SSHModule.__init__(self)
        except Exception as e:
            print "Falha ao conectar ao servidor: ", e

    def create_container(self, name):
        try:
            print "[+] Creating container: ", name
            container = self.cli.create_container(image="ubuntu",
                                                  name=name,
                                                  command="/bin/bash",
                                                  detach=True,
                                                  tty=True,
                                                  stdin_open=True)
            self.cli.start(container=container.get("Id"))
        except Exception as e:
            print "Falha ao criar container: ", e

    def exec_command(self, container, cmd):
        try:
            print "[+] Running command: ", cmd
            command = "docker exec %s %s" % (container, cmd)
            print self.execCommand(command)
        except Exception as e:
            print "Falhou ao executar o comando:", e
Beispiel #32
0
class DockerOps:

	def __init__(self):
	   try:
            config_parser = ConfigParser.ConfigParser()
            config_parser.read("/opt/4linux/beavops.ini")
            self.docker = Client(base_url=config_parser.get("docker","docker.server"))
        except Exception as e:
            logging.error("[-] Falhou ao conectar na api %s",e)

	def MostrarContainers(self):
		for d in self.docker.containers():
			print d['Names'], d['Id']

	def CriarContainer(self,aluno):
		try:
			logging.info("[+] Criando Container do aluno %s",aluno)
			container = self.docker.create_container(image="webservercloud",hostname="webservercloud", command="/bin/bash",name=aluno,tty=True)
			print container.get("Id")
			response = self.docker.start(container=container.get("Id"))
		except Exception as e:
			logging.error("[-] Falhou ao criar o container %s",e)

	def RemoverContainer(self,aluno):
		try:
			container = self.docker.stop(container=aluno)
			container = self.docker.remove_container(container=aluno)
			logging.info("[+] Removendo Container do aluno %s",aluno)
		except Exception as e:
			logging.error("[-] Erro ao remover o container %s",e)

if __name__ == '__main__':
	do = DockerOps()
	#do.MostrarContainers()
	do.CriarContainer("teste")
Beispiel #33
0
class DockerTest(object):
    def __init__(self):
        self.cli = Client(base_url='unix://var/run/docker.sock')

    def build(self, dockerfile):
        dockerfile = Path(dockerfile)
        tag = 'rf' + dockerfile.basename().replace('Dockerfile.', '')
        dockerfile.copy('redfish-client/tests/Dockerfile')
        response = [line for line in self.cli.build(
            path='redfish-client/tests',
            tag=tag,
            rm=True)]
        return(response)

    def run(self, image, command):
        container = self.cli.create_container(image=image,
                                              command=command,
                                              tty=True,
                                              stdin_open=True)
        self.cli.start(container=container.get('Id'))
        self.cli.wait(container=container.get('Id'))
        response = self.cli.logs(container=container.get('Id'),
                                 stdout=True)
        self.cli.remove_container(container=container.get('Id'))
        return(response.decode('utf8'))
Beispiel #34
0
class Docker:
    def __init__(self):
        self.cli = Client(base_url="tcp://10.100.0.116:2376", version="auto")

    def get_containers(self, all=True):
        return [ c for c in self.cli.containers(all=all) ]

    def start_container(self, name):
        return self.cli.start(name)

    def stop_container(self, name):
        return self.cli.stop(name)

    def restart_container(self, name):
        return self.cli.restart(name)

    def create_container(self, name, command, image):
        return self.cli.create_container(
            name=name,
            command=command,
            image=image
        )

    def remove_container(self, name):
        return self.cli.remove_container(name)
def run():
    if 'username' in session:
        clir = Client(base_url='tcp://'+ session['username'] +'.docker:14438')
        clirt = clir.create_container(tty=True, detach=True, image='0muproject/0mu-flask', name='0mu-Flask-06', ports=['8510', '22'], host_config=clir.create_host_config(port_bindings={8510: 8510, 22: 2222}))
        clir.start(clirt.get('Id'))
        return redirect(url_for('dockerview'))
    else:
        return redirect(url_for('main.index'))
Beispiel #36
0
class DockerModulo:
    def __init__(self):

        try:
            self.cli = Client(base_url="tcp://192.168.0.2:2376",
                              version='auto')
        except Exception as e:
            raise Exception(e)

    def getContainers(self, todos=True):

        try:
            return [c for c in self.cli.containers(all=todos)]
        except Exception as e:
            raise Exception(e)

    def startContainer(self, id):
        return self.cli.start(container=id)

    def stopContainer(self, id):
        return self.cli.stop(container=id)

    def createContainer(self, nome, hn, img):
        try:
            container = self.cli.create_container(name=nome,
                                                  hostname=hn,
                                                  image=img,
                                                  detach=True,
                                                  stdin_open=True,
                                                  tty=True)

            self.cli.start(container=container.get('Id'))
            return container

        except Exception as e:
            raise Exception(e)

    def removeContainer(self, id):
        self.cli.stop(container=id)
        return self.cli.remove_container(id)


# if __name__ == '__main__':
# 	try:

# 		manager = DockerManager()

# 		for c in manager.getContainers():
# 			print c

# 	except Exception as e:
# 		print "Falhou: %s" % e

# # 	for c in cli.containers():
# # 		print c

# # except Exception as e:
# # 	print e
Beispiel #37
0
def test_instance_activate_links_no_service(agent, responses):
    _delete_container('/c861f990-4472-4fa1-960f-65171b544c28')
    _delete_container('/target_redis')
    _delete_container('/target_mysql')

    client = Client()
    c = client.create_container('ibuildthecloud/helloworld',
                                ports=['3307/udp', '3306/tcp'],
                                name='target_mysql')
    client.start(c,
                 port_bindings={
                     '3307/udp': ('127.0.0.2', 12346),
                     '3306/tcp': ('127.0.0.2', 12345)
                 })

    c = client.create_container('ibuildthecloud/helloworld',
                                name='target_redis')
    client.start(c)

    def post(req, resp):
        del resp['data']['instance']['+data']['dockerInspect']
        docker_container = resp['data']['instance']['+data']['dockerContainer']
        id = docker_container['Id']
        fields = resp['data']['instance']['+data']['+fields']
        del docker_container['Created']
        del docker_container['Id']
        del docker_container['Status']
        docker_container = _sort_ports(docker_container)
        del docker_container['Ports'][0]['PublicPort']
        del docker_container['Ports'][1]['PublicPort']
        del fields['dockerIp']
        assert fields['dockerPorts']['8080/tcp'] is not None
        assert fields['dockerPorts']['12201/udp'] is not None
        fields['dockerPorts']['8080/tcp'] = '1234'
        fields['dockerPorts']['12201/udp'] = '5678'

        inspect = Client().inspect_container(id)

        # TODO: This seems like a bug in docker, but 'HostConfig.Links' is
        # never set
        assert inspect['HostConfig']['Links'] is None

    event_test(agent,
               'docker/instance_activate_links_no_service',
               post_func=post)
Beispiel #38
0
def create_container(internal_port, docker_image, startup_command):
    """ This task takes care of launching docker containers. """
    # Let's get a hold of the docker socket first.
    api = Client(base_url=DOCKER_SOCKET)
    container_config, hash = build_container_config(internal_port,
                                                    docker_image,
                                                    startup_command)
    container = api.create_container(**container_config)
    return container['Id'], hash
class DockerManager:
    """The DockerManager provides a way to manage a Docker engine."""

    def __init__(self, docker_url):
        """docker_url is the URL to the docker engine. It can either be the URL
        to the docker engine API or a path to the Docker socket.
        """
        self.client = Client(docker_url)

    def count_containers_by_image(self, container_image):
        """Iterates through all running containers to count the number
        of running containers associated with a container image name.
        Returns the number of running container.
        """
        containers = self.client.containers()
        service_container_count = 0
        for container in containers:
            if container['Image'] == container_image:
                service_container_count += 1
        return service_container_count

    def stop_container_by_image(self, container_image):
        """Iterates through all running containers to stop the first
        container that match a container image name.
        """
        containers = self.client.containers()
        for container in containers:
            if container['Image'] == container_image:
                self.client.kill(container['Id'])
                break

    def create_container(self, service_definition):
        """Creates a new container based on a service definition object."""
        container = self.client.create_container(
            image=service_definition['image'],
            command=service_definition['command'],
            ports=service_definition['ports'],
            environment=service_definition['environment'],
            host_config=utils.create_host_config(publish_all_ports=True))
        self.client.start(container.get('Id'))

    def ensure_containers_for_service(self,
                                      service_definition,
                                      container_number):
        """Ensures that a number of container are running for a service.
        Based on the *container_number* parameter it will stop/create
        containers to match this value.
        """
        service_container_count = self.count_containers_by_image(
            service_definition['image'])
        while service_container_count != container_number:
            if service_container_count > container_number:
                self.stop_container_by_image(service_definition['image'])
                service_container_count -= 1
            elif service_container_count < container_number:
                self.create_container(service_definition)
                service_container_count += 1
Beispiel #40
0
class DockerManager:
    def __init__(self):
        try:
            self.client = Client(base_url='unix://var/run/docker.sock')
        except Exception as e:
            print('Fail %s' %e)

    def inspect_container(self, container_id):
        try:
            print(self.client.inspect_container(container_id))
        except Exception as e:
            print('Fail %s' %e)

    def create_container(self, name, hostname, image):
        try:
            self.client.create_container(
                name=name,
                hostname=hostname,
                image=image,
                command='/bin/bash',
                detach=True,
                stdin_open=True,
                tty=True
            )
        except Exception as e:
            print('Fail %s' %e)

    def print_container(self, container):
        network = list(container.get('NetworkSettings').get('Networks').keys())[0]

        print('Container: %s' %container.get('Names')[0][1:])
        print('State: %s' % container.get('State'))
        print('Status: %s' % container.get('Status'))
        print('Rede: %s' %network)
        print('IP: %s' %container.get('NetworkSettings').get('Networks').get(network).get('IPAddress'))
        print('--------------------------------')

    def get_containers(self):
        try:
            for cli in self.client.containers(all=True):
                self.print_container(cli)

        except Exception as e:
            print('Fail %s' %e)
Beispiel #41
0
    def post(self, request):
        form = self.form_class(request.POST)
        if form.is_valid():
            sensor = SensorDetail()

            # cleaned (normalized) data
            sensor.sensor_id = self.get_sensor_id()
            sensor.station_name = form.cleaned_data['station_name']
            sensor.station_desc = form.cleaned_data['station_desc']
            sensor.sensor_type = form.cleaned_data['sensor_type']
            sensor.latitude = form.cleaned_data['latitude']
            sensor.longitude = '-' + form.cleaned_data['longitude']
            sensor.location = form.cleaned_data['location']
            sensor.sensorOwner = request.user
            tag = form.cleaned_data['sensor_type']

            form = self.form_class(None)
        available_sensors = SensorDetail.objects.filter(
            sensorOwner=request.user)

        # Container creation

        dockerClient = Client('unix://var/run/docker.sock', version='auto')
        # host_config = dockerClient.create_host_config(port_bindings={1111: 4567,2222: None}

        # dockerClient = docker.from_env()
        global DOCKER_USERNAME
        global DOCKER_PASSWORD
        global DOCKER_REPO
        dockerClient.login(DOCKER_USERNAME, DOCKER_PASSWORD)

        dockerClient.pull(DOCKER_REPO, stream=True)
        container = dockerClient.create_container(image=DOCKER_REPO,
                                                  environment={
                                                      'sensortype':
                                                      sensor.sensor_type,
                                                      'sensorid':
                                                      sensor.sensor_id
                                                  })

        sensor.container_id = container.get('Id')
        dockerClient.start(container)
        # ami = getImageID(tag)
        # sensor.ip_address = createServer(ami, tag)
        sensor.save()
        return render(
            request, self.template_name, {
                'form':
                form,
                'available_sensors':
                available_sensors,
                'sensor':
                sensor,
                'success_msg':
                'Sensor ' + str(sensor.sensor_id) + ' added successfully'
            })
Beispiel #42
0
def test_instance_activate_links_no_service(agent, responses):
    _delete_container('/c861f990-4472-4fa1-960f-65171b544c28')
    _delete_container('/target_redis')
    _delete_container('/target_mysql')

    client = Client()
    c = client.create_container('ibuildthecloud/helloworld',
                                ports=['3307/udp', '3306/tcp'],
                                name='target_mysql')
    client.start(c, port_bindings={
        '3307/udp': ('127.0.0.2', 12346),
        '3306/tcp': ('127.0.0.2', 12345)
    })

    c = client.create_container('ibuildthecloud/helloworld',
                                name='target_redis')
    client.start(c)

    def post(req, resp):
        del resp['data']['instance']['+data']['dockerInspect']
        docker_container = resp['data']['instance']['+data']['dockerContainer']
        id = docker_container['Id']
        fields = resp['data']['instance']['+data']['+fields']
        del docker_container['Created']
        del docker_container['Id']
        del docker_container['Status']
        docker_container = _sort_ports(docker_container)
        del docker_container['Ports'][0]['PublicPort']
        del docker_container['Ports'][1]['PublicPort']
        del fields['dockerIp']
        assert fields['dockerPorts']['8080/tcp'] is not None
        assert fields['dockerPorts']['12201/udp'] is not None
        fields['dockerPorts']['8080/tcp'] = '1234'
        fields['dockerPorts']['12201/udp'] = '5678'

        inspect = Client().inspect_container(id)

        # TODO: This seems like a bug in docker, but 'HostConfig.Links' is
        # never set
        assert inspect['HostConfig']['Links'] is None

    event_test(agent, 'docker/instance_activate_links_no_service',
               post_func=post)
Beispiel #43
0
def createMcInstance(port):
        directory = "/mnt/mc" + str(port)
        try:
                os.mkdir(directory)
        except:
                if debug == 1: print "Directory already exists!"
        c = Client(base_url='unix://var/run/docker.sock')
        container = c.create_container(image=imageName, ports=[25565], command='/start')
        c.start(container, port_bindings={25565: ('0.0.0.0', port)})
	return container
class DockerManager:
    """The DockerManager provides a way to manage a Docker engine."""
    def __init__(self, docker_url):
        """docker_url is the URL to the docker engine. It can either be the URL
        to the docker engine API or a path to the Docker socket.
        """
        self.client = Client(docker_url)

    def count_containers_by_image(self, container_image):
        """Iterates through all running containers to count the number
        of running containers associated with a container image name.
        Returns the number of running container.
        """
        containers = self.client.containers()
        service_container_count = 0
        for container in containers:
            if container['Image'] == container_image:
                service_container_count += 1
        return service_container_count

    def stop_container_by_image(self, container_image):
        """Iterates through all running containers to stop the first
        container that match a container image name.
        """
        containers = self.client.containers()
        for container in containers:
            if container['Image'] == container_image:
                self.client.kill(container['Id'])
                break

    def create_container(self, service_definition):
        """Creates a new container based on a service definition object."""
        container = self.client.create_container(
            image=service_definition['image'],
            command=service_definition['command'],
            ports=service_definition['ports'],
            environment=service_definition['environment'],
            host_config=utils.create_host_config(publish_all_ports=True))
        self.client.start(container.get('Id'))

    def ensure_containers_for_service(self, service_definition,
                                      container_number):
        """Ensures that a number of container are running for a service.
        Based on the *container_number* parameter it will stop/create
        containers to match this value.
        """
        service_container_count = self.count_containers_by_image(
            service_definition['image'])
        while service_container_count != container_number:
            if service_container_count > container_number:
                self.stop_container_by_image(service_definition['image'])
                service_container_count -= 1
            elif service_container_count < container_number:
                self.create_container(service_definition)
                service_container_count += 1
Beispiel #45
0
class DockerAPI(SSHAPI):
    def __init__(self):
        try:
            SSHAPI.__init__(self)
            config = ConfigParser.ConfigParser()
            config.read("deploy.cfg")
            self.docker_client = Client("tcp://%s:2376"%config.get("docker","server"))
        except Exception as e:
            print "Falhou ao conectar com Docker:",e

    def  list_Container(self):
         for c in self.docker_client.containers(all=True):
            print c.get("Names")

    def create_container(self,nome,imagem="ubuntu"):
        res = self.docker_client.create_container(name=nome,image=imagem,
                                                  command="/bin/bash",
                                                  tty=True,
                                                  stdin_open=True,
                                                  detach=True)
        if res:
            return res

        else:
            print " Falhou ao criar o container ",res

    def start_container(self,id):
        try:
            self.docker_client.start(container=id)
            print "Container executado"
        except Exception as e:
            print " Falhou ao iniciar o container ",e

    def get_container(self,nome):
        try:
            todos = self.docker_client.containers(all=True)
          
            nome = "/"+nome
            
            container = [ c for c in todos if nome in c.get("Names") ][0]
            return container
        except Exception as e:
            print " Falhou ao buscar container",e

    def _exec(self,container,cmd):
        c = "docker exec %s %s "%(container,cmd)
        self.exec_ssh_command(c)

    def get_container_address(self,nome):
        address = self.get_container(nome)
        address = address.get("NetworkSettings")\
                         .get("Networks").get("bridge")\
                         .get("IPAddress")
        return address       
Beispiel #46
0
def create(imagename):
	"""Create a container from a image.
    Args:
        imagename: the image name.
    """
	try:
		cli = Client(base_url=url)
		cli.containers()
		container = cli.create_container(image=imagename, command='/bin/sleep 30')
		print(container["Id"][:11] + " has been created.")
	except Exception,e: print str(e)
Beispiel #47
0
def startContainer1():
        cli = Client(base_url=DOCKER_HOST)
        print('container=',cli.containers())
        
        cli.stop("lighting1")
        cli.remove_container("lighting1")
        container = cli.create_container(image='aadebuger/lightingserver',name="lighting1",ports=[9090],
    host_config=cli.create_host_config(port_bindings={
        9090: 9093
    }))
        cli.start(container)
Beispiel #48
0
def create(name, image, server, force=False):
  #force can be set with a registry url value
  c=Client('http://'+server)
  if not c.images(name=image):
    if force:
      r=requests.get('http://'+force+'/v1/search')
      if r.status_code == 200:
        for i in r.json()['results']:
          if image.split('/').pop() == i['name'].split('/').pop():
            out=c.pull(force+'/'+image.split('/').pop(),insecure_registry=True,stream=False)
            if not re.search('errorDetail', out):
              r=c.create_container(image=image, network_disabled=True, name=name)
              return r['Id']
            else:
              return False
      else:
        return False
  else: 
    r=c.create_container(image=image, network_disabled=True, name=name)
    return r['Id']
Beispiel #49
0
def increase_test_clients():
    cli = DClient(base_url='tcp://163.180.117.44:4243')
    data = request.get_json()
    clients = int(int(data['clients']) / 20)

    for i in range(clients):
        container = cli.create_container(image='client', detach=True, environment={
                     'RUN_MODE': 'publish', 'TEST_CASE': '1', 'QOS': '1', 'THREAD': '20'
                    })
        cli.start(container=container.get('Id'))
    return '클라이언트 추가 완료'
Beispiel #50
0
    def download(self):
        self.cleanworkspace()

        container_name = 'resinos'

        try:
            cli = Client(base_url='unix://var/run/docker.sock', version='auto')
        except:
            log.warn(
                "Can't connect to docker daemon. Trying the rce socket...")
            try:
                cli = Client(base_url='unix://var/run/rce.sock',
                             version='auto')
            except:
                log.error("Can't connect to rce daemon.")
                return False

        # Pull docker image
        try:
            log.info(
                "Docker image pull started... this can take a couple of minutes..."
            )
            log.debug("Pulling " + self.remotefile + " ...")
            cli.pull(self.remotefile, stream=False)
        except:
            log.error("Can't pull update image.")
            return False

        # Make sure there is no 'resinhup' container
        try:
            cli.remove_container(container_name, force=True)
        except:
            pass

        # Create resinhup container
        try:
            cmd = '/bin/bash'
            container = cli.create_container(image=self.remotefile,
                                             command=cmd,
                                             name=container_name)
        except:
            log.error("Can't create temporary update container.")
            return False

        # Export the temporary resinhup container as tar archive
        try:
            strm = cli.export(container=container.get('Id'))
        except:
            log.error("Can't export tar archive update file.")
            return False
        self.updatefilestream = strm

        return True
Beispiel #51
0
    class Sloth(cls):
        def __init__(self, config):
            super().__init__(config)

            self._docker_config = extension['config']

            self._docker_client = Client(self._docker_config.get('base_url'),
                                         timeout=10)

            self._docker_client._version = str(
                self._docker_config.get('version')
                or self._docker_client._version)

            self._docker_image = self._docker_config.get('image') or slugify(
                self.listen_point)

        def execute(self, action):
            '''Execute an action inside a container, then commit the changes to the image and remove the container.

            :param action: action to be executed

            :returns: True if the execution was successful; raises exception otherwise
            '''

            self.processing_logger.info('Executing action: %s', action)

            try:
                container_id = self._docker_client.create_container(
                    self._docker_image,
                    command=action,
                    working_dir=self.config.get('work_dir') or '.',
                    mem_limit=self._docker_config.get('memory_limit') or 0,
                    cpu_shares=self._docker_config.get('cpu_share')
                    or None)['Id']

                self._docker_client.start(container_id)

                for log in self._docker_client.attach(container_id,
                                                      logs=True,
                                                      stream=True):
                    self.processing_logger.debug('%s', log)

                self._docker_client.commit(container_id,
                                           self._docker_image,
                                           message=action)

                self._docker_client.remove_container(container_id)

                self.processing_logger.info('Action executed: %s', action)
                return True

            except Exception:
                raise
Beispiel #52
0
    def setup(self):
        data_obj = data.Data()
        path = data_obj.get_work_path()

        docker = Client()

        print('Setting up environment, please wait...')

        volume = os.getcwd()

        container_name = data_obj.get_path_hash()

        docker.create_container('nimbusoft/appimager', tty=True, command="/bin/bash", name=container_name, volumes=['/mnt/appimager'],
            host_config=docker.create_host_config(binds={
                os.getcwd(): {
                    'bind': '/mnt/appimager',
                    'mode': 'rw',
                }
            }))

        docker.start(container_name)
        print('Setup Complete')
Beispiel #53
0
    def deployServer(self, auth, zone_id, req):
        """
        @param : auth
            {"auth":{
               "access_key_id":"ACCESS Key ID",
               "secret_access_key":"Secret Access Key",
                }
            }
        @param: zone_id
        @param: req (Dic)
        """
        # 1. Get Endpoint of Zone
        cloudMgr = self.locator.getManager('CloudManager')
        (r_name, z_name) = cloudMgr._getRegionZone(zone_id)

        docker_info = cloudMgr._getZoneDetail(zone_id)
        self.logger.debug(docker_info)
        base_url = docker_info['DOCKER_HOST']
        # 2. Create docker client
        client = Client(base_url=base_url)

        # 3. Create Server
        # Add placement based on zone_name
        self.logger.debug(req)

        # Pull Image first
        pulled = client.pull(req['image'], stream=True)
        self.logger.debug("Pulled Imaged:%s" % pulled)

        container = client.create_container(**req)
        response = client.start(container=container.get('Id'))
        self.logger.debug(response)

        inspect = client.inspect_container(container.get('Id'))
        self.logger.debug(inspect)
      
        server = {}
        server['server_id'] = inspect['Id']
        server['private_ip_address'] = inspect['NetworkSettings']['IPAddress']
        self.logger.debug("Create Server => private IP:%s" % server['private_ip_address'])
        server['floating_ip'] = inspect['Node']['IP']
        # (TODO) This may be private IP
        # If it is related with Docker Swarm cluster 
        # Find floating IP address of node
        server['status'] = inspect['State']['Status']

        # CPU, Memory, Disk
        # based on instance_type, get cpu, memory, disk size manaually
        # notice: There are no API for get CPU, Memory, Disk

        return server
Beispiel #54
0
def tutum_hello_world(request):
    from docker import Client
    cli = Client(base_url='unix://var/run/docker.sock')
    cli.pull('tutum/hello-world')
    container = cli.create_container(
        image='tutum/hello-world')
    cli.start(container=container.get('Id'))

    def stop():
        cli.stop(container)
        cli.remove_container(container)

    request.addfinalizer(stop)
    return container
Beispiel #55
0
def do_docker_create(self, label, parameters, environment, name, image,
                     volumes, memory_limit, folders, command):
    """
    Create necessary directories in a working directory
    for the mounts in the containers.

    Write .ini file filled with given parameters in each folder.

    Create a new docker container from a given image and
    return the id of the container
    """
    # Create needed folders for mounts
    for folder in folders:
        try:
            os.makedirs(folder, 0o2775)
        # Path already exists, ignore
        except OSError:
            if not os.path.isdir(folder):
                raise

    # Create ini file for containers
    config = configparser.SafeConfigParser()
    for section in parameters:
        if not config.has_section(section):
            config.add_section(section)
        for key, value in parameters[section].items():

            # TODO: find more elegant solution for this! ugh!
            if not key == 'units':
                if not config.has_option(section, key):
                    config.set(*map(str, [section, key, value]))

    for folder in folders:
        with open(os.path.join(folder, 'input.ini'), 'w') as f:
            config.write(f)  # Yes, the ConfigParser writes to f

    # Create docker container
    client = Client(base_url='http://localhost:4000')
    # We could also pass mem_reservation since docker-py 1.10
    config = client.create_host_config(binds=volumes, mem_limit=memory_limit)
    container = client.create_container(
        image,  # docker image
        name=name,
        host_config=config,  # mounts
        command=command,  # command to run
        environment=environment,  # {'uuid' = ""} for cloud fs sync
        labels=label  # type of container
    )
    container_id = container.get('Id')
    return container_id, ""
Beispiel #56
0
class Container(object):
    """容器类,用于创建,销毁,停止,暂停,恢复容器等操作"""

    def __init__(self):
        #initial base config
        self.cli = Client(base_url=DOCKER_BASE_URL, version='auto')
        self.logger = MyLogger()
        self.db = Database()

    def generate_string(self, size=8):
        """生成指定长度的随机字符串"""
        return ''.join(
            random.choice(string.ascii_lowercase + string.ascii_uppercase +
                          string.digits) for _ in range(size))

    def create_container(self, tid, mem_limit, hostname, image_name):
        """  create a container and update status """
        #create random mysql_password
        mysql_password = self.generate_string(8)
        self.logger.writelog('create mysql password %s' % mysql_password)
        self.logger.writelog(
            "create container with image name %s and hostname %s " %
            (image_name, hostname))
        try:
            c = self.cli.create_container(image=image_name,environment={'MYSQL_PASSWORD':mysql_password},\
                        name=hostname,hostname=hostname, detach=False,tty=False,ports=[22,3306,80],\
                        host_config = self.cli.create_host_config(publish_all_ports=True,mem_limit = mem_limit))
            docker_id = c.get('Id')
            self.logger.writelog('container id: %s' % docker_id)
            self.start_container(docker_id, tid)
            #get IP address
            ip = self.cli.inspect_container(
                docker_id)['NetworkSettings']['IPAddress']
            #get port mapping
            ssh_port = self.cli.port(docker_id, '22')[0]['HostPort']
            db_port = self.cli.port(docker_id, '3306')[0]['HostPort']
            web_port = self.cli.port(docker_id, '80')[0]['HostPort']
            sql = """insert into instances(tid,did,ip,hostname,dbport,webport,sshport,dbpwd) values('%s','%s','%s','%s','%s','%s','%s','%s');""" % (
                tid, docker_id, ip, hostname, db_port, web_port, ssh_port,
                mysql_password)
            self.logger.writelog("insert record in instances table")
            self.db.execute(sql)
            self.logger.writelog("update task status:%d" % ST_RUNNING)
            self.db.update_status(tid, ST_RUNNING)
            return docker_id
        except Exception, err:
            #create failed
            self.logger.writelog('create failed: %s ' % err, self.logger.error)
            self.db.update_status(tid, ST_UNKNOWN)
            return False