# # Copyright (C) 2022 Soleta Networks # # This program is free software: you can redistribute it and/or modify it under # the terms of the GNU Affero General Public License as published by the # Free Software Foundation; either version 3 of the License, or # (at your option) any later version. import logging import os from src.utils.fs import mount_mkdir, umount from src.utils.net import * from src.utils.probe import get_cache_dev_path OG_IMAGE_PATH = '/opt/opengnsys/images/' OG_CACHE_PATH = '/opt/opengnsys/cache' OG_CACHE_IMAGE_PATH = OG_CACHE_PATH + OG_IMAGE_PATH OGCLIENT_LOG_CACHE='/opt/opengnsys/log/{ip}.cache.txt' def mount_cache(): """ Probes for cache and mounts if succesful. Returns the mountpoint or an empty string. """ cache_dev = get_cache_dev_path() if cache_dev: # cache_target = cache_dev.replace('dev', 'mnt') mount_mkdir(cache_dev, OG_CACHE_PATH) return OG_CACHE_PATH return '' def umount_cache(): """ If OG_CACHE_PATH is a mountpoint, umounts. If not, does nothing. """ if os.path.ismount(OG_CACHE_PATH): umount(OG_CACHE_PATH) def write_cache_txt(content): """ Dumps content to /opt/opengnsys/log/{ip}.cache.txt """ client_ip = getifaddr(get_ethernet_interface()) with open(OGCLIENT_LOG_CACHE.format(ip=client_ip), 'w') as f: logging.debug('Writing cache contents to %s.cache.txt', client_ip) f.write(content) def generate_cache_txt(): """ If no OpenGnsys cache partition is detected this function will do nothing. Generates a *.cache.txt file from a given path. A .cache.txt file is just a comma separated list of the files contained in the images folder in the OpenGnsys cache. """ cache_path = mount_cache() if cache_path: try: files = os.listdir(f'{cache_path}{OG_IMAGE_PATH}') except FileNotFoundError: return content = ','.join(files) write_cache_txt(content) def init_cache(): """ If a cache partition is present, creates the following directories /opt/opengnsys/images. This is the default folder in which images are stored when using tiptorrent-cache. """ mountpoint = mount_cache() if mountpoint: logging.info(f'Creating cache directory at {mountpoint}') os.makedirs(f'{mountpoint}/opt/opengnsys/images')