Пример #1
0
def _spawn_fuse(region_name, mountpoint, foreground=True):
    fuse.FUSE(
        ec2fs.ec2fs(ec2_proxy.ec2_proxy()),
        mountpoint,
        foreground=foreground,
        allow_other=True,
        attr_timeout=0)
Пример #2
0
def mount():
    kw = {}

    while True:
        for i, v in enumerate(sys.argv):
            if v == '-o' or v.startswith('-o'):
                break
        else:
            break

        if sys.argv[i] == '-o':
            options = sys.argv[i + 1]
            del sys.argv[i]
            del sys.argv[i]

        else:
            options = sys.argv[i][2:]
            del sys.argv[i]

        for i in options.split(','):
            i = i.strip()
            n = i.find('=')
            if n == -1:
                kw[i] = True
            else:
                kw[i[:n]] = i[n+1:]

    print(sys.argv, kw)
    db = Database(sys.argv[1])
    fuse.FUSE(TagFS(db, kw.pop('base_dir', '.')), sys.argv[2], raw_fi=False, **kw)
Пример #3
0
    def mount(self, mountpoint, foreground=False, threads=False):
        '''
        Mount the filesystem.
        '''

        fuse.FUSE(self.fs, mountpoint, raw_fi=True, nothreads=not threads,
                  foreground=foreground, default_permissions=True)
Пример #4
0
def main():
    if len(sys.argv) < 3:
        print 'usage: {} <root> <mountpoint>'.format(sys.argv[0])
        exit(1)

# Find the filesystem options (the things following "-o")
    options = ""
    for i in range(len(sys.argv)):
        if sys.argv[i] == "-o" and len(sys.argv) > i + 1:
            options = sys.argv[i + 1]

# Turn them into a format fuse.FUSE can handle (kwargs)
    fuse_args = {}
    for option in options.split(","):
        option_parts = option.split("=")
        if len(option_parts) == 1:
            fuse_args[option_parts[0]] = True
        else:
            fuse_args[option_parts[0]] = option_parts[1]

    # Start the FUSE FS
    fuse.FUSE(HideSymlinks(sys.argv[1]),
              sys.argv[2],
              foreground=False,
              **fuse_args)
Пример #5
0
def main():
    parser = argparse.ArgumentParser(
        description="Mount HTML directory listings.")
    parser.add_argument("-o",
                        help="comma separated FUSE options",
                        metavar='OPTIONS')
    parser.add_argument("-t",
                        "--timeout",
                        help="HTTP request timeout",
                        type=int,
                        default=30)
    parser.add_argument("-u", "--user-agent", help="HTTP User-Agent")
    parser.add_argument("-v",
                        "--verbose",
                        help="enable debug logging",
                        action='store_true')
    parser.add_argument("-d",
                        "--daemon",
                        help="run in background",
                        action='store_true')
    parser.add_argument("url", help="URL to mount")
    parser.add_argument("mountpoint", help="filesystem mount point")
    args = parser.parse_args()
    logging.basicConfig(format='%(levelname)s:%(name)s %(message)s',
                        level=logging.DEBUG if args.verbose else logging.INFO)
    CONFIG['timeout'] = args.timeout
    CONFIG['user_agent'] = args.user_agent
    fuseobj = fuse.FUSE(rehttpfs(args.url),
                        args.mountpoint,
                        foreground=(not args.daemon),
                        **convert_fuse_options(args.o))
Пример #6
0
def cli(rawArgs: Optional[List[str]] = None) -> None:
    """Command line interface for ratarmount. Call with args = [ '--help' ] for a description."""

    # The first argument, is the path to the script and should be ignored
    tmpArgs = sys.argv[1:] if rawArgs is None else rawArgs
    if '--version' in tmpArgs or '-v' in tmpArgs:
        print("ratarmount", __version__)
        print("ratarmountcore", core.__version__)
        return

    # tmpArgs are only for the manual parsing. In general, rawArgs is None, meaning it reads sys.argv,
    # and maybe sometimes contains arguments when used programmatically. In that case the first argument
    # should not be the path to the script!
    args = _parseArgs(rawArgs)

    # Convert the comma separated list of key[=value] options into a dictionary for fusepy
    fusekwargs = (dict([
        option.split('=', 1) if '=' in option else (option, True)
        for option in args.fuse.split(',')
    ]) if args.fuse else {})
    if args.prefix:
        fusekwargs['modules'] = 'subdir'
        fusekwargs['subdir'] = args.prefix

    if args.mount_point in args.mount_source and os.path.isdir(
            args.mount_point) and os.listdir(args.mount_point):
        if hasNonEmptySupport():
            fusekwargs['nonempty'] = True

    fuseOperationsObject = FuseMount(
        # fmt: off
        pathToMount=args.mount_source,
        clearIndexCache=args.recreate_index,
        recursive=args.recursive,
        gzipSeekPointSpacing=args.gzipSeekPointSpacing,
        mountPoint=args.mount_point,
        encoding=args.encoding,
        ignoreZeros=args.ignore_zeros,
        verifyModificationTime=args.verify_mtime,
        stripRecursiveTarExtension=args.strip_recursive_tar_extension,
        indexFilePath=args.index_file,
        indexFolders=args.index_folders,
        lazyMounting=args.lazy,
        passwords=args.passwords,
        parallelization=args.parallelization,
        isGnuIncremental=args.gnu_incremental,
        printDebug=args.debug,
        # fmt: on
    )

    fuse.FUSE(
        # fmt: on
        operations=fuseOperationsObject,
        mountpoint=args.mount_point,
        foreground=args.foreground,
        nothreads=
        True,  # Can't access SQLite database connection object from multiple threads
        # fmt: off
        **fusekwargs)
Пример #7
0
def main(root, mountPoint):
    # logging.basicConfig(level=logging.DEBUG)
    allbackups = Backups(root, mountPoint)
    fuse.FUSE(BackupFS(os.path.join(root, "target/backups/"), mountPoint,
                       allbackups),
              mountPoint,
              foreground=True,
              default_permissions=True)
Пример #8
0
def mount(githubdir, mntpoint, verbose=True, foreground=True):
    """
    Mount GithubFuse filesystem to a mountpoint

    @param githubdir str: directory where we keep our github packages [cached]
    @param mntpoint  str: mount point to mount the fuse filesystem to. (e.g. /mnt/github.com)
    """
    fuse.FUSE(GithubOperations(root=githubdir),
              mntpoint, nothreads=True, foreground=foreground)
Пример #9
0
def main(args):
    args = parse_args(args)
    logging.basicConfig(
        level=logging.DEBUG if args.debug else logging.INFO,
        format='%(asctime)s %(levelname)s [%(name)s] %(message)s')
    config = Config(args.config)
    Controller(config)
    ops = SlowFS(args.root, config)
    fuse.FUSE(ops, args.mountpoint, foreground=True)
Пример #10
0
def main():
    faulthandler.enable()

    if len(sys.argv) != 3:
        print('usage: %s <disk> <mountpoint>' % sys.argv[0])
        exit(1)

    op_mgr = manager.DiskManager(sys.argv[1])
    fuse_inst = fuse.FUSE(op_mgr, sys.argv[2], foreground=True)
Пример #11
0
def main(router):
    if len(sys.argv) != 3:
        print('usage: %s <host> <mountpoint>' % sys.argv[0])
        sys.exit(1)

    blerp = fuse.FUSE(
        operations=Operations(sys.argv[1]),
        mountpoint=sys.argv[2],
        foreground=True,
        volname='%s (Mitogen)' % (sys.argv[1], ),
    )
Пример #12
0
 def __init__(self, options):
     self.log = logging.getLogger(__name__)
     path_provided = True
     if not options.directory:
         path_provided = False
         options.directory = tempfile.mkdtemp()
     self.log.info("Statistics files will be available in %s", options.directory)
     fuse.FUSE(MalariaWatcherStatsFS(options),
               options.directory, foreground=True)
     if not path_provided:
         self.log.info("Automatically removing statsfs: %s", options.directory)
         os.rmdir(options.directory)
Пример #13
0
def main(router):
    if len(sys.argv) != 3:
        print('usage: %s <host> <mountpoint>' % sys.argv[0])
        sys.exit(1)

    kwargs = {}
    if sys.platform == 'darwin':
        kwargs['volname'] = '%s (Mitogen)' % (sys.argv[1], )

    fuse.FUSE(operations=Operations(sys.argv[1]),
              mountpoint=sys.argv[2],
              foreground=True,
              **kwargs)
Пример #14
0
def mocked_ec2fs(mocked_ec2_proxy, mountpoint):
    # This fixture is such a badass!

    # To gain a controll over spawned background process
    # we have to spawn it on our own.
    pid = os.fork()

    if pid == 0:
        try:
            LOGGER.debug('FUSE started its work!')
            fuse.FUSE(
                ec2fs.ec2fs(mocked_ec2_proxy),
                str(mountpoint),
                foreground=True,
                allow_other=True,
                attr_timeout=0)
        except Exception as e:
            LOGGER.error('FUSE failed to spawn with exception: %r', e)
            os._exit(1)
        LOGGER.debug('FUSE finished its work!')
        os._exit(0)  # Finish child execution here.

    # FUSE is not be initialized at once - we have to wait.
    while not os.path.exists(f'{mountpoint}/flavors'):
        try:
            os.kill(pid, 0)
        except OSError:
            # FUSE initialization failed, since process
            # terminated before any special file was created.
            _, fuse_exit_status = os.waitpid(pid, 0)
            if fuse_exit_status == 0:
                LOGGER.warning(
                    'FUSE process finished independently with exit_status 0 '
                    '(DUNNO WHAT HAPPEND)')
            raise RuntimeError(
                'FUSE process finished independently with exit_status %d',
                fuse_exit_status)
        time.sleep(0.1)  # Yeah, I know - it's a pure evil, well.. - I'm evil.

    yield mountpoint

    try:
        subprocess.run(
            f'fusermount -u {mountpoint}',
            shell=True,
            capture_output=True,
            check=True)
    except subprocess.CalledProcessError as e:
        LOGGER.error('Failed to umount FUSE instance at "%s": %s',
                     str(mountpoint), e.stderr.decode())
        os.kill(pid, 9)  # F**k it, use the force.
Пример #15
0
def main(mountpoint):

    logging.basicConfig(level=logging.WARNING)

    try:
        fuse.FUSE(fuse_interface(),
                  mountpoint,
                  nothreads=True,
                  foreground=True,
                  direct_io=True)
    except Exception as e:
        print("[interface] faulted : %s" % str(e))
        print("exiting.")
        exit()
Пример #16
0
def launch(mount_point, username=None, foreground=False, verbose=False):
    create_logger(foreground, verbose)

    log.info('Mount point: %s', mount_point)
    fuse_op = create_kuaipan_fuse_operations(username)

    log.info('Start FUSE file system')
    fuse.FUSE(
        fuse_op,
        mount_point,
        foreground=foreground,
        uid=os.getuid(),
        gid=os.getgid(),
        # nonempty=True, # fuse: unknown option `nonempty' on OS X
        nothreads=False,  # on multiple thread
        ro=False)  # readonly
Пример #17
0
def main(mountpoint, root, debug, fuse_debug):
    if fuse_debug:
        redirect_logging()

    # setup logging
    StderrHandler(level=DEBUG if debug else INFO).push_application()

    log.info('mounting index of {} onto {}'.format(root, mountpoint))

    try:
        repo = Repo(root)
    except NotGitRepository:
        log.info('Error: {} is not a git repository'.format(root))
        sys.exit(1)

    fuse.FUSE(IndexFS(root, repo, mountpoint), mountpoint, foreground=False)
Пример #18
0
def main():
    default_path = os.path.join(os.getenv('HOME'), '.dropboxfuse')
    parser = argparse.ArgumentParser()
    parser.add_argument('-m', '--mount-point', type=str, required=True)
    parser.add_argument('-c',
                        '--config',
                        type=str,
                        default=default_path,
                        required=False)
    parser.add_argument('-k',
                        '--app-key',
                        type=str,
                        default=None,
                        required=False)
    parser.add_argument('-s',
                        '--app-secret',
                        type=str,
                        default=None,
                        required=False)
    parser.add_argument('-a',
                        '--access-token',
                        type=str,
                        default=None,
                        required=False)

    options = parser.parse_args()
    log_manager = DropboxLogManager()
    dropbox_client = DropboxClient(options.config, options.app_key,
                                   options.app_secret, options.access_token)
    CacheManager.set_cache('MetadataCache', MetadataCache(dropbox_client))
    CacheManager.set_cache('DataCache', DataCache(dropbox_client))
    dropbox_fuse = DropboxFuse(dropbox_client)
    try:
        dbfuse = fuse.FUSE(dropbox_fuse,
                           options.mount_point,
                           foreground=True,
                           nothreads=True,
                           allow_other=True)
    except Exception as e:
        print str(e)
        raise
    finally:
        del dropbox_fuse
        del dropbox_client
        del log_manager
    return 0
Пример #19
0
def ydl_fuse(d, root, rootbase, foreground=True, allow_other=False):
	"""
	Invoke fuse.py to create a mount point backed by the YDL database.
	This symlinks each video to the actual data file.
	The point of this is to permit mapping of lists to the data files without manipulating the raw data files.
	For example, playlists could include the index in the playlist and thus allow
	 an ordered viewing of the playlist. If, for example, it was formatted for the playlist to
	 appear as a TV series (eg, "{channel} - s1e{index} - {name}") then an app like Plex could
	 pick up and show the YouTube playlist as a series of episodes like a TV show.

	As this is a virtual overlay over the raw data, no actual manipulation to the data is done and would
	 thus permit representing the exact same data in multiple ways simultaneously.
	"""

	if fuse is None:
		raise Exception("Cannot run fuse, it is not installed")

	fuse.FUSE(_ydl_fuse(d, rootbase), root, nothreads=True, foreground=foreground, allow_other=allow_other)
Пример #20
0
def run(options, root_resolver):
    fuse_args = {
        'foreground': options.fuse_foreground,
        'fsname': options.fuse_filesystem_name,
        'nothreads': options.fuse_nothreads,
        # Allow sharing the mount point with Samba / smb / smbd.
        # Requires user_allow_other in /etc/fuse.conf
        # 'allow_other': True,
    }
    if os.uname()[0] == 'Darwin':
        fuse_args['volicon'] = options.macfuse_icon
        fuse_args['local'] = options.macfuse_local_disk
        fuse_args['volname'] = options.fuse_filesystem_name
    else:
        fuse_args['nonempty'] = options.fuse_nonempty

    fuse.FUSE(
        d1_onedrive.impl.drivers.fuse.callbacks.FUSECallbacks(
            options, root_resolver), options.mountpoint, **fuse_args)
Пример #21
0
def main():
    parser = optparse.OptionParser()
    parser.add_option("-v", "--verbose", action="store_true", default=False)
    parser.add_option("-f", "--foreground", action="store_true", default=False)
    options, arguments = parser.parse_args()

    if options.verbose:
        logging.getLogger().setLevel(logging.DEBUG)
        logging.basicConfig()

    if len(arguments) != 2:
        parser.print_help()
        return -1

    f = fuse.FUSE(
        ApacheFuse(arguments[0]),
        arguments[1],
        foreground=options.foreground,
        encoding="latin-1",
    )
Пример #22
0
    def run(self):

        self.m_args = self.m_parser.parse_args()
        self.m_obs.configure(self.m_args.apiurl)
        self.m_root = oscfs.root.Root(self.m_obs, self.m_args)
        if self.m_args.cache_time is not None:
            oscfs.types.Node.setMaxCacheTime(self.m_args.cache_time)

        self._checkAuth()

        fuse.FUSE(
            self,
            self.m_args.mountpoint,
            foreground=self.m_args.f,
            nothreads=True,
            # direct_io is necessary in our use case to avoid
            # caching in the kernel and support dynamically
            # determined file contents
            direct_io=True,
            nonempty=True
        )
Пример #23
0
def run(options, root_resolver):
    fuse_args = {
        "foreground": options.fuse_foreground,
        "fsname": options.fuse_filesystem_name,
        "nothreads": options.fuse_nothreads,
        # Allow sharing the mount point with Samba / smb / smbd.
        # Requires user_allow_other in /etc/fuse.conf
        # 'allow_other': True,
    }
    if os.uname()[0] == "Darwin":
        fuse_args["volicon"] = options.macfuse_icon
        fuse_args["local"] = options.macfuse_local_disk
        fuse_args["volname"] = options.fuse_filesystem_name
    else:
        fuse_args["nonempty"] = options.fuse_nonempty

    fuse.FUSE(
        d1_onedrive.impl.drivers.fuse.callbacks.FUSECallbacks(options, root_resolver),
        options.mountpoint,
        **fuse_args
    )
Пример #24
0
def run(options, root_resolver):
    # FUSE settings common to FUSE and MacFUSE.
    fuse_args = {
        'foreground': options.fuse_foreground,
        'fsname': options.fuse_filesystem_name,
        'nothreads': options.fuse_nothreads,
        # Allow sharing the mount point with Samba / smb / smbd.
        # Requires user_allow_other in /etc/fuse.conf
        # 'allow_other': True,
    }
    # FUSE settings specific to MacFUSE.
    if os.uname()[0] == 'Darwin':
        fuse_args['volicon'] = options.macfuse_icon
        fuse_args['local'] = options.macfuse_local_disk
        fuse_args['volname'] = options.fuse_filesystem_name
    # FUSE settings specific to regular FUSE.
    else:
        fuse_args['nonempty'] = options.fuse_nonempty

    # Mount the drive and handle callbacks forever.
    fuse.FUSE(callbacks.FUSECallbacks(options, root_resolver),
              options.mountpoint, **fuse_args)
Пример #25
0
def main(unused_argv):
  config_lib.CONFIG.AddContext(
      "Commandline Context",
      "Context applied for all command line tools")
  startup.Init()

  if fuse is None:
    logging.critical("""Could not start!
fusepy must be installed to run fuse_mount.py!
Try:
  sudo pip install fusepy""")
    sys.exit(1)

  if not flags.FLAGS.mountpoint:
    Usage()
    sys.exit(1)

  # We multiple inherit from GRRFuse and fuse.Operations. In the
  # case that fuse is present, we run the actual FUSE layer, since we have
  # fuse.Operations. In the case that fuse is not present, we have already
  # exited by now if we were run from the command line, and if we were not run
  # from the command line, we've been imported, and we run the tests using a
  # mock fuse.

  class FuseOperation(GRRFuse, fuse.Operations):
    pass

  root = flags.FLAGS.aff4path

  username = flags.FLAGS.username or getpass.getuser()
  token = access_control.ACLToken(username=username,
                                  reason=flags.FLAGS.reason or "fusemount")

  # If we're exporting a path inside a client, check to see if we have access to
  # that client and get the appropriate token.
  client_id = client.GetClientURNFromPath(root)
  if client_id is not None:
    token = security.Approval.GetApprovalForObject(
        client_id,
        token=token,
        username=username)

  data_store.default_token = token

  logging.info("fuse_mount.py is mounting %s at %s....", root,
               flags.FLAGS.mountpoint)

  refresh_policy = flags.FLAGS.refresh_policy

  if refresh_policy == "always":
    max_age_before_refresh = datetime.timedelta(0)
  elif refresh_policy == "never":
    # Set the max age to be the maximum possible time difference.
    max_age_before_refresh = datetime.timedelta.max
  elif refresh_policy == "if_older_than_max_age":
    max_age_before_refresh = datetime.timedelta(
        seconds=flags.FLAGS.max_age_before_refresh)
  else:
    # Otherwise, a flag outside the enum was given and the flag validator threw
    # an execption.
    pass

  fuse_operation = FuseOperation(
      root=root,
      token=token,
      max_age_before_refresh=max_age_before_refresh,
      ignore_cache=flags.FLAGS.ignore_cache,
      force_sparse_image=flags.FLAGS.force_sparse_image,
      sparse_image_threshold=flags.FLAGS.sparse_image_threshold,
      timeout=flags.FLAGS.timeout)

  fuse.FUSE(fuse_operation, flags.FLAGS.mountpoint,
            foreground=not flags.FLAGS.background)
Пример #26
0
def main(argv):
    del argv  # Unused.
    config.CONFIG.AddContext(contexts.COMMAND_LINE_CONTEXT,
                             "Context applied for all command line tools")
    server_startup.Init()

    if fuse is None:
        logging.fatal("""Could not start!
fusepy must be installed to run fuse_mount.py!
Try to run:
  pip install fusepy

inside your virtualenv.
""")
        sys.exit(1)

    if not flags.FLAGS.mountpoint:
        Usage()
        sys.exit(1)

    # We multiple inherit from GRRFuse and fuse.Operations. In the
    # case that fuse is present, we run the actual FUSE layer, since we have
    # fuse.Operations. In the case that fuse is not present, we have already
    # exited by now if we were run from the command line, and if we were not run
    # from the command line, we've been imported, and we run the tests using a
    # mock fuse.

    class FuseOperation(GRRFuse, fuse.Operations):
        pass

    root = flags.FLAGS.aff4path

    username = flags.FLAGS.username or getpass.getuser()
    data_store.default_token = access_control.ACLToken(
        username=username, reason=flags.FLAGS.reason or "fusemount")

    logging.info("fuse_mount.py is mounting %s at %s....", root,
                 flags.FLAGS.mountpoint)

    refresh_policy = flags.FLAGS.refresh_policy

    if refresh_policy == "always":
        max_age_before_refresh = datetime.timedelta(0)
    elif refresh_policy == "never":
        # Set the max age to be the maximum possible time difference.
        max_age_before_refresh = datetime.timedelta.max
    elif refresh_policy == "if_older_than_max_age":
        max_age_before_refresh = datetime.timedelta(
            seconds=flags.FLAGS.max_age_before_refresh)
    else:
        # Otherwise, a flag outside the enum was given and the flag validator threw
        # an execption.
        pass

    fuse_operation = FuseOperation(
        root=root,
        token=data_store.default_token,
        max_age_before_refresh=max_age_before_refresh,
        ignore_cache=flags.FLAGS.ignore_cache,
        force_sparse_image=flags.FLAGS.force_sparse_image,
        sparse_image_threshold=flags.FLAGS.sparse_image_threshold,
        timeout=flags.FLAGS.timeout)

    fuse.FUSE(fuse_operation,
              flags.FLAGS.mountpoint,
              foreground=not flags.FLAGS.background)
Пример #27
0
def cli():

    global printDebug

    parser = argparse.ArgumentParser(
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
        description="""\
        If no mount path is specified, then the tar will be mounted to a folder of the same name but without a file extension.
        TAR files contained inside the tar and even TARs in TARs in TARs will be mounted recursively at folders of the same name barred the file extension '.tar'.

        In order to reduce the mounting time, the created index for random access to files inside the tar will be saved to <path to tar>.index.<backend>[.<compression]. If it can't be saved there, it will be saved in ~/.ratarmount/<path to tar: '/' -> '_'>.index.<backend>[.<compression].
        """,
    )

    parser.add_argument(
        "-f",
        "--foreground",
        action="store_true",
        default=False,
        help="keeps the python program in foreground so it can print debug"
        "output when the mounted path is accessed.",
    )

    parser.add_argument(
        "-d",
        "--debug",
        type=int,
        default=1,
        help="sets the debugging level. Higher means more output. Currently 3 is the highest",
    )

    parser.add_argument(
        "-c",
        "--recreate-index",
        action="store_true",
        default=False,
        help="if specified, pre-existing .index files will be deleted and newly created",
    )

    parser.add_argument(
        "-r",
        "--recursive",
        action="store_true",
        default=False,
        help="mount TAR archives inside the mounted TAR recursively. Note that this only has an effect when creating an index. If an index already exists, then this option will be effectively ignored. Recreate the index if you want change the recursive mounting policy anyways.",
    )

    parser.add_argument(
        "-s",
        "--serialization-backend",
        type=str,
        default="custom",
        help="specify which library to use for writing out the TAR index. Supported keywords: ("
        + ",".join(IndexedTar.availableSerializationBackends)
        + ")[.("
        + ",".join(IndexedTar.availableCompressions).strip(",")
        + ")]",
    )

    parser.add_argument(
        "-p",
        "--prefix",
        type=str,
        default="",
        help="The specified path to the folder inside the TAR will be mounted to root. "
        "This can be useful when the archive as created with absolute paths. "
        "E.g., for an archive created with `tar -P cf /var/log/apt/history.log`, "
        "-p /var/log/apt/ can be specified so that the mount target directory "
        ">directly< contains history.log.",
    )

    parser.add_argument(
        "tarfilepath",
        metavar="tar-file-path",
        type=argparse.FileType("r"),
        nargs=1,
        help="the path to the TAR archive to be mounted",
    )
    parser.add_argument(
        "mountpath",
        metavar="mount-path",
        nargs="?",
        help="the path to a folder to mount the TAR contents into",
    )

    args = parser.parse_args()

    tarToMount = os.path.abspath(args.tarfilepath[0].name)
    try:
        tarfile.open(tarToMount, mode="r:")
    except tarfile.ReadError:
        print(
            "Archive",
            tarToMount,
            "can't be opened!",
            "This might happen for compressed TAR archives, which currently is not supported.",
        )
        exit(1)

    mountPath = args.mountpath
    if mountPath is None:
        mountPath = os.path.splitext(tarToMount)[0]

    mountPathWasCreated = False
    if not os.path.exists(mountPath):
        os.mkdir(mountPath)

    printDebug = args.debug

    fuseOperationsObject = TarMount(
        pathToMount=tarToMount,
        clearIndexCache=args.recreate_index,
        recursive=args.recursive,
        serializationBackend=args.serialization_backend,
        prefix=args.prefix,
    )

    fuse.FUSE(
        operations=fuseOperationsObject,
        mountpoint=mountPath,
        foreground=args.foreground,
        allow_other=True,
    )

    if mountPathWasCreated and args.foreground:
        os.rmdir(mountPath)
Пример #28
0
def StartFuseFS():
    parser = argparse.ArgumentParser(  #prog='FuseMirrorFS.py',
        description=
        'A revisioned filesystem which stores all content and revisions in another directory.'
    )
    parser.add_argument(
        'source_dir',
        metavar='source',
        help='the source directory where the files and revisions will be stored'
    )
    parser.add_argument(
        'mount_dir',
        metavar='target',
        help='the directory where to mount the source directory to')
    parser.add_argument('-f',
                        dest='foreground',
                        action='store_true',
                        help='run in foreground (default: run in background)')
    parser.add_argument(
        '-v',
        dest='verbose',
        action='count',
        help=
        'show more information, can be used several times to get even more information'
    )
    parser.add_argument(
        '-l',
        dest='log_file',
        help='log file. Default: {0} or stderr when -f is given'.format(
            log_file))

    args = parser.parse_args()

    #print (repr (args))

    if args.verbose == None:
        log_level = logging.ERROR
    elif args.verbose == 1:
        log_level = logging.WARNING
    elif args.verbose == 2:
        log_level = logging.INFO
    else:
        log_level = logging.DEBUG

    logger = logging.getLogger()
    logger.setLevel(log_level)

    ch = logging.StreamHandler()
    if args.log_file != None:
        ch = logging.FileHandler(args.log_file)
    elif not args.foreground:
        ch = logging.FileHandler(log_file)

    ch.setLevel(log_level)
    logger.addHandler(ch)

    if args.foreground:
        logger.info("Running in foreground...")

    logger.info("Mounting %s on %s", args.source_dir, args.mount_dir)

    rev_fs = RevisionFS(args.source_dir)
    fuse.FUSE(rev_fs, args.mount_dir, foreground=args.foreground)
Пример #29
0
#!/usr/bin/env python2

import fuse
import time
import sys
import errno

class fs(fuse.Operations):
    def getattr(self, path, fh=None):
        if "blockme" in path:
            raw_input('blocked, press enter')
        raise fuse.FuseOSError(errno.ENOENT)

fuse.FUSE(fs(), sys.argv[1], foreground=True)
Пример #30
0
def main(mountpoint, sunsign, moonsign):
    fuse.FUSE(HoroscopeFS(sunsign, moonsign),
              mountpoint,
              nothreads=True,
              foreground=True)