<commit_before># -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import, unicode_literals

import re
from functools import partial
from argparse import ArgumentParser, ArgumentTypeError, Action

from . import settings, meta
from .generators.swid_generator import software_id_matcher, package_name_matcher, all_matcher

class TargetAction(Action):
    def __call__(self, parser, namespace, value, option_string=None):
        if option_string == '--software-id':
            setattr(namespace, "matcher", partial(software_id_matcher, value=value))
        elif option_string == '--package':
            setattr(namespace, "matcher", partial(package_name_matcher, value=value))

def regid_string(string):
    if string is None:
        return None
    try:
        regex = re.compile(
            r'^(?:(?:http|ftp)s?://)?'
            r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|'
            r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'
            r'(?::\d+)?'
            r'(?:/?|[/?]\S+)$', re.IGNORECASE)
        return re.match(regex, string).group(0)
    except:
        raise ArgumentTypeError("String '{0}' does not match required format".format(string))

def hash_string(string):
    if string is None:
        return None
    try:
        return re.match(r'((^|,)(sha256|sha384|sha512))+$', string).group(0)
    except:
        raise ArgumentTypeError("String '{0}' does not match required format".format(string))

def entity_name_string(string):
    if string is None:
        return None
    try:
        return re.match('^[^<&"]*$', string).group(0)
    except:
        raise ArgumentTypeError("String '{0}' does not match required format".format(string))

def file_path(string):
    return string

class MainArgumentParser(object):
    def __init__(self, environment_registry):
        self.environments = environment_registry
        self.arg_parser = ArgumentParser('swid_generator',
                                         description='Generate SWID tags and Software IDs'
                                                     'from dpkg, pacman or rpm package manager')
        self.arg_parser.add_argument('-v', '--version', action='version',
                                     version='%(prog)s ' + meta.version)

        # Parent parser for common options
        parent_parser = ArgumentParser(add_help=False)

        parent_parser.add_argument('--env', choices=environment_registry.get_environment_strings(),
                                   default='auto',
                                   help='The package manager environment to be used. Defaults to "auto". '
                                        'If the environment can not be autodetected, '
                                        'the exit code is set to 3.')
        parent_parser.add_argument('--doc-separator', dest='document_separator', default='\n',
                                   help='The separator string by which the SWID XML '
                                        'documents are separated. Example: For '
                                        'one newline, use $\'\\n\'.')
        parent_parser.add_argument('--regid', dest='regid', type=regid_string,
                                   default=regid_string(settings.DEFAULT_REGID),
                                   help='The regid to use in the generated output. '
                                        'May not contain any whitespace '
                                        'characters. Default is "%s".' % settings.DEFAULT_REGID)

        subparsers = self.arg_parser.add_subparsers(help='Commands: ', dest='command')

        # Subparser for swid command
        swid_parser = subparsers.add_parser('swid', help='SWID tag output', parents=[parent_parser],
                                            description='Generate SWID tags.')

        swid_parser.add_argument('--entity-name', dest='entity_name', type=entity_name_string,
                                 default=entity_name_string(settings.DEFAULT_ENTITY_NAME),
                                 help='The entity name used in the <Entity> XML tag. '
                                      'Default is "%s".' % settings.DEFAULT_ENTITY_NAME)
        swid_parser.add_argument('--full', action='store_true', default=False,
                                 help='Dump the full SWID tags including file tags for each package.')
        swid_parser.add_argument('--pretty', action='store_true', default=False,
                                 help='Indent the XML output.')
        swid_parser.add_argument('--hash', dest='hash_algorithms', type=hash_string,
                            default=hash_string(settings.DEFAULT_HASH_ALGORITHM),
                            help='Define the algorithm for the file hashes ("sha256", "sha384", "sha512"). '
                                 'Multiple hashes can be added with comma separated. ("sha256,sha384") '
                                 'Default is "%s"' % settings.DEFAULT_HASH_ALGORITHM)
        swid_parser.add_argument('--package-file', dest='file_path', type=file_path,
                                 help='Create SWID-Tag based on information of a Package-File.'
                                 'Rpm-Environments: .rpm Package-Files, Dpkg-Environments: .deb '
                                 'Package-Files, Pacman-Environments: .pacman Package-Files')

        swid_parser.set_defaults(matcher=all_matcher)

        targeted_group = swid_parser.add_argument_group(
            title='targeted requests',
            description='You may do a targeted request against either a Software-ID or a package name. '
                        'The output only contains a SWID tag if the argument fully matches '
                        'the given target. If no matching SWID tag is found, the output is empty '
                        'and the exit code is set to 1. ')

        # mutually exclusive arguments --package/--software-id
        mutually_group = targeted_group.add_mutually_exclusive_group()
        mutually_group.add_argument('--software-id', dest='match_software_id', metavar='SOFTWARE-ID',
                            action=TargetAction,
                            help='Do a targeted request for the specified Software-ID. '
                                 'A Software-ID is made up as follows: "{regid}_{unique-id}". '
                                 'Example: '
                                 '"regid.2004-03.org.strongswan_Ubuntu_12.04-i686-strongswan-4.5.2-1.2". '
                                 'If no matching package is found, the output is empty and the '
                                 'exit code is set to 1.')
        mutually_group.add_argument('--package', dest='package_name', metavar='PACKAGE',
                                    action=TargetAction,
                                    help='Do a targeted request for the specified package name. '
                                         'The package name corresponds to a package name returned by the '
                                         'environment\'s package manager, e.g "glibc-headers" on a '
                                         'dpkg managed environment. '
                                         'If no matching package is found, the output is empty and the '
                                         'exit code is set to 1.')

        # Subparser for software-id command
        subparsers.add_parser('software-id', help='Software id output', parents=[parent_parser],
                              description='Generate Software-IDs.')

    def parse(self, arguments=None):
        return self.arg_parser.parse_args(arguments)

    def print_usage(self):
        self.arg_parser.print_usage()
<commit_msg>Check of file-path ending added; Only valid Packages can be passed as arguments<commit_after># -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import, unicode_literals

import re
from functools import partial
from argparse import ArgumentParser, ArgumentTypeError, Action

from . import settings, meta
from .generators.swid_generator import software_id_matcher, package_name_matcher, all_matcher

class TargetAction(Action):
    def __call__(self, parser, namespace, value, option_string=None):
        if option_string == '--software-id':
            setattr(namespace, "matcher", partial(software_id_matcher, value=value))
        elif option_string == '--package':
            setattr(namespace, "matcher", partial(package_name_matcher, value=value))

def regid_string(string):
    if string is None:
        return None
    try:
        regex = re.compile(
            r'^(?:(?:http|ftp)s?://)?'
            r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|'
            r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'
            r'(?::\d+)?'
            r'(?:/?|[/?]\S+)$', re.IGNORECASE)
        return re.match(regex, string).group(0)
    except:
        raise ArgumentTypeError("String '{0}' does not match required format".format(string))

def hash_string(string):
    if string is None:
        return None
    try:
        return re.match(r'((^|,)(sha256|sha384|sha512))+$', string).group(0)
    except:
        raise ArgumentTypeError("String '{0}' does not match required format".format(string))

def entity_name_string(string):
    if string is None:
        return None
    try:
        return re.match('^[^<&"]*$', string).group(0)
    except:
        raise ArgumentTypeError("String '{0}' does not match required format".format(string))

def file_path(string=None):
    if string.endswith('.deb') or string.endswith('.rpm') or string.endswith('.pkg.tar.xz'):
        return string
    else:
        raise ArgumentTypeError("File '{0}' is not a valid Package.".format(string))

class MainArgumentParser(object):
    def __init__(self, environment_registry):
        self.environments = environment_registry
        self.arg_parser = ArgumentParser('swid_generator',
                                         description='Generate SWID tags and Software IDs'
                                                     'from dpkg, pacman or rpm package manager')
        self.arg_parser.add_argument('-v', '--version', action='version',
                                     version='%(prog)s ' + meta.version)

        # Parent parser for common options
        parent_parser = ArgumentParser(add_help=False)

        parent_parser.add_argument('--env', choices=environment_registry.get_environment_strings(),
                                   default='auto',
                                   help='The package manager environment to be used. Defaults to "auto". '
                                        'If the environment can not be autodetected, '
                                        'the exit code is set to 3.')
        parent_parser.add_argument('--doc-separator', dest='document_separator', default='\n',
                                   help='The separator string by which the SWID XML '
                                        'documents are separated. Example: For '
                                        'one newline, use $\'\\n\'.')
        parent_parser.add_argument('--regid', dest='regid', type=regid_string,
                                   default=regid_string(settings.DEFAULT_REGID),
                                   help='The regid to use in the generated output. '
                                        'May not contain any whitespace '
                                        'characters. Default is "%s".' % settings.DEFAULT_REGID)

        subparsers = self.arg_parser.add_subparsers(help='Commands: ', dest='command')

        # Subparser for swid command
        swid_parser = subparsers.add_parser('swid', help='SWID tag output', parents=[parent_parser],
                                            description='Generate SWID tags.')

        swid_parser.add_argument('--entity-name', dest='entity_name', type=entity_name_string,
                                 default=entity_name_string(settings.DEFAULT_ENTITY_NAME),
                                 help='The entity name used in the <Entity> XML tag. '
                                      'Default is "%s".' % settings.DEFAULT_ENTITY_NAME)
        swid_parser.add_argument('--full', action='store_true', default=False,
                                 help='Dump the full SWID tags including file tags for each package.')
        swid_parser.add_argument('--pretty', action='store_true', default=False,
                                 help='Indent the XML output.')
        swid_parser.add_argument('--hash', dest='hash_algorithms', type=hash_string,
                            default=hash_string(settings.DEFAULT_HASH_ALGORITHM),
                            help='Define the algorithm for the file hashes ("sha256", "sha384", "sha512"). '
                                 'Multiple hashes can be added with comma separated. ("sha256,sha384") '
                                 'Default is "%s"' % settings.DEFAULT_HASH_ALGORITHM)
        swid_parser.add_argument('--package-file', dest='file_path', type=file_path,
                                 help='Create SWID-Tag based on information of a Package-File.'
                                 ' Rpm-Environment: *.rpm File, Dpkg-Environment: *.deb File, '
                                 'Pacman-Environment: *.pgk.tar.xz File')

        swid_parser.set_defaults(matcher=all_matcher)

        targeted_group = swid_parser.add_argument_group(
            title='targeted requests',
            description='You may do a targeted request against either a Software-ID or a package name. '
                        'The output only contains a SWID tag if the argument fully matches '
                        'the given target. If no matching SWID tag is found, the output is empty '
                        'and the exit code is set to 1. ')

        # mutually exclusive arguments --package/--software-id
        mutually_group = targeted_group.add_mutually_exclusive_group()
        mutually_group.add_argument('--software-id', dest='match_software_id', metavar='SOFTWARE-ID',
                            action=TargetAction,
                            help='Do a targeted request for the specified Software-ID. '
                                 'A Software-ID is made up as follows: "{regid}_{unique-id}". '
                                 'Example: '
                                 '"regid.2004-03.org.strongswan_Ubuntu_12.04-i686-strongswan-4.5.2-1.2". '
                                 'If no matching package is found, the output is empty and the '
                                 'exit code is set to 1.')
        mutually_group.add_argument('--package', dest='package_name', metavar='PACKAGE',
                                    action=TargetAction,
                                    help='Do a targeted request for the specified package name. '
                                         'The package name corresponds to a package name returned by the '
                                         'environment\'s package manager, e.g "glibc-headers" on a '
                                         'dpkg managed environment. '
                                         'If no matching package is found, the output is empty and the '
                                         'exit code is set to 1.')

        # Subparser for software-id command
        subparsers.add_parser('software-id', help='Software id output', parents=[parent_parser],
                              description='Generate Software-IDs.')

    def parse(self, arguments=None):
        return self.arg_parser.parse_args(arguments)

    def print_usage(self):
        self.arg_parser.print_usage()
<|endoftext|>


<commit_before>"""

fs.remote
=========

Utilities for interfacing with remote filesystems

This module provides reusable utility functions that can be used to construct
FS subclasses interfacing with a remote filesystem.  These include:

  * RemoteFileBuffer:  a file-like object that locally buffers the contents of
                       a remote file, writing them back on flush() or close().

  * ConnectionManagerFS:  a WrapFS subclass that tracks the connection state
                          of a remote FS, and allows client code to wait for
                          a connection to be re-established.

   * CacheFS:  a WrapFS subclass that caches file and directory meta-data in
               memory, to speed access to a remote FS.

"""

import time
import copy

from fs.base import FS, threading
from fs.wrapfs import WrapFS, wrap_fs_methods
from fs.wrapfs.lazyfs import LazyFS
from fs.path import *
from fs.errors import *
from fs.local_functools import wraps

try:
   from tempfile import SpooledTemporaryFile
except ImportError:
   from tempfile import NamedTemporaryFile
   class SpooledTemporaryFile(NamedTemporaryFile):
        def __init__(self,max_size=0,*args,**kwds):
            NamedTemporaryFile.__init__(self,*args,**kwds)

class RemoteFileBuffer(object):
    """File-like object providing buffer for local file operations.

    Instances of this class manage a local tempfile buffer corresponding
    to the contents of a remote file.  All reads and writes happen locally,
    with the content being copied to the remote file only on flush() or
    close().  Writes to the remote file are performed using the setcontents()
    method on the owning FS object.

    The intended use-case is for a remote filesystem (e.g. S3FS) to return
    instances of this class from its open() method, and to provide the
    file-uploading logic in its setcontents() method, as in the following
    pseudo-code::

        def open(self,path,mode="r"):
            rf = self._get_remote_file(path)
            return RemoteFileBuffer(self,path,mode,rf)

        def setcontents(self,path,file):
            self._put_remote_file(path,file)

    The current implementation reads the entire contents of the file into
    the buffer before returning.  Future implementations may pull data into
    the buffer on demand.
    """

    max_size_in_memory = 1024 * 8

    def __init__(self,fs,path,mode,rfile=None):
        """RemoteFileBuffer constructor.

        The owning filesystem, path and mode must be provided.  If the
        optional argument 'rfile' is provided, it must be a read()-able
        object or a string containing the initial file contents.
        """
        self.file = SpooledTemporaryFile(max_size=self.max_size_in_memory)
        self.fs = fs
        self.path = path
        self.mode = mode
        self.closed = False
        self._flushed = False
        if getattr(fs,"_lock",None) is not None:
            self._lock = fs._lock.__class__()
        else:
            self._lock = threading.RLock()
        if "r" in mode or "+" in mode or "a" in mode:
            if rfile is not None:
                if hasattr(rfile,"read"):
                    data = rfile.read(1024*256)
                    while data:
                        self.file.write(data)
                        data = rfile.read(1024*256)
                else:
                    self.file.write(str(rfile))
                if "a" not in mode:
                    self.file.seek(0)

    def __del__(self):
        #  Don't try to close a partially-constructed file
        if "_lock" in self.__dict__:
            if not self.closed:
                self.close()

    def __getattr__(self,name):
        if name in ("file","_lock","fs","path","mode","closed","_flushed"):
            raise AttributeError(name)
        file = self.__dict__['file']
        a = getattr(file, name)
        if not callable(a):
            return a
        @wraps(a)
        def call_with_lock(*args,**kwds):
            self._lock.acquire()
            try:
                if "write" in name:
                    self._flushed = False
                return a(*args,**kwds)
            finally:
                self._lock.release()
        setattr(self, name, call_with_lock)
        return call_with_lock

    def __enter__(self):
        self.file.__enter__()
        return self

    def __exit__(self,exc,value,tb):
        self.close()
        return False

    def __iter__(self):
        return iter(self.file)

    def truncate(self,size=None):
        self._lock.acquire()
        try:
            if isinstance(self.file,SpooledTemporaryFile):
                #  SpooledTemporaryFile.truncate doesn't accept size argument.
                if size is None:
                    self.file._file.truncate()
                else:
                    self.file._file.truncate(size)
            else:
                self.file.truncate(size)
            self.flush()
        finally:
            self._lock.release()

    def flush(self):
        self._lock.acquire()
        try:
            self.file.flush()
            if "w" in self.mode or "a" in self.mode or "+" in self.mode:
                if not self._flushed:
                    pos = self.file.tell()
                    self.file.seek(0)
                    self.fs.setcontents(self.path,self.file)
                    self.file.seek(pos)
                    self._flushed = True
        finally:
            self._lock.release()

    def close(self):
        self._lock.acquire()
        try:
            if not self.closed:
                self.closed = True
                if "w" in self.mode or "a" in self.mode or "+" in self.mode:
                    if not self._flushed:
                        self.file.seek(0)
                        self.file.seek(0)
                        self.fs.setcontents(self.path,self.file)
                self.file.close()
        finally:
            self._lock.release()

class ConnectionManagerFS(LazyFS):
    """FS wrapper providing simple connection management of a remote FS.

    The ConnectionManagerFS class is designed to wrap a remote FS object
    and provide some convenience methods for dealing with its remote
    connection state.

    The boolean attribute 'connected' indicates whether the remote fileystem
    has an active connection, and is initially True.  If any of the remote
    filesystem methods raises a RemoteConnectionError, 'connected' will
    switch to False and remain so until a successful remote method call.

    Application code can use the method 'wait_for_connection' to block
    until the connection is re-established.  Currently this reconnection
    is checked by a simple polling loop; eventually more sophisticated
    operating-system integration may be added.

    Since some remote FS classes can raise RemoteConnectionError during
    initialisation, this class makes use of lazy initialization. The
    remote FS can be specified as an FS instance, an FS subclass, or a
    (class,args) or (class,args,kwds) tuple. For example::

        >>> fs = ConnectionManagerFS(MyRemoteFS("http://www.example.com/"))
        Traceback (most recent call last):
            ...
        RemoteConnectionError: couldn't connect to "http://www.example.com/"
        >>> fs = ConnectionManagerFS((MyRemoteFS,["http://www.example.com/"]))
        >>> fs.connected
        False
        >>>

    """

    poll_interval = 1

    def __init__(self,wrapped_fs,poll_interval=None,connected=True):
        super(ConnectionManagerFS,self).__init__(wrapped_fs)
        if poll_interval is not None:
            self.poll_interval = poll_interval
        self._connection_cond = threading.Condition()
        self._poll_thread = None
        self._poll_sleeper = threading.Event()
        self.connected = connected

    def setcontents(self,path,data):
        return self.wrapped_fs.setcontents(path,data)

    def __getstate__(self):
        state = super(ConnectionManagerFS,self).__getstate__()
        del state["_connection_cond"]
        del state["_poll_sleeper"]
        state["_poll_thread"] = None
        return state

    def __setstate__(self,state):
        super(ConnectionManagerFS,self).__setstate__(state)
        self._connection_cond = threading.Condition()
        self._poll_sleeper = threading.Event()

    def wait_for_connection(self,timeout=None):
        self._connection_cond.acquire()
        try:
            if not self.connected:
                if not self._poll_thread:
                    target = self._poll_connection
                    self._poll_thread = threading.Thread(target=target)
                    self._poll_thread.start()
                self._connection_cond.wait(timeout)
        finally:
            self._connection_cond.release()

    def _poll_connection(self):
        while not self.connected and not self.closed:
            try:
                self.wrapped_fs.isdir("")
            except RemoteConnectionError:
                self._poll_sleeper.wait(self.poll_interval)
                self._poll_sleeper.clear()
            except FSError:
                break
            else:
                break
        self._connection_cond.acquire()
        try:
            if not self.closed:
                self.connected = True
            self._poll_thread = None
            self._connection_cond.notifyAll()
        finally:
            self._connection_cond.release()

    def close(self):
        if not self.closed:
            try:
                super(ConnectionManagerFS,self).close()
            except (RemoteConnectionError,):
                pass
            if self._poll_thread:
                self.connected = True
                self._poll_sleeper.set()
                self._poll_thread.join()
                self._poll_thread = None

def _ConnectionManagerFS_method_wrapper(func):
    """Method wrapper for ConnectionManagerFS.

    This method wrapper keeps an eye out for RemoteConnectionErrors and
    adjusts self.connected accordingly.
    """
    @wraps(func)
    def wrapper(self,*args,**kwds):
        try:
            result = func(self,*args,**kwds)
        except RemoteConnectionError:
            self.connected = False
            raise
        except FSError:
            self.connected = True
            raise
        else:
            self.connected = True
            return result
    return wrapper

wrap_fs_methods(_ConnectionManagerFS_method_wrapper,ConnectionManagerFS)

def _cached_method(func):
    """Method decorator that caches results for CacheFS."""
    @wraps(func)
    def wrapper(self,path="",*args,**kwds):
        try:
            (success,result) = self._cache_get(path,func.__name__,args,kwds)
        except KeyError:
            try:
                res = func(self,path,*args,**kwds)
            except Exception, e:
                self._cache_set(path,func.__name__,args,kwds,(False,e))
                raise
            else:
                self._cache_set(path,func.__name__,args,kwds,(True,res))
                return copy.copy(res)
        else:
            if not success:
                raise result
            else:
                return copy.copy(result)
    return wrapper

class CacheFS(WrapFS):
    """Simple wrapper to cache meta-data of a remote filesystems.

    This FS wrapper implements a simplistic cache that can help speed up
    access to a remote filesystem.  File and directory meta-data is cached
    but the actual file contents are not.
    """

    def __init__(self,fs,timeout=1):
        """CacheFS constructor.

        The optional argument 'timeout' specifies the cache timeout in
        seconds.  The default timeout is 1 second.  To prevent cache
        entries from ever timing out, set it to None.
        """
        self.timeout = timeout
        self._cache = {"":{}}
        super(CacheFS,self).__init__(fs)

    def _path_cache(self,path):
        cache = self._cache
        for name in iteratepath(path):
            cache = cache.setdefault(name,{"":{}})
        return cache

    def _cache_get(self,path,func,args,kwds):
        now = time.time()
        cache = self._path_cache(path)
        key = (tuple(args),tuple(sorted(kwds.iteritems())))
        (t,v) = cache[""][func][key]
        if self.timeout is not None:
            if t < now - self.timeout:
                raise KeyError
        return v

    def _cache_set(self,path,func,args,kwds,v):
        t = time.time()
        cache = self._path_cache(path)
        key = (tuple(args),tuple(sorted(kwds.iteritems())))
        cache[""].setdefault(func,{})[key] = (t,v)

    def _uncache(self,path,added=False,removed=False,unmoved=False):
        cache = self._cache
        names = list(iteratepath(path))
        # If it's not the root dir, also clear some items for ancestors
        if names:
            # Clear cached 'getinfo' and 'getsize' for all ancestors
            for name in names[:-1]:
                cache[""].pop("getinfo",None)
                cache[""].pop("getsize",None)
                cache = cache.get(name,None)
                if cache is None:
                    return
            # Adjust cached 'listdir' for parent directory.
            # TODO: account for whether it was added, removed, or unmoved
            cache[""].pop("getinfo",None)
            cache[""].pop("getsize",None)
            cache[""].pop("listdir",None)
        # Clear all cached info for the path itself.
        cache[names[-1]] = {"":{}}

    @_cached_method
    def exists(self,path):
        return super(CacheFS,self).exists(path)

    @_cached_method
    def isdir(self,path):
        return super(CacheFS,self).isdir(path)

    @_cached_method
    def isfile(self,path):
        return super(CacheFS,self).isfile(path)

    @_cached_method
    def listdir(self,path="",**kwds):
        return super(CacheFS,self).listdir(path,**kwds)

    @_cached_method
    def getinfo(self,path):
        return super(CacheFS,self).getinfo(path)

    @_cached_method
    def getsize(self,path):
        return super(CacheFS,self).getsize(path)

    @_cached_method
    def getxattr(self,path,name,default=None):
        return super(CacheFS,self).getxattr(path,name,default)

    @_cached_method
    def listxattrs(self,path):
        return super(CacheFS,self).listxattrs(path)

    def open(self,path,mode="r"):
        f = super(CacheFS,self).open(path,mode)
        self._uncache(path,unmoved=True)
        return f

    def setcontents(self,path,contents):
        res = super(CacheFS,self).setcontents(path,contents)
        self._uncache(path,unmoved=True)
        return res

    def getcontents(self,path):
        res = super(CacheFS,self).getcontents(path)
        self._uncache(path,unmoved=True)
        return res

    def makedir(self,path,**kwds):
        super(CacheFS,self).makedir(path,**kwds)
        self._uncache(path,added=True)

    def remove(self,path):
        super(CacheFS,self).remove(path)
        self._uncache(path,removed=True)

    def removedir(self,path,**kwds):
        super(CacheFS,self).removedir(path,**kwds)
        self._uncache(path,removed=True)

    def rename(self,src,dst):
        super(CacheFS,self).rename(src,dst)
        self._uncache(src,removed=True)
        self._uncache(dst,added=True)

    def copy(self,src,dst,**kwds):
        super(CacheFS,self).copy(src,dst,**kwds)
        self._uncache(dst,added=True)

    def copydir(self,src,dst,**kwds):
        super(CacheFS,self).copydir(src,dst,**kwds)
        self._uncache(dst,added=True)

    def move(self,src,dst,**kwds):
        super(CacheFS,self).move(src,dst,**kwds)
        self._uncache(src,removed=True)
        self._uncache(dst,added=True)

    def movedir(self,src,dst,**kwds):
        super(CacheFS,self).movedir(src,dst,**kwds)
        self._uncache(src,removed=True)
        self._uncache(dst,added=True)

    def setxattr(self,path,name,value):
        self._uncache(path,unmoved=True)
        return super(CacheFS,self).setxattr(path,name,value)

    def delxattr(self,path,name):
        self._uncache(path,unmoved=True)
        return super(CacheFS,self).delxattr(path,name)

<commit_msg>workaround seek() bug in SpooledTemporaryFile<commit_after>"""

fs.remote
=========

Utilities for interfacing with remote filesystems

This module provides reusable utility functions that can be used to construct
FS subclasses interfacing with a remote filesystem.  These include:

  * RemoteFileBuffer:  a file-like object that locally buffers the contents of
                       a remote file, writing them back on flush() or close().

  * ConnectionManagerFS:  a WrapFS subclass that tracks the connection state
                          of a remote FS, and allows client code to wait for
                          a connection to be re-established.

   * CacheFS:  a WrapFS subclass that caches file and directory meta-data in
               memory, to speed access to a remote FS.

"""

import os
import time
import copy

from fs.base import FS, threading
from fs.wrapfs import WrapFS, wrap_fs_methods
from fs.wrapfs.lazyfs import LazyFS
from fs.path import *
from fs.errors import *
from fs.local_functools import wraps

try:
   from tempfile import SpooledTemporaryFile
except ImportError:
   from tempfile import NamedTemporaryFile
   class SpooledTemporaryFile(NamedTemporaryFile):
        def __init__(self,max_size=0,*args,**kwds):
            NamedTemporaryFile.__init__(self,*args,**kwds)

class RemoteFileBuffer(object):
    """File-like object providing buffer for local file operations.

    Instances of this class manage a local tempfile buffer corresponding
    to the contents of a remote file.  All reads and writes happen locally,
    with the content being copied to the remote file only on flush() or
    close().  Writes to the remote file are performed using the setcontents()
    method on the owning FS object.

    The intended use-case is for a remote filesystem (e.g. S3FS) to return
    instances of this class from its open() method, and to provide the
    file-uploading logic in its setcontents() method, as in the following
    pseudo-code::

        def open(self,path,mode="r"):
            rf = self._get_remote_file(path)
            return RemoteFileBuffer(self,path,mode,rf)

        def setcontents(self,path,file):
            self._put_remote_file(path,file)

    The current implementation reads the entire contents of the file into
    the buffer before returning.  Future implementations may pull data into
    the buffer on demand.
    """

    max_size_in_memory = 1024 * 8

    def __init__(self,fs,path,mode,rfile=None):
        """RemoteFileBuffer constructor.

        The owning filesystem, path and mode must be provided.  If the
        optional argument 'rfile' is provided, it must be a read()-able
        object or a string containing the initial file contents.
        """
        self.file = SpooledTemporaryFile(max_size=self.max_size_in_memory)
        self.fs = fs
        self.path = path
        self.mode = mode
        self.closed = False
        self._flushed = False
        if getattr(fs,"_lock",None) is not None:
            self._lock = fs._lock.__class__()
        else:
            self._lock = threading.RLock()
        if "r" in mode or "+" in mode or "a" in mode:
            if rfile is not None:
                if hasattr(rfile,"read"):
                    data = rfile.read(1024*256)
                    while data:
                        self.file.write(data)
                        data = rfile.read(1024*256)
                else:
                    self.file.write(str(rfile))
                if "a" not in mode:
                    self.file.seek(0)

    def __del__(self):
        #  Don't try to close a partially-constructed file
        if "_lock" in self.__dict__:
            if not self.closed:
                self.close()

    def __getattr__(self,name):
        if name in ("file","_lock","fs","path","mode","closed","_flushed"):
            raise AttributeError(name)
        file = self.__dict__['file']
        a = getattr(file, name)
        if not callable(a):
            return a
        @wraps(a)
        def call_with_lock(*args,**kwds):
            self._lock.acquire()
            try:
                if "write" in name:
                    self._flushed = False
                return a(*args,**kwds)
            finally:
                self._lock.release()
        setattr(self, name, call_with_lock)
        return call_with_lock

    def __enter__(self):
        self.file.__enter__()
        return self

    def __exit__(self,exc,value,tb):
        self.close()
        return False

    def __iter__(self):
        return iter(self.file)

    def seek(self,offset,whence=os.SEEK_SET):
        if isinstance(self.file,SpooledTemporaryFile):
            #  SpooledTemporaryFile.seek doesn't roll to disk if seeking
            #  beyond the max in-memory size.
            if whence == os.SEEK_SET:
                if offset > self.file._max_size:
                    self.file.rollover()
            elif whence == os.SEEK_CUR:
                if offset + self.file.tell() > self.file._max_size:
                    self.file.rollover()
            else:
                if offset > 0:
                    self.file.rollover()
        self.file.seek(offset,whence)

    def truncate(self,size=None):
        self._lock.acquire()
        try:
            if isinstance(self.file,SpooledTemporaryFile):
                #  SpooledTemporaryFile.truncate doesn't accept size argument.
                if size is None:
                    self.file._file.truncate()
                else:
                    self.file._file.truncate(size)
            else:
                self.file.truncate(size)
            self.flush()
        finally:
            self._lock.release()

    def flush(self):
        self._lock.acquire()
        try:
            self.file.flush()
            if "w" in self.mode or "a" in self.mode or "+" in self.mode:
                if not self._flushed:
                    pos = self.file.tell()
                    self.file.seek(0)
                    self.fs.setcontents(self.path,self.file)
                    self.file.seek(pos)
                    self._flushed = True
        finally:
            self._lock.release()

    def close(self):
        self._lock.acquire()
        try:
            if not self.closed:
                self.closed = True
                if "w" in self.mode or "a" in self.mode or "+" in self.mode:
                    if not self._flushed:
                        self.file.seek(0)
                        self.file.seek(0)
                        self.fs.setcontents(self.path,self.file)
                self.file.close()
        finally:
            self._lock.release()

class ConnectionManagerFS(LazyFS):
    """FS wrapper providing simple connection management of a remote FS.

    The ConnectionManagerFS class is designed to wrap a remote FS object
    and provide some convenience methods for dealing with its remote
    connection state.

    The boolean attribute 'connected' indicates whether the remote fileystem
    has an active connection, and is initially True.  If any of the remote
    filesystem methods raises a RemoteConnectionError, 'connected' will
    switch to False and remain so until a successful remote method call.

    Application code can use the method 'wait_for_connection' to block
    until the connection is re-established.  Currently this reconnection
    is checked by a simple polling loop; eventually more sophisticated
    operating-system integration may be added.

    Since some remote FS classes can raise RemoteConnectionError during
    initialisation, this class makes use of lazy initialization. The
    remote FS can be specified as an FS instance, an FS subclass, or a
    (class,args) or (class,args,kwds) tuple. For example::

        >>> fs = ConnectionManagerFS(MyRemoteFS("http://www.example.com/"))
        Traceback (most recent call last):
            ...
        RemoteConnectionError: couldn't connect to "http://www.example.com/"
        >>> fs = ConnectionManagerFS((MyRemoteFS,["http://www.example.com/"]))
        >>> fs.connected
        False
        >>>

    """

    poll_interval = 1

    def __init__(self,wrapped_fs,poll_interval=None,connected=True):
        super(ConnectionManagerFS,self).__init__(wrapped_fs)
        if poll_interval is not None:
            self.poll_interval = poll_interval
        self._connection_cond = threading.Condition()
        self._poll_thread = None
        self._poll_sleeper = threading.Event()
        self.connected = connected

    def setcontents(self,path,data):
        return self.wrapped_fs.setcontents(path,data)

    def __getstate__(self):
        state = super(ConnectionManagerFS,self).__getstate__()
        del state["_connection_cond"]
        del state["_poll_sleeper"]
        state["_poll_thread"] = None
        return state

    def __setstate__(self,state):
        super(ConnectionManagerFS,self).__setstate__(state)
        self._connection_cond = threading.Condition()
        self._poll_sleeper = threading.Event()

    def wait_for_connection(self,timeout=None):
        self._connection_cond.acquire()
        try:
            if not self.connected:
                if not self._poll_thread:
                    target = self._poll_connection
                    self._poll_thread = threading.Thread(target=target)
                    self._poll_thread.start()
                self._connection_cond.wait(timeout)
        finally:
            self._connection_cond.release()

    def _poll_connection(self):
        while not self.connected and not self.closed:
            try:
                self.wrapped_fs.isdir("")
            except RemoteConnectionError:
                self._poll_sleeper.wait(self.poll_interval)
                self._poll_sleeper.clear()
            except FSError:
                break
            else:
                break
        self._connection_cond.acquire()
        try:
            if not self.closed:
                self.connected = True
            self._poll_thread = None
            self._connection_cond.notifyAll()
        finally:
            self._connection_cond.release()

    def close(self):
        if not self.closed:
            try:
                super(ConnectionManagerFS,self).close()
            except (RemoteConnectionError,):
                pass
            if self._poll_thread:
                self.connected = True
                self._poll_sleeper.set()
                self._poll_thread.join()
                self._poll_thread = None

def _ConnectionManagerFS_method_wrapper(func):
    """Method wrapper for ConnectionManagerFS.

    This method wrapper keeps an eye out for RemoteConnectionErrors and
    adjusts self.connected accordingly.
    """
    @wraps(func)
    def wrapper(self,*args,**kwds):
        try:
            result = func(self,*args,**kwds)
        except RemoteConnectionError:
            self.connected = False
            raise
        except FSError:
            self.connected = True
            raise
        else:
            self.connected = True
            return result
    return wrapper

wrap_fs_methods(_ConnectionManagerFS_method_wrapper,ConnectionManagerFS)

def _cached_method(func):
    """Method decorator that caches results for CacheFS."""
    @wraps(func)
    def wrapper(self,path="",*args,**kwds):
        try:
            (success,result) = self._cache_get(path,func.__name__,args,kwds)
        except KeyError:
            try:
                res = func(self,path,*args,**kwds)
            except Exception, e:
                self._cache_set(path,func.__name__,args,kwds,(False,e))
                raise
            else:
                self._cache_set(path,func.__name__,args,kwds,(True,res))
                return copy.copy(res)
        else:
            if not success:
                raise result
            else:
                return copy.copy(result)
    return wrapper

class CacheFS(WrapFS):
    """Simple wrapper to cache meta-data of a remote filesystems.

    This FS wrapper implements a simplistic cache that can help speed up
    access to a remote filesystem.  File and directory meta-data is cached
    but the actual file contents are not.
    """

    def __init__(self,fs,timeout=1):
        """CacheFS constructor.

        The optional argument 'timeout' specifies the cache timeout in
        seconds.  The default timeout is 1 second.  To prevent cache
        entries from ever timing out, set it to None.
        """
        self.timeout = timeout
        self._cache = {"":{}}
        super(CacheFS,self).__init__(fs)

    def _path_cache(self,path):
        cache = self._cache
        for name in iteratepath(path):
            cache = cache.setdefault(name,{"":{}})
        return cache

    def _cache_get(self,path,func,args,kwds):
        now = time.time()
        cache = self._path_cache(path)
        key = (tuple(args),tuple(sorted(kwds.iteritems())))
        (t,v) = cache[""][func][key]
        if self.timeout is not None:
            if t < now - self.timeout:
                raise KeyError
        return v

    def _cache_set(self,path,func,args,kwds,v):
        t = time.time()
        cache = self._path_cache(path)
        key = (tuple(args),tuple(sorted(kwds.iteritems())))
        cache[""].setdefault(func,{})[key] = (t,v)

    def _uncache(self,path,added=False,removed=False,unmoved=False):
        cache = self._cache
        names = list(iteratepath(path))
        # If it's not the root dir, also clear some items for ancestors
        if names:
            # Clear cached 'getinfo' and 'getsize' for all ancestors
            for name in names[:-1]:
                cache[""].pop("getinfo",None)
                cache[""].pop("getsize",None)
                cache = cache.get(name,None)
                if cache is None:
                    return
            # Adjust cached 'listdir' for parent directory.
            # TODO: account for whether it was added, removed, or unmoved
            cache[""].pop("getinfo",None)
            cache[""].pop("getsize",None)
            cache[""].pop("listdir",None)
        # Clear all cached info for the path itself.
        cache[names[-1]] = {"":{}}

    @_cached_method
    def exists(self,path):
        return super(CacheFS,self).exists(path)

    @_cached_method
    def isdir(self,path):
        return super(CacheFS,self).isdir(path)

    @_cached_method
    def isfile(self,path):
        return super(CacheFS,self).isfile(path)

    @_cached_method
    def listdir(self,path="",**kwds):
        return super(CacheFS,self).listdir(path,**kwds)

    @_cached_method
    def getinfo(self,path):
        return super(CacheFS,self).getinfo(path)

    @_cached_method
    def getsize(self,path):
        return super(CacheFS,self).getsize(path)

    @_cached_method
    def getxattr(self,path,name,default=None):
        return super(CacheFS,self).getxattr(path,name,default)

    @_cached_method
    def listxattrs(self,path):
        return super(CacheFS,self).listxattrs(path)

    def open(self,path,mode="r"):
        f = super(CacheFS,self).open(path,mode)
        self._uncache(path,unmoved=True)
        return f

    def setcontents(self,path,contents):
        res = super(CacheFS,self).setcontents(path,contents)
        self._uncache(path,unmoved=True)
        return res

    def getcontents(self,path):
        res = super(CacheFS,self).getcontents(path)
        self._uncache(path,unmoved=True)
        return res

    def makedir(self,path,**kwds):
        super(CacheFS,self).makedir(path,**kwds)
        self._uncache(path,added=True)

    def remove(self,path):
        super(CacheFS,self).remove(path)
        self._uncache(path,removed=True)

    def removedir(self,path,**kwds):
        super(CacheFS,self).removedir(path,**kwds)
        self._uncache(path,removed=True)

    def rename(self,src,dst):
        super(CacheFS,self).rename(src,dst)
        self._uncache(src,removed=True)
        self._uncache(dst,added=True)

    def copy(self,src,dst,**kwds):
        super(CacheFS,self).copy(src,dst,**kwds)
        self._uncache(dst,added=True)

    def copydir(self,src,dst,**kwds):
        super(CacheFS,self).copydir(src,dst,**kwds)
        self._uncache(dst,added=True)

    def move(self,src,dst,**kwds):
        super(CacheFS,self).move(src,dst,**kwds)
        self._uncache(src,removed=True)
        self._uncache(dst,added=True)

    def movedir(self,src,dst,**kwds):
        super(CacheFS,self).movedir(src,dst,**kwds)
        self._uncache(src,removed=True)
        self._uncache(dst,added=True)

    def setxattr(self,path,name,value):
        self._uncache(path,unmoved=True)
        return super(CacheFS,self).setxattr(path,name,value)

    def delxattr(self,path,name):
        self._uncache(path,unmoved=True)
        return super(CacheFS,self).delxattr(path,name)

<|endoftext|>


<commit_before>import logging

import elasticutils
from celeryutils import task

log = logging.getLogger('elasticutils')

@task
def index_objects(model, ids, **kw):
    """Models can asynchronously update their ES index.

    If a model extends SearchMixin, it can add a post_save hook like so::

        @receiver(dbsignals.post_save, sender=MyModel)
        def update_search_index(sender, instance, **kw):
            from elasticutils import tasks
            tasks.index_objects.delay(sender, [instance.id])

    """
    es = elasticutils.get_es()
    log.info('Indexing objects %s-%s. [%s]' % (ids[0], ids[-1], len(ids)))
    qs = model.objects.filter(id__in=ids)
    for item in qs:
        model.index(item.fields(), bulk=True, id=item.id)
    es.flush_bulk(forced=True)
<commit_msg>Remove<commit_after>import logging

import elasticutils
from celeryutils import task

log = logging.getLogger('elasticutils')

@task
def index_objects(model, ids, **kw):
    """Models can asynchronously update their ES index.

    If a model extends SearchMixin, it can add a post_save hook like so::

        @receiver(dbsignals.post_save, sender=MyModel)
        def update_search_index(sender, instance, **kw):
            from elasticutils import tasks
            tasks.index_objects.delay(sender, [instance.id])

    """
    es = elasticutils.get_es()
    log.info('Indexing objects %s-%s. [%s]' % (ids[0], ids[-1], len(ids)))
    qs = model.objects.filter(id__in=ids)
    for item in qs:
        model.index(item.fields(), bulk=True, id=item.id)
    es.flush_bulk(forced=True)

@task
def unindex_objects(model, ids, **kw):
    for id in ids:
        log.info('Removing object [%s.%d] from search index.' % (model, id))
        elasticutils.get_es().delete(model._get_index(), model._meta.db_table, id)
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import, unicode_literals

import subprocess

from .common import CommonEnvironment
from ..package_info import PackageInfo, FileInfo

class PacmanEnvironment(CommonEnvironment):
    """
    Environment class for distributions using pacman as package manager (used
    by Arch Linux).

    """
    executable = 'pacman'

    @classmethod
    def get_package_list(cls):
        """
        Get list of installed packages.

        Returns:
            List of ``PackageInfo`` instances.

        """

        command_args = [cls.executable, '-Q', '--color', 'never']
        data = subprocess.check_output(command_args)
        if isinstance(data, bytes):
            data = data.decode('utf-8')
        lines = filter(None, data.rstrip().split('\n'))
        result = []
        for line in lines:
            split_line = line.split()
            assert len(split_line) == 2, repr(split_line)
            info = PackageInfo()
            info.package = split_line[0]
            info.version = split_line[1]
            result.append(info)
        return result

    @classmethod
    def get_files_for_package(cls, package_info):
        """
        Get list of files related to the specified package.

        Caching could be implemented by using `Ql` without any package name.

        Args:
            package_name (str):
                The package name as string (e.g. ``cowsay``).

        Returns:
            List of ``FileInfo`` instances.

        """
        command_args = [cls.executable, '-Ql', package_info.package]
        data = subprocess.check_output(command_args)
        if isinstance(data, bytes):
            data = data.decode('utf-8')
        lines = filter(None, data.rstrip().split('\n'))
        result = []
        for line in lines:
            split_line = line.split(' ', 1)
            assert len(split_line) == 2, repr(split_line)
            file_path = split_line[1]
            if cls._is_file(file_path):
                file_info = FileInfo(file_path)
                # With the assumption that files in the '/etc'-Folders are mostly Configuration-Files
                if "/etc" in file_path:
                    file_info.mutable = True
                result.append(file_info)
        return result

    @classmethod
    def get_files_from_packagefile(cls, file_fullpathname):

        command_args = [cls.executable, '-Qlp', file_fullpathname]
        data = subprocess.check_output(command_args)
        if isinstance(data, bytes):
            data = data.decode('utf-8')

        save_options = cls._create_temp_folder(file_fullpathname)
        lines = data.split('\n')

        lines = filter(lambda l: len(l) > 0, lines)

        for line in lines:
            split_line = line.split(' ')

        return []

    @classmethod
    def get_packageinfo_from_packagefile(cls, file_path):
        command_args = [cls.executable, '--query', '--file', file_path]
        data = subprocess.check_output(command_args)
        if isinstance(data, bytes):
            data = data.decode('utf-8')

        line_split = data.split(' ')

        package_info = PackageInfo()
        package_info.package = line_split[0]
        package_info.version = line_split[1].rstrip()

        return package_info
<commit_msg>Pacman-Environment get_files_from_packagefile-Method finished<commit_after># -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import, unicode_literals

import subprocess

from .common import CommonEnvironment
from ..package_info import PackageInfo, FileInfo

class PacmanEnvironment(CommonEnvironment):
    """
    Environment class for distributions using pacman as package manager (used
    by Arch Linux).

    """
    executable = 'pacman'

    @classmethod
    def get_package_list(cls):
        """
        Get list of installed packages.

        Returns:
            List of ``PackageInfo`` instances.

        """

        command_args = [cls.executable, '-Q', '--color', 'never']
        data = subprocess.check_output(command_args)
        if isinstance(data, bytes):
            data = data.decode('utf-8')
        lines = filter(None, data.rstrip().split('\n'))
        result = []
        for line in lines:
            split_line = line.split()
            assert len(split_line) == 2, repr(split_line)
            info = PackageInfo()
            info.package = split_line[0]
            info.version = split_line[1]
            result.append(info)
        return result

    @classmethod
    def get_files_for_package(cls, package_info):
        """
        Get list of files related to the specified package.

        Caching could be implemented by using `Ql` without any package name.

        Args:
            package_name (str):
                The package name as string (e.g. ``cowsay``).

        Returns:
            List of ``FileInfo`` instances.

        """
        command_args = [cls.executable, '-Ql', package_info.package]
        data = subprocess.check_output(command_args)
        if isinstance(data, bytes):
            data = data.decode('utf-8')
        lines = filter(None, data.rstrip().split('\n'))
        result = []
        for line in lines:
            split_line = line.split(' ', 1)
            assert len(split_line) == 2, repr(split_line)
            file_path = split_line[1]
            if cls._is_file(file_path):
                file_info = FileInfo(file_path)
                # With the assumption that files in the '/etc'-Folders are mostly Configuration-Files
                if "/etc" in file_path:
                    file_info.mutable = True
                result.append(file_info)
        return result

    @classmethod
    def get_files_from_packagefile(cls, file_fullpathname):

        command_args = [cls.executable, '-Qlp', file_fullpathname]
        data = subprocess.check_output(command_args)
        if isinstance(data, bytes):
            data = data.decode('utf-8')

        save_options = cls._create_temp_folder(file_fullpathname)
        lines = data.split('\n')
        all_files = []
        lines = filter(lambda l: len(l) > 0, lines)

        subprocess.call(["tar", "-xf", save_options['absolute_package_path']], cwd=save_options[
            'save_location'])

        for line in lines:
            path = line.split(' ')[1]
            temporary_path = save_options['save_location'] + path
            if cls._is_file(temporary_path):
                file_info = FileInfo(path, actual_path=False)
                file_info.set_actual_path(temporary_path)
                if 'etc' in path:
                    file_info.mutable = True
                all_files.append(file_info)

        return all_files

    @classmethod
    def get_packageinfo_from_packagefile(cls, file_path):
        command_args = [cls.executable, '--query', '--file', file_path]
        data = subprocess.check_output(command_args)
        if isinstance(data, bytes):
            data = data.decode('utf-8')

        line_split = data.split(' ')

        package_info = PackageInfo()
        package_info.package = line_split[0]
        package_info.version = line_split[1].rstrip()

        return package_info
<|endoftext|>


<commit_before>from __future__ import absolute_import

import logging

from sydent.db.valsession import ThreePidValSessionStore
from sydent.util import time_msec

from sydent.validators import (
    IncorrectClientSecretException,
    InvalidSessionIdException,
    IncorrectSessionTokenException,
    SessionExpiredException,
    ValidationSession,
)

logger = logging.getLogger(__name__)

def validateSessionWithToken(sydent, sid, clientSecret, token):
    """
    Attempt to validate a session, identified by the sid, using
    the token from out-of-band. The client secret is given to
    prevent attempts to guess the token for a sid.

    :param sid: The ID of the session to validate.
    :type sid: unicode
    :param clientSecret: The client secret to validate.
    :type clientSecret: unicode
    :param token: The token to validate.
    :type token: unicode

    :return: A dict with a "success" key which is True if the session
        was successfully validated, False otherwise.
    :rtype: dict[str, bool]

    :raise IncorrectClientSecretException: The provided client_secret is incorrect.
    :raise SessionExpiredException: The session has expired.
    :raise InvalidSessionIdException: The session ID couldn't be matched with an
        existing session.
    :raise IncorrectSessionTokenException: The provided token is incorrect
    """
    valSessionStore = ThreePidValSessionStore(sydent)
    s = valSessionStore.getTokenSessionById(sid)
    if not s:
        logger.info("Session ID %s not found", sid)
        raise InvalidSessionIdException()

    if not clientSecret == s.clientSecret:
        logger.info("Incorrect client secret", sid)
        raise IncorrectClientSecretException()

    if s.mtime + ValidationSession.THREEPID_SESSION_VALIDATION_TIMEOUT_MS < time_msec():
        logger.info("Session expired")
        raise SessionExpiredException()

    # TODO once we can validate the token oob
    #if tokenObj.validated and clientSecret == tokenObj.clientSecret:
    #    return True

    if s.token == token:
        logger.info("Setting session %s as validated", s.id)
        valSessionStore.setValidated(s.id, True)

        return {'success': True}
    else:
        logger.info("Incorrect token submitted")
        return IncorrectSessionTokenException()
<commit_msg>Raise IncorrectSessionTokenException instead of returning it<commit_after>from __future__ import absolute_import

import logging

from sydent.db.valsession import ThreePidValSessionStore
from sydent.util import time_msec

from sydent.validators import (
    IncorrectClientSecretException,
    InvalidSessionIdException,
    IncorrectSessionTokenException,
    SessionExpiredException,
    ValidationSession,
)

logger = logging.getLogger(__name__)

def validateSessionWithToken(sydent, sid, clientSecret, token):
    """
    Attempt to validate a session, identified by the sid, using
    the token from out-of-band. The client secret is given to
    prevent attempts to guess the token for a sid.

    :param sid: The ID of the session to validate.
    :type sid: unicode
    :param clientSecret: The client secret to validate.
    :type clientSecret: unicode
    :param token: The token to validate.
    :type token: unicode

    :return: A dict with a "success" key which is True if the session
        was successfully validated, False otherwise.
    :rtype: dict[str, bool]

    :raise IncorrectClientSecretException: The provided client_secret is incorrect.
    :raise SessionExpiredException: The session has expired.
    :raise InvalidSessionIdException: The session ID couldn't be matched with an
        existing session.
    :raise IncorrectSessionTokenException: The provided token is incorrect
    """
    valSessionStore = ThreePidValSessionStore(sydent)
    s = valSessionStore.getTokenSessionById(sid)
    if not s:
        logger.info("Session ID %s not found", sid)
        raise InvalidSessionIdException()

    if not clientSecret == s.clientSecret:
        logger.info("Incorrect client secret", sid)
        raise IncorrectClientSecretException()

    if s.mtime + ValidationSession.THREEPID_SESSION_VALIDATION_TIMEOUT_MS < time_msec():
        logger.info("Session expired")
        raise SessionExpiredException()

    # TODO once we can validate the token oob
    #if tokenObj.validated and clientSecret == tokenObj.clientSecret:
    #    return True

    if s.token == token:
        logger.info("Setting session %s as validated", s.id)
        valSessionStore.setValidated(s.id, True)

        return {'success': True}
    else:
        logger.info("Incorrect token submitted")
        raise IncorrectSessionTokenException()
<|endoftext|>


<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Scriptter

Scriptter is a brain for your cron job.

Usage:
    scriptter [--reset] [--state <state-path>] [trial | run] <schedule>
    scriptter check <schedule>

Options:
    -h --help              Show this screen.
    --version              Show version.
    --verbose              Show verbose output.
    --state <state-path>   Path for storing state [default: "./state.yml"]
    --reset                Reset stored state
"""
from collections import deque, Iterable, Mapping, OrderedDict
from codecs import open
import datetime as dt
import hashlib
import itertools as it
import logging
import pprint
import shlex
import subprocess

from docopt import docopt
from path import path
import parsedatetime
import pytz
import six
import yaml

VERSION = 0.1

logger = logging.getLogger('scriptter')

# __all__ = ['Schedule']

# Ordered loading/dumping of YAML: http://stackoverflow.com/a/21912744/18950
class OrderedLoader(yaml.Loader):
    pass

def construct_mapping(loader, node):
    loader.flatten_mapping(node)
    return OrderedDict(loader.construct_pairs(node))
OrderedLoader.add_constructor(
    yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
    construct_mapping)

class OrderedDumper(yaml.Dumper):
    pass

def _dict_representer(dumper, data):
    return dumper.represent_mapping(
        yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
        data.items())
OrderedDumper.add_representer(OrderedDict, _dict_representer)

def _load_yaml(method, data):
    result = getattr(yaml, method)(data, Loader=OrderedLoader)
    if method == 'load_all':
        result = deque(result)
    return result

def _load_file_path_or_yaml(method, data):
    if isinstance(data, six.string_types):
        if len(data.strip().splitlines()) > 1:
            return _load_yaml(method, data)
        else:
            file_path = path(data)
            if file_path.exists():
                with open(data, encoding='utf-8') as fi:
                    return _load_yaml(method, fi)

    else:
        return _load_yaml(method, data)

def yaml_load(data):
    result = _load_file_path_or_yaml('load', data)
    return result if result is not None else {}

def yaml_load_all(data):
    result = _load_file_path_or_yaml('load_all', data)
    return result if result is not None else deque()

def yaml_dump(data):
    return yaml.dump(data, Dumper=OrderedDumper, default_flow_style=False)

def yaml_dump_all(data):
    return yaml.dump_all(data, Dumper=OrderedDumper, default_flow_style=False)

def _ensure_unicode_strings(value):
    if isinstance(value, six.text_type):
        return value
    elif isinstance(value, six.string_types):
        return six.u(value)
    elif isinstance(value, Mapping):
        return {k: _ensure_unicode_strings(v) for k, v in value.items()}
    elif isinstance(value, Iterable):
        return [_ensure_unicode_strings(i) for i in value]
    else:
        return value

DEFAULTS = {
    'delay': '5mins',
    'timezone': 'US/Pacific',
    'cmd': 'echo @{as} says: {say}',
    'repeat': True,
}

class ScheduleLoader(object):
    def __init__(self, schedule_path):
        self.file_path = schedule_path
        options, items = self.extract_options_and_schedule_items(schedule_path)

        self.loaded_options = options
        self.options = OrderedDict()
        self.options.update(DEFAULTS)
        self.options.update(options)

        self.items = items

    @classmethod
    def extract_options_and_schedule_items(klass, data):
        schedule = yaml_load_all(data)
        options = {}
        items = []

        # Get first item, see if it contains defaults:
        item = schedule.popleft()
        if 'defaults' in item:
            options = item['defaults']
        else:
            items.append(item)

        # Everything else is a schedule item.
        items.extend(schedule)

        return options, items

    def add_ids(self):
        for item in self.items:
            if 'id' not in item:
                item['id'] = self.hash_item(item)

    def hash_item(self, item):
        if not isinstance(item, six.string_types):
            if isinstance(item, Mapping):
                item = tuple(sorted(
                    (k, self.hash_item(v))
                    for k, v in item.items()
                ))
            elif isinstance(item, Iterable):
                item = tuple(sorted(item))

        return hashlib.md5(repr(item)).hexdigest()

    def as_stream(self):
        stream = [{'defaults': self.loaded_options}]
        stream.extend(self.items)
        return stream

    def as_yaml(self):
        return yaml_dump_all(self.as_stream())

class Schedule(object):
    def __init__(self, options, items):
        self.options = options
        self.items = items

    def by_id(self, id):
        try:
            return next(it.dropwhile(
                lambda i: i.get('id') != id,
                self.items
            ))
        except StopIteration:
            raise IndexError(id)

    def next_after_id(self, id):
        try:
            gen = it.dropwhile(
                lambda i: i.get('id') != id,
                self.items
            )
            next(gen)
            return next(gen)
        except StopIteration:
            if self.options['repeat']:
                return self.items[0]
            else:
                raise IndexError(id)

    def get_timezone(self):
        return pytz.timezone(self.options['timezone'])

    def localize_naive_utc_datetime(self, time):
        return pytz.UTC.localize(time).astimezone(self.get_timezone())

    def get_now(self):
        return self.localize_naive_utc_datetime(dt.datetime.utcnow())

class StateLoader(object):
    def __init__(self, state_path):
        self.state_path = state_path
        self.state = yaml_load(state_path)

    def write_state(self, fp=None):
        if fp is None:
            assert isinstance(self.state_path, six.string_types)
            fp = self.state_path

        with open(fp, 'w') as fo:
            state = yaml_dump(self.state)
            fo.write(state)

    def reset(self):
        self.state.clear()

class SENTINEL(object):
    pass

class Scriptter(object):
    def __init__(self, schedule, state):
        self.state = state
        self.schedule = schedule
        self.calendar = parsedatetime.Calendar()

    def get_scheduled_item(self):
        scheduled_item = None
        scheduled_id = self.state.get('scheduled', SENTINEL)
        if scheduled_id is SENTINEL:
            scheduled_item = self.schedule.items[0]
        elif scheduled_id:
            try:
                scheduled_item = self.schedule.by_id(scheduled_id)
            except IndexError:
                logger.error("Could not find scheduled item %s", scheduled_id)

        return scheduled_item

    def get_scheduled_run_time(self):
        when = self.state.get('when')
        if not when:
            when = self.schedule.get_now()
        else:
            when = pytz.UTC.localize(when)

        return when.astimezone(self.schedule.get_timezone())

    def get_next_item_after(self, item):
        try:
            return self.schedule.next_after_id(item['id'])
        except IndexError:
            return None

    def get_next_run_time(self, item, now=None):
        ctx = self.get_context(item)
        delay = ctx['delay']
        tz = pytz.timezone(ctx['timezone'])
        if now is None:
            now = pytz.UTC.localize(dt.datetime.utcnow())
        if now.tzinfo is None:
            now = pytz.UTC.localize(now)
        now = now.astimezone(tz)
        logger.debug('Using base `now`: %r', now)
        when = self.calendar.parseDT(
            delay,
            sourceTime=now,
            tzinfo=tz,
        )[0]
        return when

    def set_next(self, item, now=None):
        next_item = self.get_next_item_after(item)
        if next_item is None:
            next_id = None
        else:
            next_id = next_item['id']

        self.state['scheduled'] = next_id
        self.state['when'] = (
            None if next_id is None
            else self.get_next_run_time(next_item, now=now))

    def get_context(self, item):
        ctx = {}
        for data in (self.schedule.options, item):
            for key, value in data.items():
                # Ensure that all values are unicode strings
                ctx[key] = _ensure_unicode_strings(value)

        return ctx

    def get_commands(self, item):
        ctx = self.get_context(item)
        cmd = ctx['cmd']
        if isinstance(cmd, six.string_types):
            commands = [cmd]
        elif isinstance(cmd, Iterable):
            commands = list(cmd)

        return [command.format(**ctx) for command in commands]

    def run(self, dry_run=False):
        item = self.get_scheduled_item()
        when = self.get_scheduled_run_time()
        now = self.schedule.get_now()

        if item is None:
            logger.warning("Nothing to do!")
        elif when > now:
            for command in self.get_commands(item):
                logger.warning("Will run `%s` at %s", command, when.isoformat())
        else:
            self.set_next(item)
            logger.debug('Running with item: %s', pprint.pformat(item))

            for command in self.get_commands(item):
                command = shlex.split(command)
                logger.info("Running command: %r", command)
                if not dry_run:
                    result = subprocess.check_output(command)
                    logger.info("Result was: %s", result)

    def check(self):
        formatter = '%b %d, %Y at %X'
        now = self.schedule.get_now()
        print(six.u("%s %s -- (start)") % (now.strftime(formatter), now.tzinfo))
        for item in self.schedule.items:
            print('-----')
            delay = self.get_context(item)['delay']
            when = self.get_next_run_time(item, now=now)
            print(six.u("%s -- (%s)") % (when.strftime(formatter), delay))
            for command in self.get_commands(item):
                print(command)
            now = when
        print('-----')

def main():   # pragma: no cover
    logging.basicConfig()
    arguments = docopt(__doc__, version='Scriptter {}'.format(VERSION))
    if arguments.get('--verbose'):
        logger.setLevel(logging.DEBUG)
    else:
        logger.setLevel(logging.INFO)

    logger.debug("Received arguments: %s", pprint.pformat(arguments))
    loaded_schedule = ScheduleLoader(arguments['<schedule>'])
    loaded_schedule.add_ids()
    # loaded_schedule.write_schedule()

    schedule = Schedule(loaded_schedule.options, loaded_schedule.items)

    state_path = arguments.get('<state-path>', './state.yml')
    state = StateLoader(state_path)

    if arguments['--reset']:
        state.reset()
        state.write_state()

    scriptter = Scriptter(schedule, state.state)

    if arguments['run'] or arguments['trial']:
        scriptter.run(dry_run=arguments['trial'])
        state.write_state()
    elif arguments['check']:
        scriptter.check()

if __name__ == '__main__':   # pragma: no cover
    main()
<commit_msg>Add --verbose option to check command<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Scriptter

Scriptter is a brain for your cron job.

Usage:
    scriptter [--reset] [--verbose] [--state <state-path>] [trial | run] <schedule>
    scriptter [--verbose] check <schedule>

Options:
    -h --help              Show this screen.
    --version              Show version.
    --verbose              Show verbose output.
    --state <state-path>   Path for storing state [default: "./state.yml"]
    --reset                Reset stored state
"""
from collections import deque, Iterable, Mapping, OrderedDict
from codecs import open
import datetime as dt
import hashlib
import itertools as it
import logging
import pprint
import shlex
import subprocess

from docopt import docopt
from path import path
import parsedatetime
import pytz
import six
import yaml

VERSION = 0.1

logger = logging.getLogger('scriptter')

# __all__ = ['Schedule']

# Ordered loading/dumping of YAML: http://stackoverflow.com/a/21912744/18950
class OrderedLoader(yaml.Loader):
    pass

def construct_mapping(loader, node):
    loader.flatten_mapping(node)
    return OrderedDict(loader.construct_pairs(node))
OrderedLoader.add_constructor(
    yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
    construct_mapping)

class OrderedDumper(yaml.Dumper):
    pass

def _dict_representer(dumper, data):
    return dumper.represent_mapping(
        yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
        data.items())
OrderedDumper.add_representer(OrderedDict, _dict_representer)

def _load_yaml(method, data):
    result = getattr(yaml, method)(data, Loader=OrderedLoader)
    if method == 'load_all':
        result = deque(result)
    return result

def _load_file_path_or_yaml(method, data):
    if isinstance(data, six.string_types):
        if len(data.strip().splitlines()) > 1:
            return _load_yaml(method, data)
        else:
            file_path = path(data)
            if file_path.exists():
                with open(data, encoding='utf-8') as fi:
                    return _load_yaml(method, fi)

    else:
        return _load_yaml(method, data)

def yaml_load(data):
    result = _load_file_path_or_yaml('load', data)
    return result if result is not None else {}

def yaml_load_all(data):
    result = _load_file_path_or_yaml('load_all', data)
    return result if result is not None else deque()

def yaml_dump(data):
    return yaml.dump(data, Dumper=OrderedDumper, default_flow_style=False)

def yaml_dump_all(data):
    return yaml.dump_all(data, Dumper=OrderedDumper, default_flow_style=False)

def _ensure_unicode_strings(value):
    if isinstance(value, six.text_type):
        return value
    elif isinstance(value, six.string_types):
        return six.u(value)
    elif isinstance(value, Mapping):
        return {k: _ensure_unicode_strings(v) for k, v in value.items()}
    elif isinstance(value, Iterable):
        return [_ensure_unicode_strings(i) for i in value]
    else:
        return value

DEFAULTS = {
    'delay': '5mins',
    'timezone': 'US/Pacific',
    'cmd': 'echo @{as} says: {say}',
    'repeat': True,
}

class ScheduleLoader(object):
    def __init__(self, schedule_path):
        self.file_path = schedule_path
        options, items = self.extract_options_and_schedule_items(schedule_path)

        self.loaded_options = options
        self.options = OrderedDict()
        self.options.update(DEFAULTS)
        self.options.update(options)

        self.items = items

    @classmethod
    def extract_options_and_schedule_items(klass, data):
        schedule = yaml_load_all(data)
        options = {}
        items = []

        # Get first item, see if it contains defaults:
        item = schedule.popleft()
        if 'defaults' in item:
            options = item['defaults']
        else:
            items.append(item)

        # Everything else is a schedule item.
        items.extend(schedule)

        return options, items

    def add_ids(self):
        for item in self.items:
            if 'id' not in item:
                item['id'] = self.hash_item(item)

    def hash_item(self, item):
        if not isinstance(item, six.string_types):
            if isinstance(item, Mapping):
                item = tuple(sorted(
                    (k, self.hash_item(v))
                    for k, v in item.items()
                ))
            elif isinstance(item, Iterable):
                item = tuple(sorted(item))

        return hashlib.md5(repr(item)).hexdigest()

    def as_stream(self):
        stream = [{'defaults': self.loaded_options}]
        stream.extend(self.items)
        return stream

    def as_yaml(self):
        return yaml_dump_all(self.as_stream())

class Schedule(object):
    def __init__(self, options, items):
        self.options = options
        self.items = items

    def by_id(self, id):
        try:
            return next(it.dropwhile(
                lambda i: i.get('id') != id,
                self.items
            ))
        except StopIteration:
            raise IndexError(id)

    def next_after_id(self, id):
        try:
            gen = it.dropwhile(
                lambda i: i.get('id') != id,
                self.items
            )
            next(gen)
            return next(gen)
        except StopIteration:
            if self.options['repeat']:
                return self.items[0]
            else:
                raise IndexError(id)

    def get_timezone(self):
        return pytz.timezone(self.options['timezone'])

    def localize_naive_utc_datetime(self, time):
        return pytz.UTC.localize(time).astimezone(self.get_timezone())

    def get_now(self):
        return self.localize_naive_utc_datetime(dt.datetime.utcnow())

class StateLoader(object):
    def __init__(self, state_path):
        self.state_path = state_path
        self.state = yaml_load(state_path)

    def write_state(self, fp=None):
        if fp is None:
            assert isinstance(self.state_path, six.string_types)
            fp = self.state_path

        with open(fp, 'w') as fo:
            state = yaml_dump(self.state)
            fo.write(state)

    def reset(self):
        self.state.clear()

class SENTINEL(object):
    pass

class Scriptter(object):
    def __init__(self, schedule, state):
        self.state = state
        self.schedule = schedule
        self.calendar = parsedatetime.Calendar()

    def get_scheduled_item(self):
        scheduled_item = None
        scheduled_id = self.state.get('scheduled', SENTINEL)
        if scheduled_id is SENTINEL:
            scheduled_item = self.schedule.items[0]
        elif scheduled_id:
            try:
                scheduled_item = self.schedule.by_id(scheduled_id)
            except IndexError:
                logger.error("Could not find scheduled item %s", scheduled_id)

        return scheduled_item

    def get_scheduled_run_time(self):
        when = self.state.get('when')
        if not when:
            when = self.schedule.get_now()
        else:
            when = pytz.UTC.localize(when)

        return when.astimezone(self.schedule.get_timezone())

    def get_next_item_after(self, item):
        try:
            return self.schedule.next_after_id(item['id'])
        except IndexError:
            return None

    def get_next_run_time(self, item, now=None):
        ctx = self.get_context(item)
        delay = ctx['delay']
        tz = pytz.timezone(ctx['timezone'])
        if now is None:
            now = pytz.UTC.localize(dt.datetime.utcnow())
        if now.tzinfo is None:
            now = pytz.UTC.localize(now)
        now = now.astimezone(tz)
        logger.debug('Using base `now`: %r', now)
        when = self.calendar.parseDT(
            delay,
            sourceTime=now,
            tzinfo=tz,
        )[0]
        return when

    def set_next(self, item, now=None):
        next_item = self.get_next_item_after(item)
        if next_item is None:
            next_id = None
        else:
            next_id = next_item['id']

        self.state['scheduled'] = next_id
        self.state['when'] = (
            None if next_id is None
            else self.get_next_run_time(next_item, now=now))

    def get_context(self, item):
        ctx = {}
        for data in (self.schedule.options, item):
            for key, value in data.items():
                # Ensure that all values are unicode strings
                ctx[key] = _ensure_unicode_strings(value)

        return ctx

    def get_commands(self, item):
        ctx = self.get_context(item)
        cmd = ctx['cmd']
        if isinstance(cmd, six.string_types):
            commands = [cmd]
        elif isinstance(cmd, Iterable):
            commands = list(cmd)

        return [command.format(**ctx) for command in commands]

    def run(self, dry_run=False):
        item = self.get_scheduled_item()
        when = self.get_scheduled_run_time()
        now = self.schedule.get_now()

        if item is None:
            logger.warning("Nothing to do!")
        elif when > now:
            for command in self.get_commands(item):
                logger.warning("Will run `%s` at %s", command, when.isoformat())
        else:
            self.set_next(item)
            logger.debug('Running with item: %s', pprint.pformat(item))

            for command in self.get_commands(item):
                command = shlex.split(command)
                logger.info("Running command: %r", command)
                if not dry_run:
                    result = subprocess.check_output(command)
                    logger.info("Result was: %s", result)

    def check(self):
        formatter = '%b %d, %Y at %X'
        now = self.schedule.get_now()
        print(six.u("%s %s -- (start)") % (now.strftime(formatter), now.tzinfo))
        for item in self.schedule.items:
            print('-----')
            delay = self.get_context(item)['delay']
            when = self.get_next_run_time(item, now=now)
            print(six.u("%s -- (%s)") % (when.strftime(formatter), delay))
            for command in self.get_commands(item):
                print(command)
            now = when
        print('-----')

def main():   # pragma: no cover
    logging.basicConfig()
    arguments = docopt(__doc__, version='Scriptter {}'.format(VERSION))
    if arguments.get('--verbose'):
        logger.setLevel(logging.DEBUG)
    else:
        logger.setLevel(logging.INFO)

    logger.debug("Received arguments: %s", pprint.pformat(arguments))
    loaded_schedule = ScheduleLoader(arguments['<schedule>'])
    loaded_schedule.add_ids()
    # loaded_schedule.write_schedule()

    schedule = Schedule(loaded_schedule.options, loaded_schedule.items)

    state_path = arguments.get('<state-path>', './state.yml')
    state = StateLoader(state_path)

    if arguments['--reset']:
        state.reset()
        state.write_state()

    scriptter = Scriptter(schedule, state.state)

    if arguments['run'] or arguments['trial']:
        scriptter.run(dry_run=arguments['trial'])
        state.write_state()
    elif arguments['check']:
        scriptter.check()

if __name__ == '__main__':   # pragma: no cover
    main()
<|endoftext|>