container.py 5.4 KB
Newer Older
K
kuizhiqing 已提交
1
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
2
#
K
kuizhiqing 已提交
3 4 5
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
6
#
K
kuizhiqing 已提交
7
#     http://www.apache.org/licenses/LICENSE-2.0
8
#
K
kuizhiqing 已提交
9 10 11 12 13 14
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

15
from paddle.distributed.launch.utils.process_context import ProcessContext
K
kuizhiqing 已提交
16 17 18

from .status import Status

19 20
import os
import sys
K
kuizhiqing 已提交
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39


class Container(object):
    '''
    TODO(kuizhiqing) A container can be run by process/thread or just a callable function
    '''

    def __init__(self, entrypoint=[], rank=-1, env={}):
        self._entrypoint = entrypoint
        self._rank = rank
        self._out = None
        self._err = None
        self._env = env
        self._proc = None

        self._retry: int = 3
        self._grace_period = 10

        self._log_handler = None
40
        self._shell = False
K
kuizhiqing 已提交
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

    @property
    def entrypoint(self):
        return self._entrypoint

    @entrypoint.setter
    def entrypoint(self, entry):
        self._entrypoint = entry

    @property
    def rank(self):
        return self._rank

    @rank.setter
    def rank(self, r):
        self._rank = r

    @property
    def outfile(self):
        return self._out

    @outfile.setter
    def outfile(self, out):
        self._out = out

    @property
    def errfile(self):
        return self._err

    @errfile.setter
    def errfile(self, err):
        self._err = err

74 75 76 77 78 79 80 81
    @property
    def shell(self):
        return self._shell

    @shell.setter
    def shell(self, shell):
        self._shell = shell

K
kuizhiqing 已提交
82 83 84 85 86 87 88
    def update_env(self, env={}, **kwargs):
        env = {k: v for k, v in env.items() if isinstance(v, str)}
        self._env.update(env)

        kwargs = {k: v for k, v in kwargs.items() if isinstance(v, str)}
        self._env.update(kwargs)

89 90 91 92 93
    def _valide_env(self):
        for k, v in self._env.items():
            assert isinstance(k, str) and isinstance(
                v, str), 'env {}:{} must be str'.format(k, v)

K
kuizhiqing 已提交
94 95 96 97 98 99 100 101
    def _get_fd(self, pth):
        if not pth:
            return None

        try:
            d = os.path.dirname(pth)
            if not os.path.isdir(d):
                os.makedirs(d, exist_ok=True)
102
            return open(pth, 'a')
K
kuizhiqing 已提交
103 104 105
        except:
            return None

106
    def start(self):
K
kuizhiqing 已提交
107 108 109
        if self._proc and self._proc.alive():
            return True

110 111
        self._valide_env()

K
kuizhiqing 已提交
112 113 114 115 116 117
        self._stdout = self._get_fd(self._out) or sys.stdout
        if self._out == self._err:
            self._stderr = self._stdout
        elif self._err:
            self._stderr = self._get_fd(self._err) or sys.stderr

118 119 120 121 122
        if not self._log_handler:
            self._log_handler = open(self._out)
            self._log_handler.seek(0, 2)
            self._log_start_offset = self._log_handler.tell()

123 124 125
        self._proc = ProcessContext(self._entrypoint,
                                    env=self._env,
                                    out=self._stdout,
126 127
                                    err=self._stderr,
                                    shell=self._shell)
128

K
kuizhiqing 已提交
129 130 131 132 133 134 135 136 137 138 139
        self._proc.start()

    def terminate(self, force=False):
        if self._log_handler:
            self._log_handler.close()
            self._log_handler = None

        if self._proc and self._proc.alive():
            return self._proc.terminate(force)

    def wait(self, timeout=None):
K
kuizhiqing 已提交
140 141 142 143 144
        try:
            self._proc.wait(timeout)
            return True
        except Exception:
            return False
K
kuizhiqing 已提交
145

146
    @property
K
kuizhiqing 已提交
147 148 149
    def exit_code(self):
        return self._proc.exit_code() if self._proc else -1

150
    @property
K
kuizhiqing 已提交
151 152 153 154 155 156 157 158 159 160 161 162 163
    def status(self):
        if not self._proc:
            return Status.UNINIT
        if self._proc.alive():
            return Status.RUNNING
        elif self._proc.exit_code() == 0:
            return Status.COMPLETED
        else:
            return Status.FAILED

    def __str__(self):
        return 'Container rank {} status {} cmd {} code {} log {} \nenv {}'.format(
            self._rank,
164
            self.status,
K
kuizhiqing 已提交
165
            self._entrypoint,
166
            self.exit_code,
K
kuizhiqing 已提交
167
            self.errfile,
168 169
            self._env,
        )
K
kuizhiqing 已提交
170

171
    def logs(self, fn=None, offset=0, whence=1, limit=1000):
K
kuizhiqing 已提交
172 173 174 175 176 177 178
        if not self._log_handler:
            self._log_handler = open(self._out)

        if fn is None:
            fn = sys.stdout

        try:
179
            if offset != 0 or whence != 1:
180 181
                if whence == 0 and offset < self._log_start_offset:
                    offset = self._log_start_offset
182 183 184 185 186
                self._log_handler.seek(offset, whence)

            for _ in range(limit):
                line = self._log_handler.readline()
                if not line:
187
                    return False
188
                fn.write(line)
189
            return True
190
        except:
K
kuizhiqing 已提交
191
            return
K
kuizhiqing 已提交
192 193 194 195 196

    def tail(self, length=3000):
        if not self._log_handler:
            self._log_handler = open(self._out)

197 198 199 200 201
        try:
            self._log_handler.seek(0, 2)
            ed = self._log_handler.tell()
        except:
            pass
K
kuizhiqing 已提交
202 203 204 205 206

        if ed > length:
            self.logs(offset=ed - length, whence=0)
        else:
            self.logs(offset=0, whence=0)