bfile.py 26.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# Copyright (c) 2020 VisualDL Authors. All Rights Reserve.
#
# 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
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# 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 16
import base64
import hashlib
17 18
import os
import tempfile
走神的阿圆's avatar
走神的阿圆 已提交
19
import time
走神的阿圆's avatar
走神的阿圆 已提交
20 21 22 23 24 25 26 27 28 29

try:
    import hdfs
    from hdfs.util import HdfsError
    HDFS_ENABLED = True
except ImportError:
    HDFS_ENABLED = False
try:
    from baidubce.services.bos.bos_client import BosClient
    from baidubce import exception
走神的阿圆's avatar
走神的阿圆 已提交
30 31
    from baidubce.bce_client_configuration import BceClientConfiguration
    from baidubce.auth.bce_credentials import BceCredentials
走神的阿圆's avatar
走神的阿圆 已提交
32 33 34
    BOS_ENABLED = True
except ImportError:
    BOS_ENABLED = False
35 36 37 38 39 40 41

# Note: Some codes here refer to TensorBoardX.
# A good default block size depends on the system in question.
# A somewhat conservative default chosen here.
_DEFAULT_BLOCK_SIZE = 16 * 1024 * 1024


走神的阿圆's avatar
走神的阿圆 已提交
42 43 44 45 46 47
def content_md5(buffer):
    md5 = hashlib.md5()
    md5.update(buffer)
    return base64.standard_b64encode(md5.digest())


48 49 50 51 52 53 54 55
class FileFactory(object):
    def __init__(self):
        self._register_factories = {}

    def register_filesystem(self, path, filesystem):
        self._register_factories.update({path: filesystem})

    def get_filesystem(self, path):
走神的阿圆's avatar
走神的阿圆 已提交
56 57
        if path.startswith(
                'hdfs://') and "hdfs" not in self._register_factories:
走神的阿圆's avatar
走神的阿圆 已提交
58 59
            if not HDFS_ENABLED:
                raise RuntimeError('Please install module named "hdfs".')
走神的阿圆's avatar
走神的阿圆 已提交
60
            try:
61 62
                default_file_factory.register_filesystem(
                    "hdfs", HDFileSystem())
走神的阿圆's avatar
走神的阿圆 已提交
63 64 65
            except hdfs.util.HdfsError:
                raise RuntimeError(
                    "Please initialize `~/.hdfscli.cfg` for HDFS.")
走神的阿圆's avatar
走神的阿圆 已提交
66 67 68 69 70 71 72
        elif path.startswith(
                'bos://') and "bos" not in self._register_factories:
            if not BOS_ENABLED:
                raise RuntimeError(
                    'Please install module named "bce-python-sdk".')
            default_file_factory.register_filesystem("bos", BosFileSystem())

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
        prefix = ""
        index = path.find("://")
        if index >= 0:
            prefix = path[:index]
        fs = self._register_factories.get(prefix, None)
        if fs is None:
            raise ValueError("No recognized filesystem for prefix %s" % prefix)
        return fs


default_file_factory = FileFactory()


class LocalFileSystem(object):
    def __init__(self):
        pass

    @staticmethod
    def exists(path):
        return os.path.exists(path)

    @staticmethod
    def makedirs(path):
        os.makedirs(path)

    @staticmethod
    def join(path, *paths):
        return os.path.join(path, *paths)

走神的阿圆's avatar
走神的阿圆 已提交
102 103 104 105 106 107 108 109 110
    def isfile(self, filename):
        return os.path.isfile(filename)

    def read_file(self, filename, binary_mode=True):
        mode = "rb" if binary_mode else "r"
        with open(filename, mode) as reader:
            data = reader.read()
        return data

111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
    def read(self, filename, binary_mode=False, size=None, continue_from=None):
        mode = "rb" if binary_mode else "r"
        encoding = None if binary_mode else "utf-8"
        offset = None
        if continue_from is not None:
            offset = continue_from.get("last_offset", None)
        with open(filename, mode=mode, encoding=encoding) as fp:
            if offset is not None:
                fp.seek(offset)
            data = fp.read(size)
            continue_from_token = {"last_offset": fp.tell()}
            return data, continue_from_token

    def _write(self, filename, file_content, mode):
        encoding = None if "b" in mode else "utf-8"
        with open(filename, mode, encoding=encoding) as fp:
            fp.write(file_content)

    def append(self, filename, file_content, binary_mode=False):
130 131 132 133
        try:
            self._write(filename, file_content, "ab" if binary_mode else "a")
        except FileNotFoundError:
            self.makedirs(os.path.dirname(filename))
134 135

    def write(self, filename, file_content, binary_mode=False):
136 137 138 139
        try:
            self._write(filename, file_content, "ab" if binary_mode else "a")
        except FileNotFoundError:
            self.makedirs(os.path.dirname(filename))
140
        # self._write(filename, file_content, "wb" if binary_mode else "w")
141 142

    def walk(self, dir):
143 144
        if 'posix' == os.name:
            return os.walk(dir, followlinks=True)
145 146 147 148 149 150
        return os.walk(dir)


default_file_factory.register_filesystem("", LocalFileSystem())


151 152 153 154 155 156 157 158 159 160
class HDFileSystem(object):
    def __init__(self):
        self.cli = hdfs.config.Config().get_client('dev')

    def exists(self, path):
        if self.cli.status(hdfs_path=path[7:], strict=False) is None:
            return False
        else:
            return True

走神的阿圆's avatar
走神的阿圆 已提交
161 162 163 164 165 166 167 168
    def isfile(self, filename):
        return exists(filename)

    def read_file(self, filename, binary_mode=True):
        with self.cli.read(hdfs_path=filename[7:]) as reader:
            data = reader.read()
        return data

169 170 171 172 173
    def makedirs(self, path):
        self.cli.makedirs(hdfs_path=path[7:])

    @staticmethod
    def join(path, *paths):
走神的阿圆's avatar
走神的阿圆 已提交
174 175 176
        result = os.path.join(path, *paths)
        result.replace('\\', '/')
        return result
177 178 179 180 181 182 183

    def read(self, filename, binary_mode=False, size=0, continue_from=None):
        offset = 0
        if continue_from is not None:
            offset = continue_from.get("last_offset", 0)

        encoding = None if binary_mode else "utf-8"
走神的阿圆's avatar
走神的阿圆 已提交
184
        try:
185 186 187
            with self.cli.read(
                    hdfs_path=filename[7:], offset=offset,
                    encoding=encoding) as reader:
走神的阿圆's avatar
走神的阿圆 已提交
188 189 190 191 192
                data = reader.read()
                continue_from_token = {"last_offset": offset + len(data)}
                return data, continue_from_token
        except HdfsError:
            raise EOFError('No more events to read on HDFS.')
193 194 195 196 197

    def append(self, filename, file_content, binary_mode=False):
        self.cli.write(hdfs_path=filename[7:], data=file_content, append=True)

    def write(self, filename, file_content, binary_mode=False):
198 199
        self.cli.write(hdfs_path=filename[7:], data=file_content, append=True)
        # self.cli.write(hdfs_path=filename[7:], data=file_content)
200 201 202

    def walk(self, dir):
        walks = self.cli.walk(hdfs_path=dir[7:])
走神的阿圆's avatar
走神的阿圆 已提交
203
        return (['hdfs://' + root, dirs, files] for root, dirs, files in walks)
204 205


走神的阿圆's avatar
走神的阿圆 已提交
206 207 208 209 210 211 212 213 214 215 216 217
def get_object_info(path):
    path = path[6:]
    index = path.index('/')
    bucket_name = path[0:index]
    object_key = path[index + 1:]
    return bucket_name, object_key


class BosConfigClient(object):
    def __init__(self, bos_ak, bos_sk, bos_sts, bos_host="bj.bcebos.com"):
        self.config = BceClientConfiguration(
            credentials=BceCredentials(bos_ak, bos_sk),
218 219
            endpoint=bos_host,
            security_token=bos_sts)
走神的阿圆's avatar
走神的阿圆 已提交
220
        self.bos_client = BosClient(self.config)
走神的阿圆's avatar
走神的阿圆 已提交
221

走神的阿圆's avatar
走神的阿圆 已提交
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
    def exists(self, path):
        bucket_name, object_key = get_object_info(path)
        try:
            self.bos_client.get_object_meta_data(bucket_name, object_key)
            return True
        except exception.BceError:
            return False

    def makedirs(self, path):
        if not path.endswith('/'):
            path += '/'
        if self.exists(path):
            return
        bucket_name, object_key = get_object_info(path)
        if not object_key.endswith('/'):
            object_key += '/'
        init_data = b''
239 240 241 242 243 244
        self.bos_client.append_object(
            bucket_name=bucket_name,
            key=object_key,
            data=init_data,
            content_md5=content_md5(init_data),
            content_length=len(init_data))
走神的阿圆's avatar
走神的阿圆 已提交
245 246 247 248 249 250 251 252

    @staticmethod
    def join(path, *paths):
        result = os.path.join(path, *paths)
        result.replace('\\', '/')
        return result

    def upload_object_from_file(self, path, filename):
253 254 255 256 257 258 259
        """!
        Upload a local file to baidu bos filesystem. The path can de divided as bucket name and prefix directory.
        The file would be uploaded in bucket at path `join(prefix directory in path, filename)`
        @param self object
        @param path(str)  bos directory path to store file, which consists of bucket_name + prefix directory.
        @param filename(str) local file path to upload
        """
走神的阿圆's avatar
走神的阿圆 已提交
260 261 262 263 264 265 266 267
        if not self.exists(path):
            self.makedirs(path)
        bucket_name, object_key = get_object_info(path)

        object_key = self.join(object_key, filename)
        # if not object_key.endswith('/'):
        #     object_key += '/'
        print('Uploading file `%s`' % filename)
268 269
        self.bos_client.put_object_from_file(
            bucket=bucket_name, key=object_key, file_name=filename)
走神的阿圆's avatar
走神的阿圆 已提交
270 271 272 273


class BosFileSystem(object):
    def __init__(self, write_flag=True):
274 275 276 277 278 279 280
        self.max_contents_count = 1
        self.max_contents_time = 1
        self.file_length_map = {}

        self._file_contents_to_add = b''
        self._file_contents_count = 0
        self._start_append_time = time.time()
走神的阿圆's avatar
走神的阿圆 已提交
281 282 283
        if write_flag:
            self.get_bos_config()
            self.bos_client = BosClient(self.config)
走神的阿圆's avatar
走神的阿圆 已提交
284 285

    def get_bos_config(self):
286 287 288
        '''
        Get Bos configuration from environment variables.
        '''
走神的阿圆's avatar
走神的阿圆 已提交
289 290 291 292 293 294 295 296 297 298 299
        bos_host = os.getenv("BOS_HOST")
        if not bos_host:
            raise KeyError('${BOS_HOST} is not found.')
        access_key_id = os.getenv("BOS_AK")
        if not access_key_id:
            raise KeyError('${BOS_AK} is not found.')
        secret_access_key = os.getenv("BOS_SK")
        if not secret_access_key:
            raise KeyError('${BOS_SK} is not found.')
        self.max_contents_count = int(os.getenv('BOS_CACHE_COUNT', 1))
        self.max_contents_time = int(os.getenv('BOS_CACHE_TIME', 1))
走神的阿圆's avatar
走神的阿圆 已提交
300
        bos_sts = os.getenv("BOS_STS")
走神的阿圆's avatar
走神的阿圆 已提交
301 302
        self.config = BceClientConfiguration(
            credentials=BceCredentials(access_key_id, secret_access_key),
303 304
            endpoint=bos_host,
            security_token=bos_sts)
走神的阿圆's avatar
走神的阿圆 已提交
305

306 307
    def set_bos_config(self, bos_ak, bos_sk, bos_sts,
                       bos_host="bj.bcebos.com"):
308 309 310
        '''
        Set Bos configuration and get bos client according to parameters.
        '''
走神的阿圆's avatar
走神的阿圆 已提交
311 312
        self.config = BceClientConfiguration(
            credentials=BceCredentials(bos_ak, bos_sk),
313 314
            endpoint=bos_host,
            security_token=bos_sts)
走神的阿圆's avatar
走神的阿圆 已提交
315 316
        self.bos_client = BosClient(self.config)

317
    def renew_bos_client_from_server(self):
318 319 320
        '''
        Get bos client by visualdl provided ak, sk, and sts token
        '''
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
        import requests
        import json
        from visualdl.utils.dir import CONFIG_PATH
        with open(CONFIG_PATH, 'r') as fp:
            server_url = json.load(fp)['server_url']
        url = server_url + '/sts/'
        res = requests.post(url=url).json()
        err_code = res.get('code')
        msg = res.get('msg')
        if '000000' == err_code:
            sts_ak = msg.get('sts_ak')
            sts_sk = msg.get('sts_sk')
            sts_token = msg.get('token')
            self.set_bos_config(sts_ak, sts_sk, sts_token)
        else:
            print('Renew bos client error. Error msg: {}'.format(msg))
            return

走神的阿圆's avatar
走神的阿圆 已提交
339 340 341 342
    def isfile(self, filename):
        return exists(filename)

    def read_file(self, filename, binary=True):
走神的阿圆's avatar
走神的阿圆 已提交
343
        bucket_name, object_key = get_object_info(filename)
344 345
        result = self.bos_client.get_object_as_string(bucket_name, object_key)
        return result
走神的阿圆's avatar
走神的阿圆 已提交
346

走神的阿圆's avatar
走神的阿圆 已提交
347
    def exists(self, path):
走神的阿圆's avatar
走神的阿圆 已提交
348
        bucket_name, object_key = get_object_info(path)
走神的阿圆's avatar
走神的阿圆 已提交
349 350 351 352 353 354 355 356 357 358 359 360 361 362
        try:
            self.bos_client.get_object_meta_data(bucket_name, object_key)
            return True
        except exception.BceError:
            return False

    def get_meta(self, bucket_name, object_key):
        return self.bos_client.get_object_meta_data(bucket_name, object_key)

    def makedirs(self, path):
        if not path.endswith('/'):
            path += '/'
        if self.exists(path):
            return
走神的阿圆's avatar
走神的阿圆 已提交
363
        bucket_name, object_key = get_object_info(path)
走神的阿圆's avatar
走神的阿圆 已提交
364 365 366
        if not object_key.endswith('/'):
            object_key += '/'
        init_data = b''
367 368 369 370 371 372
        self.bos_client.append_object(
            bucket_name=bucket_name,
            key=object_key,
            data=init_data,
            content_md5=content_md5(init_data),
            content_length=len(init_data))
走神的阿圆's avatar
走神的阿圆 已提交
373 374 375 376 377 378 379 380

    @staticmethod
    def join(path, *paths):
        result = os.path.join(path, *paths)
        result.replace('\\', '/')
        return result

    def read(self, filename, binary_mode=False, size=0, continue_from=None):
走神的阿圆's avatar
走神的阿圆 已提交
381
        bucket_name, object_key = get_object_info(filename)
走神的阿圆's avatar
走神的阿圆 已提交
382 383 384
        offset = 0
        if continue_from is not None:
            offset = continue_from.get("last_offset", 0)
走神的阿圆's avatar
走神的阿圆 已提交
385 386 387
        length = int(
            self.get_meta(bucket_name, object_key).metadata.content_length)
        if offset < length:
388 389 390 391
            data = self.bos_client.get_object_as_string(
                bucket_name=bucket_name,
                key=object_key,
                range=[offset, length - 1])
走神的阿圆's avatar
走神的阿圆 已提交
392 393 394 395
        else:
            data = b''

        continue_from_token = {"last_offset": length}
走神的阿圆's avatar
走神的阿圆 已提交
396 397
        return data, continue_from_token

走神的阿圆's avatar
走神的阿圆 已提交
398 399 400 401 402 403 404 405 406 407 408 409 410 411
    def ready_to_append(self):
        if self._file_contents_count >= self.max_contents_count or \
                time.time() - self._start_append_time > self.max_contents_time:
            return True
        else:
            return False

    def append(self, filename, file_content, binary_mode=False, force=False):
        self._file_contents_to_add += file_content
        self._file_contents_count += 1

        if not force and not self.ready_to_append():
            return
        file_content = self._file_contents_to_add
走神的阿圆's avatar
走神的阿圆 已提交
412
        bucket_name, object_key = get_object_info(filename)
走神的阿圆's avatar
走神的阿圆 已提交
413 414
        if not self.exists(filename):
            init_data = b''
415 416 417
            # Two cases will come here
            # 1. the file not exist, then we need to create the file
            # 2. sts token invalid in self.exists, we should renew the token, and continue to write
418 419 420 421 422 423 424
            try:
                self.bos_client.append_object(
                    bucket_name=bucket_name,
                    key=object_key,
                    data=init_data,
                    content_md5=content_md5(init_data),
                    content_length=len(init_data))
425 426
            except (exception.BceServerError,
                    exception.BceHttpClientError) as e:
427 428 429 430
                if bucket_name == 'visualdl-server':  # only sts token from visualdl-server, we can renew automatically
                    self.renew_bos_client_from_server()
                    # we should add a judgement for case 2
                    try:
431 432
                        self.bos_client.get_object_meta_data(
                            bucket_name, object_key)
433 434 435 436 437 438 439 440 441 442 443
                    except exception.BceError:
                        # the file not exists, then create the file
                        self.bos_client.append_object(
                            bucket_name=bucket_name,
                            key=object_key,
                            data=init_data,
                            content_md5=content_md5(init_data),
                            content_length=len(init_data))
                        return
                else:
                    raise e  # user defined bos token, we have no idea to renew the token, so throw the exception
走神的阿圆's avatar
走神的阿圆 已提交
444 445
        content_length = len(file_content)

446 447 448
        try:
            offset = self.get_meta(bucket_name,
                                   object_key).metadata.content_length
449 450 451 452 453 454 455
            self.bos_client.append_object(
                bucket_name=bucket_name,
                key=object_key,
                data=file_content,
                content_md5=content_md5(file_content),
                content_length=content_length,
                offset=offset)
456 457 458 459 460 461 462 463 464 465 466 467 468 469
        except (exception.BceServerError, exception.BceHttpClientError) as e:
            if bucket_name == 'visualdl-server':  # only sts token from visualdl-server, we can renew automatically
                self.renew_bos_client_from_server()
                offset = self.get_meta(bucket_name,
                                       object_key).metadata.content_length
                self.bos_client.append_object(
                    bucket_name=bucket_name,
                    key=object_key,
                    data=file_content,
                    content_md5=content_md5(file_content),
                    content_length=content_length,
                    offset=offset)
            else:
                raise e  # user defined bos token, we have no idea to renew the token, so throw the exception
走神的阿圆's avatar
走神的阿圆 已提交
470 471 472
        self._file_contents_to_add = b''
        self._file_contents_count = 0
        self._start_append_time = time.time()
走神的阿圆's avatar
走神的阿圆 已提交
473 474

    def write(self, filename, file_content, binary_mode=False):
475 476 477 478 479 480 481 482 483
        self.append(filename, file_content, binary_mode=False)

        # bucket_name, object_key = BosFileSystem._get_object_info(filename)
        #
        # self.bos_client.append_object(bucket_name=bucket_name,
        #                               key=object_key,
        #                               data=file_content,
        #                               content_md5=content_md5(file_content),
        #                               content_length=len(file_content))
走神的阿圆's avatar
走神的阿圆 已提交
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509

    def walk(self, dir):
        class WalkGenerator():
            def __init__(self, bucket_name, contents):
                self.contents = None
                self.length = 0
                self.bucket = bucket_name
                self.handle_contents(contents)
                self.count = 0

            def handle_contents(self, contents):
                contents_map = {}
                for item in contents:
                    try:
                        rindex = item.rindex('/')
                        key = item[0:rindex]
                        value = item[rindex + 1:]
                    except ValueError:
                        key = '.'
                        value = item
                    if key in contents_map.keys():
                        contents_map[key].append(value)
                    else:
                        contents_map[key] = [value]
                temp_walk = []
                for key, value in contents_map.items():
510 511 512 513
                    temp_walk.append([
                        BosFileSystem.join('bos://' + self.bucket, key), [],
                        value
                    ])
走神的阿圆's avatar
走神的阿圆 已提交
514 515 516 517 518 519 520 521 522 523 524 525 526
                self.length = len(temp_walk)
                self.contents = temp_walk

            def __iter__(self):
                return self

            def __next__(self):
                if self.count < self.length:
                    self.count += 1
                    return self.contents[self.count - 1]
                else:
                    raise StopIteration

走神的阿圆's avatar
走神的阿圆 已提交
527
        bucket_name, object_key = get_object_info(dir)
走神的阿圆's avatar
走神的阿圆 已提交
528 529 530 531 532 533

        if object_key in ['.', './']:
            prefix = None
        else:
            prefix = object_key if object_key.endswith(
                '/') else object_key + '/'
534
        response = self.bos_client.list_objects(bucket_name, prefix=prefix)
走神的阿圆's avatar
走神的阿圆 已提交
535 536 537 538
        contents = [content.key for content in response.contents]
        return WalkGenerator(bucket_name, contents)


539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560
class BFile(object):
    def __init__(self, filename, mode):
        if mode not in ('r', 'rb', 'br', 'w', 'wb', 'bw'):
            raise NotImplementedError("mode {} not supported by "
                                      "BFile.".format(mode))
        self._filename = filename
        self.fs = default_file_factory.get_filesystem(filename)
        self.fs_supports_append = hasattr(self.fs, 'append')
        self.buff = None
        self.buff_chunk_size = _DEFAULT_BLOCK_SIZE
        self.buff_offset = 0
        self.continuation_token = None
        self.write_temp = None
        self.write_started = False
        self.binary_mode = 'b' in mode
        self.write_mode = 'w' in mode
        self.closed = False

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
561 562 563 564
        self.close()
        self.buff = None
        self.buff_offset = 0
        self.continuation_token = None
565 566 567 568

    def __iter__(self):
        return self

走神的阿圆's avatar
走神的阿圆 已提交
569 570 571
    def isfile(self, filename):
        return self.fs.isfile(filename)

572 573 574 575 576 577 578 579 580 581 582 583 584 585 586
    def _read_buffer_to_offset(self, new_buff_offset):
        """Read buffer from index self.buffer_offset to index new_buff_offset.

        self.buff_offset marks the last position of the last read,
        new_buff_offset indicates the last position of this read.
        self.buff_offset will be updated by new_buff_offset after this read.

        Returns:
            self.buff[i1: i2]: Content of self.buff.
        """
        old_buff_offset = self.buff_offset
        read_size = min(len(self.buff), new_buff_offset) - old_buff_offset
        self.buff_offset += read_size
        return self.buff[old_buff_offset:old_buff_offset + read_size]

走神的阿圆's avatar
走神的阿圆 已提交
587 588 589
    def read_file(self, filename, binnary=True):
        return self.fs.read_file(filename, binnary)

590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705
    def read(self, n=None):
        """Read `n` or all contents of self.buff or file.

        Returns:
            result: Data from self.buff or file.
        """
        result = None
        # If self.buff is not none and length of self.buff more than
        # self.buff_offset, means there are some content in self.buff have
        # not been read.
        if self.buff and len(self.buff) > self.buff_offset:
            if n is not None:
                chunk = self._read_buffer_to_offset(self.buff_offset + n)
                # If length of data in self.buff is more than `n`, then read `n`
                # data from local buffer.
                if len(chunk) == n:
                    return chunk
                result = chunk
                # The length of all data in self.buff may less than `n`,
                # so we should read other `n-length(self.buff)` data.
                n -= len(chunk)
            # If n is none, read all data in self.buff.
            else:
                # add all local buffer and update offsets
                result = self._read_buffer_to_offset(len(self.buff))

        # self.buff is empty if program is here.
        # Read from filesystem.
        # If n is not none, read max(n, self.buff_chunk_size) data from file,
        # otherwise read all data from file.
        # TODO(shenhuhan) N is limited to max_buff, but all-data is unlimited?
        read_size = max(self.buff_chunk_size, n) if n is not None else None
        self.buff, self.continuation_token = self.fs.read(
            self._filename, self.binary_mode, read_size,
            self.continuation_token)
        self.buff_offset = 0

        if n is not None:
            chunk = self._read_buffer_to_offset(n)
        else:
            # add all local buffer and update offsets
            chunk = self._read_buffer_to_offset(len(self.buff))
        result = result + chunk if result else chunk

        return result

    def write(self, file_content):
        """Write contents to file.

        Args:
            file_content: Contents waiting to be written to file.
        """
        if not self.write_mode:
            raise RuntimeError("File not opened in write mode")
        if self.closed:
            raise RuntimeError("File already closed")

        if self.fs_supports_append:
            if not self.write_started:
                self.fs.write(self._filename, file_content, self.binary_mode)
                self.write_started = True
            else:
                self.fs.append(self._filename, file_content, self.binary_mode)
        else:
            # add to temp file, but wait for flush to write to final filesystem
            if self.write_temp is None:
                mode = "w+b" if self.binary_mode else "w+"
                self.write_temp = tempfile.TemporaryFile(mode)
            self.write_temp.write(file_content)

    def __next__(self):
        line = None
        while True:
            if not self.buff:
                # read one unit into the buffer
                line = self.read(1)
                if line and (line[-1] == '\n' or not self.buff):
                    return line
                if not self.buff:
                    raise StopIteration()
            else:
                index = self.buff.find('\n', self.buff_offset)
                if index != -1:
                    # include line until now plus newline
                    chunk = self.read(index + 1 - self.buff_offset)
                    line = line + chunk if line else chunk
                    return line

                # read one unit past end of buffer
                chunk = self.read(len(self.buff) + 1 - self.buff_offset)
                line = line + chunk if line else chunk
                if line and (line[-1] == '\n' or not self.buff):
                    return line
                if not self.buff:
                    raise StopIteration()

    def next(self):
        return self.__next__()

    def flush(self):
        """Flush data to disk.
        """
        if self.closed:
            raise RuntimeError("File already closed")
        if not self.fs_supports_append:
            if self.write_temp is not None:
                # read temp file from the beginning
                self.write_temp.flush()
                self.write_temp.seek(0)
                chunk = self.write_temp.read()
                if chunk is not None:
                    # write full contents and keep in temp file
                    self.fs.write(self._filename, chunk, self.binary_mode)
                    self.write_temp.seek(len(chunk))

    def close(self):
走神的阿圆's avatar
走神的阿圆 已提交
706
        if isinstance(self.fs, BosFileSystem):
707
            try:
708 709
                self.fs.append(
                    self._filename, b'', self.binary_mode, force=True)
P
Peter Pan 已提交
710
            except Exception:
711
                pass
712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733
        self.flush()
        if self.write_temp is not None:
            self.write_temp.close()
            self.write_temp = None
            self.write_started = False
        self.closed = True


def exists(path):
    return default_file_factory.get_filesystem(path).exists(path)


def makedirs(path):
    return default_file_factory.get_filesystem(path).makedirs(path)


def join(path, *paths):
    return default_file_factory.get_filesystem(path).join(path, *paths)


def walk(dir):
    return default_file_factory.get_filesystem(dir).walk(dir)