File size: 2,981 Bytes
fb361ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import asyncio
import fcntl
import hashlib
import json
from pathlib import Path
import subprocess
import tempfile
from harbor.environments.docker.docker import DockerEnvironment

class StrictDocker(DockerEnvironment):
    def __init__(self,*args,**kwargs):
        super().__init__(*args,**kwargs)
        self._strict_network_name='strict-eval-'+hashlib.sha256(self.session_id.encode()).hexdigest()[:18]
        self._strict_overlay_dir=tempfile.TemporaryDirectory(prefix='strict-net-')
        self._strict_overlay=Path(self._strict_overlay_dir.name)/'compose.json'
        overlay={'networks':{'default':{'external':True,'name':self._strict_network_name}}}
        if self.environment_name.startswith('instance_'):
            # Official Pro images use a bare bash ENTRYPOINT. Harbor's usual
            # [sh,-c,sleep infinity] CMD becomes `bash sh ...` and exits 126.
            # Reset only this adapter's disposable Pro main container entrypoint.
            overlay['services']={'main':{'entrypoint':[],'command':['sh','-c','sleep infinity']}}
        self._strict_overlay.write_text(json.dumps(overlay))

    @property
    def _docker_compose_paths(self):
        paths=super()._docker_compose_paths
        return [*paths,self._strict_overlay] if hasattr(self,'_strict_overlay') else paths

    def _allocate_network(self):
        # Each trial gets its own bridge. No shared task network or daemon edits.
        with open('/tmp/benchmark-eval-net-counter.lock','a+') as lock:
            fcntl.flock(lock,fcntl.LOCK_EX)
            lock.seek(0)
            text=lock.read().strip()
            counter=int(text) if text else 0
            for _ in range(4096):
                counter=(counter+1)%4096
                octet=counter//16
                start=(counter%16)*16
                subnet=f'10.200.{octet}.{start}/28'
                result=subprocess.run(['docker','network','create','--label','owner=benchmark-eval','--subnet',subnet,self._strict_network_name],capture_output=True,text=True,timeout=20)
                if result.returncode==0:
                    lock.seek(0);lock.truncate();lock.write(str(counter));lock.flush()
                    self.logger.info('Allocated isolated network %s subnet=%s',self._strict_network_name,subnet)
                    return
                if 'overlap' not in result.stderr:
                    raise RuntimeError(result.stderr)
            raise RuntimeError('No free strict evaluation subnet')

    async def start(self,force_build):
        await asyncio.to_thread(self._allocate_network)
        await super().start(force_build=force_build)

    async def stop(self,delete):
        try:
            await super().stop(delete=delete)
        finally:
            process=await asyncio.create_subprocess_exec('docker','network','rm',self._strict_network_name,stdout=asyncio.subprocess.DEVNULL,stderr=asyncio.subprocess.DEVNULL)
            await process.wait()
            self._strict_overlay_dir.cleanup()