Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
try:
self.docker_client.swarm.init()
except docker.errors.APIError:
pass
# docker network
self.network_name = "test-network-dfple"
self.network = self.docker_client.networks.create(name=self.network_name, driver='overlay')
# docker-flow-proxy service
# dfp_image = self.docker_client.images.pull('vfarcic/docker-flow-proxy')
dfp_service = {
'name': 'proxy_{}'.format(self.test_name),
'image': 'vfarcic/docker-flow-proxy',
'constraints': [],
'endpoint_spec': docker.types.EndpointSpec(
ports={80: 80, 443: 443, 8080: 8080}),
'env': [
"LISTENER_ADDRESS=swarm_listener_{}".format(self.test_name),
"MODE=swarm",
"DEBUG=true",
"SERVICE_NAME=proxy_{}".format(self.test_name) ],
'networks': [self.network_name]
}
# docker-flow-swarm-listener service
# dfsl_image = self.docker_client.images.pull('vfarcic/docker-flow-swarm-listener')
dfsl_service = {
'name': 'swarm_listener_{}'.format(self.test_name),
'image': 'vfarcic/docker-flow-swarm-listener',
'constraints': ["node.role == manager"],
'endpoint_spec': docker.types.EndpointSpec(
win_nodes = []
linux_nodes = []
for node in nodes:
if node.startswith("windows"):
win_nodes.append(node)
else:
linux_nodes.append(node)
client = docker.DockerClient(base_url=configs.get("docker_api_url"))
if dynamic_docker_challenge.docker_image.startswith("{"):
images = json.loads(dynamic_docker_challenge.docker_image, object_pairs_hook=OrderedDict)
redis_util = RedisUtils(app)
range_prefix = redis_util.get_available_network_range()
ipam_pool = docker.types.IPAMPool(
subnet=range_prefix + '.0/24',
gateway=range_prefix + '.254'
)
ipam_config = docker.types.IPAMConfig(driver='default', pool_configs=[ipam_pool])
network_name = str(user_id) + '-' + uuid_code
network = client.networks.create(network_name, internal=True, ipam=ipam_config, attachable=True,
labels={'prefix': range_prefix}, driver="overlay", scope="swarm")
dns = []
end_ip = 250
containers = configs.get("docker_auto_connect_containers", "").split(",")
for c in containers:
if c.find("dns") != -1:
network.connect(c, ipv4_address=range_prefix + "." + str(end_ip))
dns.append(range_prefix + "." + str(end_ip))
end_ip += 1
# Create connection to docker-deamon
client = docker.DockerClient(base_url="unix://var/run/docker.sock")
# create master container
log.info("master - master read mount...")
time.sleep(1)
with open("/mnt/data/one.txt") as f:
log.info(f.read())
# create container and pass: docker-deamon socker, network and data-volume.
log.info("master - Creating container")
container = client.containers.run("test-slave",
detach=True,
mounts=[
# TODO this needs to be OS independant
docker.types.Mount(
"/var/run/docker.sock",
"//var/run/docker.sock",
type="bind"
)
],
network="isolated",
# mount the docker-volume `data` and bind it to /mnt/data
volumes={"data":{"bind": "/mnt/data", "mode": "rw"}}
)
# checking internet connection
log.info("master - master attemt to connect to the internet")
res = requests.get("https://facebook.com")
log.info(f"stat={res.status_code}")
# keep reading slave log
def create_network(self, network_name):
"""
:rtype: Network
"""
import docker
ipam_pool = docker.types.IPAMPool(
subnet=config.DOCKER_SUBNET,
gateway=config.DOCKER_GATEWAY
)
ipam_config = docker.types.IPAMConfig(
pool_configs=[ipam_pool]
)
return self.client.networks.create(
network_name,
check_duplicate=True,
ipam=ipam_config
)
# iterates over mounts to create
# a new mounts list of docker.types.Mount
container_spec['mounts'] = []
for mount in self.container_spec['mounts']:
m = dict(**mount)
if 'source' in m:
m['source'] = m['source'].format(
username=self.service_owner)
if 'driver_config' in m:
device = m['driver_config']['options']['device'].format(
username=self.service_owner
)
m['driver_config']['options']['device'] = device
m['driver_config'] = docker.types.DriverConfig(
**m['driver_config'])
container_spec['mounts'].append(docker.types.Mount(**m))
# some Envs are required by the single-user-image
container_spec['env'] = self.get_env()
if hasattr(self, 'resource_spec'):
resource_spec = self.resource_spec
resource_spec.update(user_options.get('resource_spec', {}))
if hasattr(self, 'networks'):
networks = self.networks
if user_options.get('networks') is not None:
networks = user_options.get('networks')
def setup_config(self):
container_spec = docker.types.ContainerSpec(image=self.image)
placement = docker.types.Placement(constraints=DEFAULT_CONSTRAINTS)
task_template = docker.types.TaskTemplate(container_spec=container_spec, placement=placement)
service_mode = docker.types.ServiceMode(mode="replicated", replicas=self.replicas)
endpoint_spec = docker.types.EndpointSpec(ports={14001:4000})
update_config = docker.types.UpdateConfig(parallelism=1, delay=15, failure_action="continue")
return {
"TaskTemplate": task_template,
"ServiceMode": service_mode,
"EndpointSpec": endpoint_spec,
"UpdateConfig": update_config
}
# Determine if we can extract DLL files from the full Windows base image (version 1809 and newer only)
tags = requests.get('https://mcr.microsoft.com/v2/windows/tags/list').json()['tags']
if hostRelease in tags:
# Pull the full Windows base image with the appropriate tag if it does not already exist
image = 'mcr.microsoft.com/windows:{}'.format(hostRelease)
print('Pulling full Windows base image "{}"...'.format(image))
subprocess.run(['docker', 'pull', image], check=True)
# Start a container from which we will copy the DLL files, bind-mounting our DLL destination directory
print('Starting a container to copy DLL files from...')
mountPath = 'C:\\dlldir'
container = DockerUtils.start(
image,
['timeout', '/t', '99999', '/nobreak'],
mounts = [docker.types.Mount(mountPath, dllDir, 'bind')],
stdin_open = True,
tty = True,
remove = True
)
# Copy the DLL files to the host
print('Copying DLL files to the host system...')
DockerUtils.execMultiple(container, [['xcopy', '/y', os.path.join(dllDir, dll), mountPath + '\\'] for dll in requiredDLLs])
# Stop the container
print('Stopping the container...')
container.stop()
else:
print('The following DLL files will need to be manually copied into {}:'.format(dllDir))
print('\n'.join(['- {}'.format(dll) for dll in requiredDLLs if dll not in existing]))
def build_subnet(self):
try:
#subnet_collections=[]
#chalids=redis_store.hgetall('chals')
#teamids=redis_store.hgetall('teams')
print self.config['network_prefix']+'.0.0/16'
ipam_pool = docker.types.IPAMPool(
subnet=self.config['network_prefix']+'.0.0/16'
)
ipam_config = docker.types.IPAMConfig(
pool_configs=[ipam_pool]
)
self.network=self.docker_client.networks.create(
self.config['network_name'],
driver='bridge',
ipam=ipam_config
)
return {'status':'success'}
except Exception,e:
return {'status':'fail','reason':str(e)}