file_handler.py 2.55 KB
Newer Older
1
2
3
4
5
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.

"""Utilities for file."""

6
import itertools
7
8
9
from pathlib import Path
from datetime import datetime

10
import yaml
11
from omegaconf import OmegaConf
12

13
from superbench.common.utils import logger, get_vm_size
14
15
16
17
18
19
20
21
22
23
24
25


def rotate_dir(target_dir):
    """Rotate directory if it is not empty.

    Args:
        target_dir (str): Target directory path.
    """
    try:
        if target_dir.is_dir() and any(target_dir.iterdir()):
            logger.warning('Directory %s is not empty.', str(target_dir))
            for i in itertools.count(start=1):
26
                backup_dir = target_dir.with_name(f'{target_dir.name}.bak{i}')
27
28
29
30
31
32
33
                if not backup_dir.is_dir():
                    target_dir.rename(backup_dir)
                    break
    except Exception:
        logger.exception('Failed to rotate directory %s.', str(target_dir))
        raise

34

35
36
def create_sb_output_dir(output_dir=None):
    """Create output directory.
37

38
39
40
41
    Create output directory on filesystem, generate a new name based on current time if not provided.

    Args:
        output_dir (str): Output directory. Defaults to None.
42
43

    Returns:
44
        str: Given or generated output directory.
45
    """
46
47
48
    if not output_dir:
        output_dir = str(Path('outputs', datetime.now().strftime('%Y-%m-%d_%H-%M-%S')))
    output_path = Path(output_dir).expanduser().resolve()
49
50
51
52
53
    try:
        output_path.mkdir(mode=0o755, parents=True, exist_ok=True)
    except Exception:
        logger.exception('Failed to create directory %s.', str(output_path))
        raise
54
    return output_dir
55
56


57
def get_sb_config(config_file):
58
59
    """Read SuperBench config yaml.

60
    Read config file, detect Azure SKU and use corresponding config if None is provided.
61
62
63
64
65

    Args:
        config_file (str): config file path.

    Returns:
66
        OmegaConf: Config object, None if file does not exist.
67
    """
68
69
70
71
72
73
74
75
76
77
78
79
    p = Path(str(config_file))
    if not config_file:
        config_path = (Path(__file__).parent / '../../config').resolve()
        p = config_path / 'default.yaml'
        vm_size = get_vm_size().lower()
        if vm_size:
            logger.info('Detected Azure SKU %s.', vm_size)
            for config in (config_path / 'azure').glob('**/*'):
                if config.name.startswith(vm_size):
                    p = config
                    break
        logger.info('No benchmark config provided, using config file %s.', str(p))
80
81
    if not p.is_file():
        return None
82
83
    with p.open() as fp:
        return OmegaConf.create(yaml.load(fp, Loader=yaml.SafeLoader))