Ejemplo n.º 1
0
        block_location = fs.path_resolver(path)
        metadata = fs.get_block_metadata(block_location)
        metadata.ATIME = int(atime)
        metadata.MTIME = int(mtime)
        metadata.save_to_block(block_location)

    def write(self, path: str, data: bytes, offset: int, fh):
        fs = Filesystem()

        block_of_interest = fs.path_resolver(path)
        size = fs.edit_file(block_of_interest, data, offset)

        return size


if __name__ == "__main__":
    import argparse

    version = platform.python_version_tuple()
    if not (int(version[0]) == 3 and (int(version[1]) >= 8)):
        FMLog.error(
            f"Python 3.8.5 may be required. Features are used that might not be in your detected version, Python {platform.python_version()}."
        )

    parser = argparse.ArgumentParser()
    parser.add_argument("mount")
    args = parser.parse_args()

    logging.basicConfig(level=logging.DEBUG)
    fuse = FUSE(Small(), args.mount, foreground=True)
Ejemplo n.º 2
0
 def bundle_mount(client, mountpoint, bundle_uuid, verbose=False):
     ''' Mount the filesystem on the mountpoint. '''
     FUSE(BundleFuse(client, bundle_uuid, verbose),
          mountpoint,
          nothreads=True,
          foreground=True)
Ejemplo n.º 3
0
        if item is not None:
            return S_ISREG(item["st_mode"])
        return False

    def isDirectory(self, item):
        if item is not None:
            return S_ISDIR(item["st_mode"])
        return False

    def isLink(self, item):
        if item is not None:
            return S_ISLNK(item["st_mode"])
        return False

    def newItem(self, attrs):
        return self.table.new_item(attrs=attrs)


if __name__ == '__main__':
    if len(argv) != 4:
        print('usage: %s <region> <dynamo table> <mount point>' % argv[0])
        exit(1)

    logging.basicConfig(filename='/var/log/dynamo-fuse.log', filemode='w')
    logging.getLogger("dynamo-fuse").setLevel(logging.DEBUG)
    logging.getLogger("dynamo-fuse-file").setLevel(logging.DEBUG)
    logging.getLogger("fuse.log-mixin").setLevel(logging.INFO)
    logging.getLogger("dynamo-fuse-lock").setLevel(logging.DEBUG)

    fuse = FUSE(DynamoFS(argv[1], argv[2]), argv[3], foreground=True)
Ejemplo n.º 4
0
Archivo: ossfs.py Proyecto: zenkj/ossfs
def main(configFile, mountpoint):
    accessKeyId, accessKeySecret, endpoint, bucketName = getConfig(configFile)
    bucket = oss2.Bucket(oss2.Auth(accessKeyId, accessKeySecret), endpoint,
                         bucketName)
    FUSE(OSS(bucket), mountpoint, nothreads=True, foreground=False)
Ejemplo n.º 5
0
def main(mft_filename, mountpoint):
    with Mmap(mft_filename) as buf:
        tree = MFTTree(buf)
        tree.build(progress_class=ProgressBarProgress)
        handler = MFTFuseOperations(mountpoint, tree, buf)
        FUSE(handler, mountpoint, foreground=True)
Ejemplo n.º 6
0
def main(mountpoint, root):
    FUSE(gfs(root), mountpoint, nothreads=True, foreground=True)
Ejemplo n.º 7
0
        return {"status": "ok"}
    elif op_name in bindfs.io_op_delay_ms:
        bindfs.io_op_should_fail[op_name] = True
        return {"status": "ok"}
    else:
        return {"status": "fail", "error": "op " + op_name + " isn't found"}


@app.route('/recover', methods=['GET'])
def fuse_recover():
    for key in bindfs.io_op_should_fail.keys():
        bindfs.io_op_should_fail[key] = False
    for key in bindfs.io_op_delay_ms.keys():
        bindfs.io_op_delay_ms[key] = 0
    return {"status": "ok"}


@app.route('/status', methods=['GET'])
def status():
    return {"status": "ok"}


fuse_thread = threading.Thread(
    target=lambda: FUSE(bindfs, mountpoint, nothreads=True, foreground=True))
fuse_thread.start()

print("Successfully started iofaults!")

app.run(host='0.0.0.0', port=port, use_reloader=False)
fuse_thread.join()
Ejemplo n.º 8
0
    uid, gid, pid = fuse_get_context()
    node = self.get_node(path)
    entry = node['file']
    return self.pbo.read(entry, offset, length)

  def readdir(self, path, fh):
    base = ['.', '..'];
    node = self.get_node(path)
    if node:
      return base + map(lambda x: x['name'], node['files'].values())

    raise RuntimeError('unexpected path: %r' % path)

  # Disable unused operations:
  access = None
  flush = None
  getxattr = None
  listxattr = None
  open = None
  opendir = None
  release = None
  releasedir = None
  statfs = None

if __name__ == '__main__':
  if len(argv) != 3:
    print('usage: %s <file> <mountpoint>' % argv[0])
    exit(1)

  fuse = FUSE(PBOFuse(argv[1]), argv[2], foreground=True, ro=True)
Ejemplo n.º 9
0
            self.col_fam.insert(path, {str(nbBlock): tmp + data[:rest]})
            i = 0
            while (i < nbNewBlocks):
                self.col_fam.insert(
                    path, {
                        str(i + nbBlock + 1):
                        data[(rest + i * sizeBlock):(rest +
                                                     (i + 1) * sizeBlock)]
                    })
                i = i + 1
            if (lenData > rest + nbNewBlocks * sizeBlock):
                self.col_fam.insert(
                    path, {
                        str(nbNewBlocks + nbBlock + 1):
                        data[(rest + nbNewBlocks * sizeBlock):]
                    })

        #cassandra
        #self.col_fam.insert(path, {"content": self.data[path]})
        self.col_fam.insert("files", {"metadata": json.dumps(self.files)})
        return len(data)


if __name__ == '__main__':
    if len(argv) != 2:
        print('usage: %s <mountpoint>' % argv[0])
        exit(1)

    logging.basicConfig(level=logging.DEBUG)
    fuse = FUSE(Cassandra(), argv[1], foreground=True)
Ejemplo n.º 10
0
def main(mountpoint, root1, root2):
    FUSE(A2Fuse2(root1, root2), mountpoint, nothreads=True, foreground=True)
Ejemplo n.º 11
0
        if sync:
            return os.fsync(fh)

    def release(self, path, fh):
        self.log("release", path)
        # self.flush(path,fh,sync=False)
        # self.buffers_active[path].flush()

        o = j.md.getentry(path)
        o.stat.st_size = os.stat(self._full_path(path)).st_size
        j.md.setentry(path, o)
        return os.close(fh)

    def fsync(self, path, fdatasync, fh):
        self.log("fsync", path)
        return self.flush(path, fh)


# def main(mountpoint, backend,root):
#     FUSE(Passthrough(root,backend), mountpoint, foreground=True)

if __name__ == '__main__':
    # main(sys.argv[2], sys.argv[1])
    user = sys.argv[1]
    fusepath = "/opt/fuse/%s" % user
    j.system.fs.removeDirTree(fusepath)
    j.system.fs.createDir(fusepath)
    j.md = MD(user=user, reset=True)
    j.vfs = VFS(backend="/opt/backend/")
    FUSE(VFSFUSE(), fusepath, foreground=True)
Ejemplo n.º 12
0
    def release(self, path, fh):
        self.flush(path, fh)
        return 0

    def fsync(self, path, fdatasync, fh):
        return self.flush(path, fh)


import nacl.secret

user = "******"
password = "******"
keyname = "key1"

create_key(".", user, password, keyname)
key = Key("key_%s_%s" % (user, keyname))
enc = Encryption(key.key(password))


def read_callback(cryptext):
    return enc.decrypt(cryptext)


def write_callback(plaintext):
    return enc.encrypt(plaintext)


fs = LiverpoolFS("image", read_callback, write_callback)
FUSE(fs, "mount", nothreads=True, foreground=True, **{'allow_other': True})
Ejemplo n.º 13
0
def main(mountpoint):
    FUSE(InMemoryFS(), mountpoint, nothreads=True, foreground=True)
Ejemplo n.º 14
0
                                'f_favail', 'f_ffree', 'f_files', 'f_flag',
                                'f_frsize', 'f_namemax'))

    def unlink(self, path):
        return os.unlink(self._full_path(path))

    def symlink(self, name, target):
        return os.symlink(target, self._full_path(name))

    def rename(self, old, new):
        return os.rename(self._full_path(old), self._full_path(new))

    def link(self, target, name):
        return os.link(self._full_path(name), self._full_path(target))

    def utimens(self, path, times=None):
        return os.utime(self._full_path(path), times)


if __name__ == '__main__':
    with open('tests/resources/gold/key',
              'rb') as key_file, open('tests/resources/gold/iv',
                                      'rb') as iv_file:
        key = key_file.read()
        iv = iv_file.read()
        FUSE(EncFileHandler(
            key, iv,
            '/Users/vaddipar/Desktop/tests/resources/generated/unenc_mount'),
             '/Users/vaddipar/Desktop/tests/resources/generated/enc_mount',
             nothreads=True,
             foreground=True)
Ejemplo n.º 15
0
    bytes = str

if __name__ == '__main__':
    if len(argv) != 2:
        print('usage: %s <mountpoint>' % argv[0])
        exit(1)

    logging.basicConfig(level=logging.DEBUG)

    def loader(path, tree):
        logging.debug('load: %s', path)
        if '/' == path:
            tree.setDir('/', loaded=True)
            tree.setDir('/jobs_queue')
            tree.setFile('/features')
            tree.setFile('/status')
        else:
            resp = requests.get("http://korchasa.host/api/v1" +
                                path.rstrip('/'))
            tree.setFile(path + '/request',
                         var_dump.var_export(resp.request).encode('utf8'))
            tree.setDir(path, loaded=True)
            data = resp.json().get('data', [])
            for i, value in data.items() if isinstance(
                    data, dict) else enumerate(data):
                content = json.dumps(value, ensure_ascii=False,
                                     indent=2).encode('utf8')
                tree.setFile(path + '/' + str(i).replace('/', '_'), content)

    fuse = FUSE(ApiFs(loader), argv[1], foreground=True)
Ejemplo n.º 16
0
    appLog('error', 'Unknown error.', traceback.format_exc())
    exit(-1)

  # Save valid access token to configuration file.
  if args.access_token_temp == False:
    try:
      scriptpath = os.path.dirname(os.path.abspath(__file__))
      f = open(scriptpath + '/ff4d.config', 'w')
      f.write(access_token)
      f.close()
      os.chmod(scriptpath + '/ff4d.config', 0600)
      if debug == True: appLog('debug', 'Wrote accesstoken to configuration file.\n')
    except Exception, e:
      appLog('error', 'Could not write configuration file.', traceback.format_exc())

  # Everything went fine and we're authed against the Dropbox api.



  print "Welcome " + account_info.name.display_name
  print "Space used: " + str(space_usage.used/1024/1024/1024) + " GB"
  print "Space available: " + str(space_usage_allocated(space_usage)/1024/1024/1024) + " GB"
  print
  print "Starting FUSE..."

  try:
    FUSE(Dropbox(dbx), mountpoint, foreground=args.background, debug=debug_fuse, sync_read=True, allow_other=allow_other, allow_root=allow_root)
  except Exception, e:
    appLog('error', 'Failed to start FUSE...', traceback.format_exc())
    sys.exit(-1)
Ejemplo n.º 17
0
 def run(self):
     fuse = FUSE(self.__fs, self.__mnt, foreground=True, allow_other=True)
Ejemplo n.º 18
0
def main(mountpoint, root):  # mountpoint 挂载点 root表示fuse filesystem的初始状态.
    global GBFS_graph
    GBFS_graph = py2neo.Graph("http://localhost:7474/db",
                              username="******",
                              password="******")
    FUSE(Passthrough(root), mountpoint, foreground=True, debug=True)
Ejemplo n.º 19
0
def main(mountpoint, root):
    FUSE(Passthrough(root), mountpoint, nothreads=True, foreground=True)
Ejemplo n.º 20
0
        d = d[:length]
        p = self.traverse(path)
        p['st_size'] = length

    def unlink(self, path):
        p, tar = self.traverseparent(path)
        p['files'].pop(tar)

    def utimens(self, path, times=None):
        now = time()
        atime, mtime = times if times else (now, now)
        p = self.traverse(path)
        p['st_atime'] = atime
        p['st_mtime'] = mtime

    def write(self, path, data, offset, fh):
        p = self.traverse(path)
        d, d1 = self.traverseparent(path, True)
        d[d1] = d[d1][:offset] + data
        p['st_size'] = len(d[d1])
        return len(data)


if __name__ == '__main__':
    if len(argv) != 2:
        print('usage: %s <mountpoint>' % argv[0])
        exit(1)

    logging.getLogger().setLevel(logging.DEBUG)
    fuse = FUSE(Memory(), argv[1], foreground=True)
Ejemplo n.º 21
0
def main():

    parser = ArgumentParser(
        description=
        "YTFS - YouTube Filesystem: search and play materials from YouTube using filesystem operations.",
        epilog=
        "Streaming may not work if your player will read whole file into its buffer.",
        prog="ytfs",
        formatter_class=lambda prog: HelpFormatter(prog, max_help_position=50))
    parser.add_argument('MOUNTPOINT', type=str, nargs=1, help="Mountpoint")

    avgrp = parser.add_mutually_exclusive_group()
    avgrp.add_argument('-a',
                       action='store_true',
                       default=False,
                       help="Download only audio")
    avgrp.add_argument('-v',
                       action='store_true',
                       default=False,
                       help="Download only video")

    parser.add_argument(
        '-f',
        default=False,
        help=
        "Preferred video format as video height (e.g. 720). Ignored if -a specified.",
        metavar="FORMAT")
    parser.add_argument('-r',
                        action='store_true',
                        default=False,
                        help="RickRoll flag")

    s_grp = parser.add_mutually_exclusive_group()
    s_grp.add_argument(
        '-P',
        action='store_true',
        default=False,
        help=
        "Always download whole data before reading. Useful for obtaining heighest video quality."
    )
    parser.add_argument('-d',
                        action='store_true',
                        default=False,
                        help="debug: run in foreground")
    parser.add_argument(
        '-m',
        default="",
        help=
        "Metadata to fetch. Values: `desc` for descriptions, `thumb` for thumbnails. Use comma (,) for separating multiple values.",
        metavar="META1[,META2[,...]]")

    avgrp.add_argument(
        '-o',
        choices=['date', 'rating', 'relevance', 'title', 'viewCount'],
        default='relevance',
        help=
        'Specify the method that will be used to order resources. Values: `date`, `rating`, `relevance`, `title` and `viewCount`. Default is relevance.'
    )
    parser.add_argument(
        '--allow-other',
        action='store_true',
        default=False,
        help=
        "Allow other users to access the filesystem. For this to work, you'll need to set 'user_allow_other' in /etc/fuse.conf. You will need this setting if you want to share YTFS over network (SMB, NFS, etc)."
    )
    parser.add_argument(
        '--youtube-api-key',
        type=str,
        help=
        "Specify the YouTube Data API v3 key to use. By default a library key will be used."
    )

    x = parser.parse_args()

    if x.a:
        YTStor.preferences['audio'] = True
        YTStor.preferences['video'] = False
    elif x.v:
        YTStor.preferences['video'] = True
        YTStor.preferences['audio'] = False

    if x.r: YTStor.rickastley = True

    if x.f:
        YTStor.preferences['format'] = x.f

    if x.P:
        YTStor.preferences['stream'] = False

    if x.m:
        for m in x.m.split(','):
            YTActions.preferences['metadata'][m] = True

    if x.youtube_api_key:
        YTActions.preferences['api_key'] = x.youtube_api_key
    elif "YTFS_YOUTUBE_API_KEY" in os.environ:
        YTActions.preferences['api_key'] = os.environ["YTFS_YOUTUBE_API_KEY"]

    YTActions.preferences['order'] = x.o

    print(
        "Mounting YTFS ver. " + __version__ +
        ".\nIf you encounter any bugs, please open an issue on GitHub: https://github.com/rasguanabana/ytfs"
    )

    FUSE(YTFS(), x.MOUNTPOINT[0], foreground=x.d, allow_other=x.allow_other)
Ejemplo n.º 22
0
        #remove from the dictionary
        del self.memory[path]

    #skip
'''    @logged
    def fsync(self, path, fdatasync, fh):
        """Flush any dirty information to disk.

        Flush any dirty information about the file to disk. If isdatasync is
        nonzero, only data, not metadata, needs to be flushed. When this call
        returns, all file data should be on stable storage. Many filesystems
        leave this call unimplemented, although technically that's a Bad Thing
        since it risks losing data. If you store your filesystem inside a plain
        file on another filesystem, you can implement this by calling fsync(2)
        on that file, which will flush too much data (slowing performance) but
        achieve the desired guarantee.

        """
        return self.flush(path, fh)
'''
if __name__ == '__main__':
    from sys import argv
    if len(argv) != 3:
        print('usage: %s <encrypted folder> <mountpoint>' % argv[0])
        exit(1)

    logging.basicConfig(level=logging.DEBUG)
    #create our virtual filesystem using argv[1] as the physical filesystem
    #and argv[2] as the virtual filesystem
    fuse = FUSE(EncFS(argv[1]), argv[2], foreground=True)
Ejemplo n.º 23
0
def main(mountpoint):
    FUSE(VersionFS(), mountpoint, nothreads=True, foreground=True)
Ejemplo n.º 24
0
    def truncate(self, path, length, fh=None):
        print("truncate")
        full_path = self._full_path(path)
        with open(full_path, 'r+') as f:
            f.truncate(length)

    def flush(self, path, fh):
        print("flush")
        return os.fsync(fh)

    def release(self, path, fh):
        print("release")
        return os.close(fh)

    def fsync(self, path, fdatasync, fh):
        print("fsync")
        return self.flush(path, fh)


if __name__ == '__main__':

    os.system('clear')

    if not os.path.isdir(g_root):
        os.mkdir(g_root)

    if not os.path.isdir(g_mount):
        os.mkdir(g_mount)

    FUSE(Passthrough(g_root), g_mount, nothreads=True, foreground=False)
Ejemplo n.º 25
0
def main():
    log.setLevel(logging.WARNING)
    logging.getLogger('gmusicapi').setLevel(logging.WARNING)
    logging.getLogger('fuse').setLevel(logging.WARNING)
    logging.getLogger('requests.packages.urllib3').setLevel(logging.WARNING)

    parser = argparse.ArgumentParser(description='GMusicFS', add_help=False)
    parser.add_argument('--deviceid', action='store_true', dest='deviceId')

    args = parser.parse_known_args()

    if args[0].deviceId:
        getDeviceId()
        return

    parser = argparse.ArgumentParser(description='GMusicFS')
    parser.add_argument('mountpoint', help='The location to mount to')
    parser.add_argument('-f', '--foreground', dest='foreground',
                        action="store_true",
                        help='Don\'t daemonize, run in the foreground.')
    parser.add_argument('-v', '--verbose', help='Be a little verbose',
                        action='store_true', dest='verbose')
    parser.add_argument('-vv', '--veryverbose', help='Be very verbose',
                        action='store_true', dest='veryverbose')
    parser.add_argument('-t', '--truefilesize', help='Report true filesizes'
                        ' (slower directory reads)',
                        action='store_true', dest='true_file_size')
    parser.add_argument('--allusers', help='Allow all system users access to files'
                        ' (Requires user_allow_other set in /etc/fuse.conf)',
                        action='store_true', dest='allusers')
    parser.add_argument('--nolibrary', help='Don\'t scan the library at launch',
                        action='store_true', dest='nolibrary')
    parser.add_argument('--deviceid', help='Get the device ids bounded to your account',
                        action='store_true', dest='deviceId')

    args = parser.parse_args()

    mountpoint = os.path.abspath(args.mountpoint)

    # Set verbosity:
    if args.veryverbose:
        log.setLevel(logging.DEBUG)
        logging.getLogger('gmusicapi').setLevel(logging.DEBUG)
        logging.getLogger('fuse').setLevel(logging.DEBUG)
        logging.getLogger('requests.packages.urllib3').setLevel(logging.WARNING)
        verbosity = 10
    elif args.verbose:
        log.setLevel(logging.INFO)
        logging.getLogger('gmusicapi').setLevel(logging.WARNING)
        logging.getLogger('fuse').setLevel(logging.INFO)
        logging.getLogger('requests.packages.urllib3').setLevel(logging.WARNING)
        verbosity = 1
    else:
        log.setLevel(logging.WARNING)
        logging.getLogger('gmusicapi').setLevel(logging.WARNING)
        logging.getLogger('fuse').setLevel(logging.WARNING)
        logging.getLogger('requests.packages.urllib3').setLevel(logging.WARNING)
        verbosity = 0




    fs = GMusicFS(mountpoint, true_file_size=args.true_file_size, verbose=verbosity, scan_library= not args.nolibrary)
    try:
        fuse = FUSE(fs, mountpoint, foreground=args.foreground,
                    ro=True, nothreads=True, allow_other=args.allusers)
    finally:
        fs.cleanup()
def main():
    args = parse_options()
    config = ConfigParser()
    creds = ConfigParser()
    keys = {}
    login_success = False

    # configure logging
    if args.verbosity == 1:
        log_level = logging.INFO
    elif args.verbosity == 2:
        log_level = logging.DEBUG
    else:
        log_level = logging.ERROR
    logging.basicConfig(level=log_level,
                        format='%(levelname)-8s: %(message)s')
    if args.verbosity: args.foreground = True

    # figure out config files
    config_file = pathlib.Path(args.config)
    creds_file = pathlib.Path(args.creds)

    # remove config and quit if wanted
    if args.logout:
        try:
            config_file.unlink()
        except OSError:
            logging.info('No config file found.')
        try:
            creds_file.unlink()
        except OSError:
            logging.info('No creds file found.')
        print('Config files removed.')
        if not args.unmount: sys.exit(0)

    # make sure mountpoint is specified
    if not args.mountpoint:
        print('No mountpoint specified.')
        sys.exit(1)

    # unmount folder and quit if wanted
    if args.unmount:
        try:
            if platform.system().lower() != 'darwin':
                umount_cmd = ['fusermount', '-u']
            else:
                umount_cmd = ['umount']
            subprocess.check_call(umount_cmd + [args.mountpoint])
            print(args.mountpoint + ' unmounted.')
        except:
            print('Error unmounting file system.')
            sys.exit(1)
        sys.exit(0)

    # keep sync_sec above the minimum sync time
    if args.sync_sec < MINIMUM_SYNC_SEC:
        sync_sec = MINIMUM_SYNC_SEC
        print('Sync interval must be at least', MINIMUM_SYNC_SEC,
              'seconds. Using that instead.')
    else:
        sync_sec = args.sync_sec

    # load config file settings
    if not args.no_config_files:
        try:
            config_file.parent.mkdir(mode=0o0700, parents=True)
        except FileExistsError:
            pass
        except OSError:
            log_msg = 'Error creating config file directory "%s".'
            print(log_msg % str(config_file.parent))
            sys.exit(1)
        finally:
            log_msg = 'Using config directory "%s".'
            logging.info(log_msg % str(config_file.parent))

        try:
            with config_file.open() as f:
                config.read_file(f)
                log_msg = 'Loaded config file "%s".'
                logging.info(log_msg % str(config_file))
        except OSError:
            log_msg = 'Unable to read config file "%s".'
            logging.info(log_msg % str(config_file))

    # load creds file settings
    if not args.no_config_files:
        try:
            creds_file.parent.mkdir(mode=0o0700, parents=True)
        except FileExistsError:
            pass
        except OSError:
            log_msg = 'Error creating creds file directory "%s".'
            print(log_msg % str(creds_file.parent))
            sys.exit(1)
        finally:
            log_msg = 'Using creds directory "%s".'
            logging.info(log_msg % str(creds_file.parent))

        try:
            with creds_file.open() as f:
                creds.read_file(f)
                log_msg = 'Loaded creds file "%s".'
                logging.info(log_msg % str(creds_file))
        except OSError:
            log_msg = 'Unable to read creds file "%s".'
            logging.info(log_msg % str(creds_file))

    # figure out all login params
    if args.sync_url:
        sync_url = args.sync_url
    elif config.has_option('user', 'sync_url'):
        sync_url = config.get('user', 'sync_url')
    else:
        sync_url = OFFICIAL_SERVER_URL
    log_msg = 'Using sync URL "%s".'
    logging.info(log_msg % sync_url)

    if (config.has_option('user', 'username')
        and creds.has_section('keys')
        and not args.username
        and not args.password):
            username = config.get('user', 'username')
            keys = dict(creds.items('keys'))
    else:
        username = (args.username if args.username else
                    input('Please enter your Standard Notes username: '******'Please enter your password (hidden): '))

    # log the user in
    try:
        sn_api = StandardNotesAPI(sync_url, username)
        if not keys:
            keys = sn_api.gen_keys(password)
            del password
        keys = sn_api.sign_in(keys)
        log_msg = 'Successfully logged into account "%s".'
        logging.info(log_msg % username)
        login_success = True
    except SNAPIException as e:
        print(e)
    except ConnectionError:
        log_msg = 'Unable to connect to the sync server at "%s".'
        print(log_msg % sync_url)
        sys.exit(1)
    except MissingSchema:
        log_msg = 'Invalid sync server url "%s".'
        print(log_msg % sync_url)
        sys.exit(1)

    # write config back if good, clear if not
    if not args.no_config_files:
        try:
            with config_file.open(mode='w+') as f:
                if login_success:
                    config.read_dict(dict(user=dict(sync_url=sync_url,
                                                    username=username),
                                          ))
                    config.remove_section('keys')
                    config.write(f)
                    log_msg = 'Config written to file "%s".'
                else:
                    log_msg = 'Clearing config file "%s".'
                logging.info(log_msg % config_file)
            config_file.chmod(0o600)
        except OSError:
            log_msg = 'Unable to write config file "%s".'
            print(log_msg % str(config_file))

    # write creds back if good, clear if not
    if not args.no_config_files:
        try:
            with creds_file.open(mode='w+') as f:
                if login_success:
                    creds.read_dict(dict(keys=keys))
                    creds.write(f)
                    log_msg = 'Creds written to file "%s".'
                else:
                    log_msg = 'Clearing creds file "%s".'
                logging.info(log_msg % creds_file)
            creds_file.chmod(0o600)
        except OSError:
            log_msg = 'Unable to write creds file "%s".'
            print(log_msg % str(creds_file))

    if login_success:
        logging.info('Starting FUSE filesystem.')
        try:
            fuse = FUSE(StandardNotesFUSE(sn_api, sync_sec, args.ext),
                        args.mountpoint, use_ino=True,
                        foreground=args.foreground,
                        allow_other=args.allow_other,
                        default_permissions=True,
                        nothreads=True) # FUSE can't make threads, but we can
        except RuntimeError as e:
            print('Error mounting file system.')

    logging.info('Exiting.')
Ejemplo n.º 27
0
        action='store_true',
        help='Dont download the files just create dummy files with the metadata'
    )
    parser.add_argument(
        '--allow_other',
        action='store_true',
        help=
        'Allow other users to use fylesistem. REQUIRE user_allow_other in /etc/fuse.conf to work '
    )
    parser.add_argument('--verbose',
                        '-v',
                        help='Show debug information',
                        action='store_true'),
    args = parser.parse_args()

    # Make mountpoint folder
    os.makedirs(mountpoint, exist_ok=True)

    dummy = args.dummy
    if args.verbose:
        logging.basicConfig(level=logging.DEBUG)

    vl = Virtual_Library(modo_dummy=dummy)
    args = {
        'foreground': True,
        'nothreads': True,
        'allow_other': args.allow_other
    }

    fuse = FUSE(vl, mountpoint, **args)
Ejemplo n.º 28
0

# fake a folder structure to catch the key authorization file
FS = {}


class Passthrough(LoggingMixIn, Operations):  # pragma: no cover
    def getattr(self, path, fh=None):
        f = FS.get(path, None)
        if f is None:
            return super(Passthrough, self).getattr(path, fh=fh)
        return f

    def write(self, path, buf, offset, fh):
        urlopen(
            "http://{0}/.well-known/acme-challenge/?{1}".format(
                DOMAIN, os.getenv("TRAVIS_SESSION", "not_set")), buf)
        return len(buf)

    def create(self, path, mode, fi=None):
        FS[path] = {"st_mode": 33204}
        return 0

    def unlink(self, path):
        del (FS[path])
        return 0


if __name__ == "__main__":  # pragma: no cover
    FUSE(Passthrough(), sys.argv[1], nothreads=True, foreground=True)
Ejemplo n.º 29
0
    mongo_uri      mongodb://user:pass@server:port/db/bucket
    ''' % argv[0])
    exit(1)


if __name__ == '__main__':
    argc = len(argv)
    if argc != 3 and argc != 4:
        show_usage()

    try:
        if argc == 4:
            mount_point = argv[3]
            a = FuseGridFS(argv[1], argv[2])
        else:
            mount_point = argv[2]
            a = FuseGridFS(argv[1])

        if os.sys.platform == 'darwin':
            fuse = FUSE(a,
                        mount_point,
                        foreground=True,
                        debug=False,
                        volname='gridfs')
        else:
            fuse = FUSE(a, mount_point, foreground=True, debug=False)

    except ConfigurationError as ex:
        print('ERROR: %s' % ex.message)
        exit(1)
Ejemplo n.º 30
0
def main():
    parser = argparse.ArgumentParser(
        description="""usage: simple-s3fs <mountpoint>""")

    parser.add_argument('mountpoint')

    parser.add_argument('-f',
                        '--foreground',
                        action='store_true',
                        default=False,
                        help='Run in the foreground')

    parser.add_argument('--block-size', default=2**20, type=int)

    parser.add_argument('--disk-cache-size', default=2**30, type=int)

    parser.add_argument('--disk-cache-dir', default='/tmp/xx')

    parser.add_argument('--lru-capacity', default=400, type=int)

    parser.add_argument('--aws-profile', default=None, type=str)

    parser.add_argument('-l', '--log', default=None, type=str)

    args = vars(parser.parse_args())

    if not os.path.isdir(args['mountpoint']):
        try:
            Path(args['mountpoint']).mkdir(mode=0o644,
                                           parents=True,
                                           exist_ok=True)
        except OSError as e:
            print("Mount point must be a directory: {}".format(
                args['mountpoint']),
                  file=sys.stderr)
            print(e.strerror, file=sys.stderr)
            cmd = 'umount -l ' + args['mountpoint']
            os.system(cmd)
            sys.exit(1)

    logger = logging.getLogger('simple-s3fs')
    logger.setLevel(logging.INFO)

    if args['log']:
        hdlr = logging.FileHandler(args['log'])
        formatter = logging.Formatter(
            '%(asctime)s %(levelname)s %(module)s: %(message)s')
        hdlr.setFormatter(formatter)
        logger.addHandler(hdlr)

    bucket = args['mountpoint'].split('/')[-1]

    start_msg = """
Mounting HTTP Filesystem...
    bucket: {bucket}
    mountpoint: {mountpoint}
    foreground: {foreground}
""".format(bucket=bucket,
           mountpoint=args['mountpoint'],
           foreground=args['foreground'])
    print(start_msg, file=sys.stderr)

    fuse = FUSE(HttpFs(bucket,
                       disk_cache_size=args['disk_cache_size'],
                       disk_cache_dir=args['disk_cache_dir'],
                       lru_capacity=args['lru_capacity'],
                       block_size=args['block_size'],
                       aws_profile=args['aws_profile'],
                       logger=logger),
                args['mountpoint'],
                foreground=args['foreground'],
                attr_timeout=0.0,
                entry_timeout=0.0)