~smoser/curtin/yakkety.lp1666986

« back to all changes in this revision

Viewing changes to curtin/util.py

  • Committer: Ryan Harper
  • Date: 2016-09-29 18:36:01 UTC
  • mfrom: (1.1.41)
  • mto: This revision was merged to the branch mainline in revision 59.
  • Revision ID: ryan.harper@canonical.com-20160929183601-utf54hgpsizdfzxp
* New upstream snapshot.
  - unittest,tox.ini: catch and fix issue with trusty-level mock of open 
  - block/mdadm: add option to ignore mdadm_assemble errors  (LP: #1618429)
  - curtin/doc: overhaul curtin documentation for readthedocs.org  (LP: #1351085)
  - curtin.util: re-add support for RunInChroot  (LP: #1617375)
  - curtin/net: overhaul of eni rendering to handle mixed ipv4/ipv6 configs 
  - curtin.block: refactor clear_holders logic into block.clear_holders and cli cmd 
  - curtin.apply_net should exit non-zero upon exception.  (LP: #1615780)
  - apt: fix bug in disable_suites if sources.list line is blank. 
  - vmtests: disable Wily in vmtests 
  - Fix the unittests for test_apt_source. 

Show diffs side-by-side

added added

removed removed

Lines of Context:
143
143
        a list of times to sleep in between retries.  After each failure
144
144
        subp will sleep for N seconds and then try again.  A value of [1, 3]
145
145
        means to run, sleep 1, run, sleep 3, run and then return exit code.
 
146
    :param target:
 
147
        run the command as 'chroot target <args>'
146
148
    """
147
149
    retries = []
148
150
    if "retries" in kwargs:
302
304
 
303
305
 
304
306
def write_file(filename, content, mode=0o644, omode="w"):
 
307
    """
 
308
    write 'content' to file at 'filename' using python open mode 'omode'.
 
309
    if mode is not set, then chmod file to mode. mode is 644 by default
 
310
    """
305
311
    ensure_dir(os.path.dirname(filename))
306
312
    with open(filename, omode) as fp:
307
313
        fp.write(content)
308
 
    os.chmod(filename, mode)
309
 
 
310
 
 
311
 
def load_file(path, mode="r"):
 
314
    if mode:
 
315
        os.chmod(filename, mode)
 
316
 
 
317
 
 
318
def load_file(path, mode="r", read_len=None, offset=0):
312
319
    with open(path, mode) as fp:
313
 
        return fp.read()
 
320
        if offset:
 
321
            fp.seek(offset)
 
322
        return fp.read(read_len) if read_len else fp.read()
 
323
 
 
324
 
 
325
def file_size(path):
 
326
    """get the size of a file"""
 
327
    with open(path, 'rb') as fp:
 
328
        fp.seek(0, 2)
 
329
        return fp.tell()
314
330
 
315
331
 
316
332
def del_file(path):
853
869
    return val
854
870
 
855
871
 
 
872
def bytes2human(size):
 
873
    """convert size in bytes to human readable"""
 
874
    if not (isinstance(size, (int, float)) and
 
875
            int(size) == size and
 
876
            int(size) >= 0):
 
877
        raise ValueError('size must be a integral value')
 
878
    mpliers = {'B': 1, 'K': 2 ** 10, 'M': 2 ** 20, 'G': 2 ** 30, 'T': 2 ** 40}
 
879
    unit_order = sorted(mpliers, key=lambda x: -1 * mpliers[x])
 
880
    unit = next((u for u in unit_order if (size / mpliers[u]) >= 1), 'B')
 
881
    return str(int(size / mpliers[unit])) + unit
 
882
 
 
883
 
856
884
def import_module(import_str):
857
885
    """Import a module."""
858
886
    __import__(import_str)
868
896
 
869
897
 
870
898
def is_file_not_found_exc(exc):
871
 
    return (isinstance(exc, IOError) and exc.errno == errno.ENOENT)
 
899
    return (isinstance(exc, (IOError, OSError)) and
 
900
            hasattr(exc, 'errno') and
 
901
            exc.errno in (errno.ENOENT, errno.EIO, errno.ENXIO))
872
902
 
873
903
 
874
904
def _lsb_release(target=None):
916
946
 
917
947
 
918
948
def json_dumps(data):
919
 
    return json.dumps(data, indent=1, sort_keys=True,
920
 
                      separators=(',', ': ')).encode('utf-8')
 
949
    return json.dumps(data, indent=1, sort_keys=True, separators=(',', ': '))
921
950
 
922
951
 
923
952
def get_platform_arch():
1055
1084
    return os.path.join(target, path)
1056
1085
 
1057
1086
 
 
1087
class RunInChroot(ChrootableTarget):
 
1088
    """Backwards compatibility for RunInChroot (LP: #1617375).
 
1089
    It needs to work like:
 
1090
        with RunInChroot("/target") as in_chroot:
 
1091
            in_chroot(["your", "chrooted", "command"])"""
 
1092
    __call__ = ChrootableTarget.subp
 
1093
 
 
1094
 
1058
1095
# vi: ts=4 expandtab syntax=python