File size: 5,959 Bytes
b192407
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
"""
SetupController Module - Controller for environment setup operations.

This module handles initial environment configuration:
- Copies task data files to the workspace
- Downloads required files from URLs
- Executes setup commands in the container

Reference: https://github.com/yiyihum/da-code/tree/main/da_agent/controllers/setup.py
"""

import json
import os


import shutil
import logging
from typing import Any, Union, Optional
from typing import Dict, List
import uuid
import requests
import docker
import shutil
from da_agent import configs


FILE_PATH = os.path.dirname(os.path.abspath(__file__))
logger = logging.getLogger("da_agent.setup")


class SetupController:
    def __init__(self, container, cache_dir):
        self.cache_dir = cache_dir
        self.container = container
        self.mnt_dir = [mount['Source'] for mount in container.attrs['Mounts']][0]
        
    def setup_cp_dir(self, dir: str):
        """
        Args:
            dir (str): the directory to copy to the workspace
        """
        mnt_dir = self.mnt_dir

        if os.path.isfile(dir):
            print(f"Warning: {dir} is a file, not a directory. Copying the file to {mnt_dir}.")
            shutil.copy2(dir, mnt_dir)
        elif os.path.isdir(dir):
            print(f"Copying all files in {dir} to {mnt_dir}.")
            shutil.copytree(dir, mnt_dir, dirs_exist_ok=True)
        else:
            print(f"Warning: {dir} is neither a file nor a directory.")
        return

    def setup(self, config: List[Dict[str, Any]]):
        """
        Args:
            config (List[Dict[str, Any]]): list of dict like {str: Any}. each
              config dict has the structure like
                {
                    "type": str, corresponding to the `_{:}_setup` methods of
                      this class
                    "parameters": dick like {str, Any} providing the keyword
                      parameters
                }
        """  
        for cfg in config:
            config_type: str = cfg["type"]
            parameters: Dict[str, Any] = cfg["parameters"]

            setup_function: str = "_{:}_setup".format(config_type)

            if hasattr(self, setup_function):
                # Assumes all the setup the functions should follow this name
                # protocol
                # assert hasattr(self, setup_function), f'Setup controller cannot find init function {setup_function}'
                getattr(self, setup_function)(**parameters)
                logger.info("SETUP: %s(%s)", setup_function, str(parameters))
            else:
                # customized setup functions
                setup_function: str = "{:}_setup".format(config_type)
                config_function = getattr(configs, setup_function, None)
                assert config_function is not None, f'Setup controller cannot find function {setup_function}'
                config_function(self, **parameters)
                logger.info("SETUP: %s(%s)", setup_function, str(parameters))    
    
    
    def _download_setup(self, files: List[Dict[str, str]]):
        """
        Args:
            files (List[Dict[str, str]]): files to download. lisf of dict like
              {
                "url": str, the url to download
                "path": str, the path on the VM to store the downloaded file
              }
        """
        for f in files:
            url: str = f["url"]
            path: str = f["path"]

            cache_path: str = os.path.join(self.cache_dir, "{:}_{:}".format(
                uuid.uuid5(uuid.NAMESPACE_URL, url),
                os.path.basename(path)))
            if not url or not path:
                raise Exception(f"Setup Download - Invalid URL ({url}) or path ({path}).")

            if not os.path.exists(cache_path):
                max_retries = 3
                downloaded = False
                e = None
                for i in range(max_retries):
                    try:
                        response = requests.get(url, stream=True, timeout=10)
                        response.raise_for_status()

                        with open(cache_path, 'wb') as f:
                            for chunk in response.iter_content(chunk_size=8192):
                                if chunk:
                                    f.write(chunk)
                        logger.info("File downloaded successfully")
                        downloaded = True
                        break

                    except requests.RequestException as e:
                        logger.error(
                            f"Failed to download {url} caused by {e}. Retrying... ({max_retries - i - 1} attempts left)")
                if not downloaded:
                    raise requests.RequestException(f"Failed to download {url}. No retries left. Error: {e}")
            shutil.copy(cache_path, os.path.join(self.mnt_dir, os.path.basename(path)))

        
        
    def _execute_setup(self, command: str):
        """
        Args:
            command (List[str]): the command to execute on the VM
        """
        cmd = ["sh", "-c", command]
        exit_code, output = self.container.exec_run(cmd)
        return output.decode("utf-8").strip()

    def _copy_all_subfiles_setup(self, dirs: List[str]):
        mnt_dir = self.mnt_dir
        for dir in dirs:
            # change the father directory to  self.source_dir
            file_name = os.path.basename(dir)
            dir = os.path.join(self.source_dir, file_name)

            if os.path.isfile(dir):
                print(f"Warning: {dir} is a file, not a directory. Copying the file to {mnt_dir}.")
                shutil.copy2(dir, mnt_dir)
            elif os.path.isdir(dir):
                print(f"Copying all files in {dir} to {mnt_dir}.")
                shutil.copytree(dir, mnt_dir, dirs_exist_ok=True)
            else:
                print(f"Warning: {dir} is neither a file nor a directory.")
        return