• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python lockfile.FilesystemLock类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中twisted.python.lockfile.FilesystemLock的典型用法代码示例。如果您正苦于以下问题:Python FilesystemLock类的具体用法?Python FilesystemLock怎么用?Python FilesystemLock使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了FilesystemLock类的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: copyPackage

    def copyPackage(title):
        """
        Copy package directory to db path using a file lock to avoid potential
        concurrency race conditions.

        @param title: string to use in log entry
        @type title: C{str}
        """
        dbpath = FilePath(TimezoneCache.getDBPath())
        pkgpath = TimezoneCache.FilteredFilePath(TimezoneCache._getPackageDBPath())

        lockfile = FilesystemLock(dbpath.path + ".lock")
        result = lockfile.lock()
        try:
            if result and not dbpath.exists():
                log.info(
                    "{title} timezones from {pkg} to {to}",
                    title=title,
                    pkg=pkgpath.path,
                    to=dbpath.path
                )

                # Copy over the entire package
                pkgpath.copyFilteredDirectoryTo(dbpath)
        finally:
            if result:
                lockfile.unlock()
开发者ID:red-hood,项目名称:calendarserver,代码行数:27,代码来源:timezones.py


示例2: check

 def check():
     localLock = FilesystemLock(workingDirectory + ".lock")
     self.assertTrue(localLock.lock())
     self.assertEqual(1, fakeReactor.stopCount)
     # We don't wait for the process deferreds here, so nothing is
     # returned by the function before shutdown
     self.assertIdentical(None, functions[0]())
开发者ID:JohnDoes95,项目名称:project_parser,代码行数:7,代码来源:test_disttrial.py


示例3: test_runUsedDirectory

    def test_runUsedDirectory(self):
        """
        L{DistTrialRunner} checks if the test directory is already locked, and
        if it is generates a name based on it.
        """

        class FakeReactorWithLock(FakeReactor):

            def spawnProcess(oself, worker, *args, **kwargs):
                self.assertEqual(os.path.abspath(worker._logDirectory),
                                 os.path.abspath(
                                     os.path.join(workingDirectory + "-1",
                                                  str(oself.spawnCount))))
                localLock = FilesystemLock(workingDirectory + "-1.lock")
                self.assertFalse(localLock.lock())
                oself.spawnCount += 1
                worker.makeConnection(FakeTransport())
                worker._ampProtocol.run = lambda *args: succeed(None)

        newDirectory = self.mktemp()
        os.mkdir(newDirectory)
        workingDirectory = os.path.join(newDirectory, "_trial_temp")
        lock = FilesystemLock(workingDirectory + ".lock")
        lock.lock()
        self.addCleanup(lock.unlock)
        self.runner._workingDirectory = workingDirectory

        fakeReactor = FakeReactorWithLock()
        suite = TrialSuite()
        for i in range(10):
            suite.addTest(TestCase())
        self.runner.run(suite, fakeReactor)
开发者ID:JohnDoes95,项目名称:project_parser,代码行数:32,代码来源:test_disttrial.py


示例4: do_restore

def do_restore():
    lock = FilesystemLock("/var/run/jolicloud_restore_utility.lock")
    if lock.lock():
        if os.environ.get('DISPLAY', False):
            JolicloudRestoreUtilityGtk()
        else:
            JolicloudRestoreUtilityText()
        reactor.run()
        lock.unlock()
开发者ID:AlfredArouna,项目名称:jolicloud-restore-utility,代码行数:9,代码来源:restore_utility.py


示例5: spawnProcess

 def spawnProcess(oself, worker, *args, **kwargs):
     self.assertEqual(os.path.abspath(worker._logDirectory),
                      os.path.abspath(
                          os.path.join(workingDirectory + "-1",
                                       str(oself.spawnCount))))
     localLock = FilesystemLock(workingDirectory + "-1.lock")
     self.assertFalse(localLock.lock())
     oself.spawnCount += 1
     worker.makeConnection(FakeTransport())
     worker._ampProtocol.run = lambda *args: succeed(None)
开发者ID:JohnDoes95,项目名称:project_parser,代码行数:10,代码来源:test_disttrial.py


示例6: _unusedTestDirectory

def _unusedTestDirectory(base):
    """
    Find an unused directory named similarly to C{base}.

    Once a directory is found, it will be locked and a marker dropped into it to
    identify it as a trial temporary directory.

    @param base: A template path for the discovery process.  If this path
        exactly cannot be used, a path which varies only in a suffix of the
        basename will be used instead.
    @type base: L{FilePath}

    @return: A two-tuple.  The first element is a L{FilePath} representing the
        directory which was found and created.  The second element is a locked
        L{FilesystemLock<twisted.python.lockfile.FilesystemLock>}.  Another
        call to C{_unusedTestDirectory} will not be able to reused the the
        same name until the lock is released, either explicitly or by this
        process exiting.
    """
    from twisted.python.lockfile import FilesystemLock
    counter = 0
    while True:
        if counter:
            testdir = base.sibling('%s-%d' % (base.basename(), counter))
        else:
            testdir = base

        testDirLock = FilesystemLock(testdir.path + '.lock')
        if testDirLock.lock():
            # It is not in use
            if testdir.exists():
                # It exists though - delete it
                _removeSafely(testdir)

            # Create it anew and mark it as ours so the next _removeSafely on it
            # succeeds.
            testdir.makedirs()
            testdir.child('_trial_marker').setContent('')
            return testdir, testDirLock
        else:
            # It is in use
            if base.basename() == '_trial_temp':
                counter += 1
            else:
                raise _WorkingDirectoryBusy()
开发者ID:geodrinx,项目名称:gearthview,代码行数:45,代码来源:util.py


示例7: __init__

    def __init__(self, uuid, state, responder):
        """
        Initialize the lock resource. Parameters to this constructor are
        automatically passed by u1db.

        :param uuid: The user unique id.
        :type uuid: str
        :param state: The backend database state.
        :type state: u1db.remote.ServerState
        :param responder: The infrastructure to send responses to client.
        :type responder: u1db.remote.HTTPResponder
        """
        self._shared_db = state.open_database(SoledadApp.SHARED_DB_NAME)
        self._lock_doc_id = '%s%s' % (SHARED_DB_LOCK_DOC_ID_PREFIX, uuid)
        self._lock = FilesystemLock(
            hashlib.sha512(self._lock_doc_id).hexdigest())
        self._state = state
        self._responder = responder
开发者ID:MeanderingCode,项目名称:soledad,代码行数:18,代码来源:__init__.py


示例8: OptionParser

            log.error('Sendchange failed for %s: ' % release, exc_info=True)

    if rc != 0:
        sys.exit(rc)

if __name__ == '__main__':
    parser = OptionParser(__doc__)
    parser.add_option('-l', '--lockfile', dest='lockfile',
                      default=path.join(os.getcwd(), ".release-runner.lock"))
    parser.add_option('-c', '--config', dest='config',
                      help='Configuration file')

    options = parser.parse_args()[0]

    if not options.config:
        parser.error('Need to pass a config')

    lockfile = options.lockfile
    log.debug("Using lock file %s", lockfile)
    lock = FilesystemLock(lockfile)
    if not lock.lock():
        raise Exception("Cannot acquire lock: %s" % lockfile)
    log.debug("Lock acquired: %s", lockfile)
    if not lock.clean:
        log.warning("Previous run did not properly exit")
    try:
        main(options)
    finally:
        log.debug("Releasing lock: %s", lockfile)
        lock.unlock()
开发者ID:magnyld,项目名称:build-tools,代码行数:30,代码来源:release-runner.py


示例9: FilesystemLock

 tempdir = path = tempfile.mkdtemp()
 
 _home = os.environ.get('HOME', '/')
 if platform.system() == 'Windows':
     novatool_config_home = os.path.join(os.environ['APPDATA'], 'Novatool')
 elif platform.system() == 'Linux':
     novatool_config_home = os.path.join(os.environ.get('XDG_CONFIG_HOME', os.path.join(_home, '.config')), 'novatool')
 elif platform.system() == 'Darwin':
     novatool_config_home = os.path.join(_home, 'Library', 'Application Support', 'Novatool')
 else:
     novatool_config_home = os.path.join(_home, '.novatool')
 if not os.path.exists(novatool_config_home):
     os.makedirs(novatool_config_home)
     
 ipc_file = os.path.join(novatool_config_home,'ipc')
 
 lock = FilesystemLock(os.path.join(novatool_config_home,"lock"))
 if lock.lock():
     mainWin = MainWindow(novatool_config_home, tempdir, githash)
     reactor.run()
     lock.unlock()
     QApplication.quit()
 else:
     if os.path.isfile(ipc_file):
         f = open(ipc_file,'r')
         ipc_port = int(f.read())
         f.close()
         s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
         s.connect(('localhost', ipc_port))
     else:
         print lock.name, 'is locked.'
开发者ID:wosigh,项目名称:novatool,代码行数:31,代码来源:novatool.py


示例10: LockResource

class LockResource(object):
    """
    Handle requests for locking documents.

    This class uses Twisted's Filesystem lock to manage a lock in the shared
    database.
    """

    url_pattern = '/%s/lock/{uuid}' % SHARED_DB_NAME
    """
    """

    TIMEOUT = 300  # XXX is 5 minutes reasonable?
    """
    The timeout after which the lock expires.
    """

    # used for lock doc storage
    TIMESTAMP_KEY = '_timestamp'
    LOCK_TOKEN_KEY = '_token'

    FILESYSTEM_LOCK_TRIES = 5
    FILESYSTEM_LOCK_SLEEP_SECONDS = 1

    def __init__(self, uuid, state, responder):
        """
        Initialize the lock resource. Parameters to this constructor are
        automatically passed by u1db.

        :param uuid: The user unique id.
        :type uuid: str
        :param state: The backend database state.
        :type state: u1db.remote.ServerState
        :param responder: The infrastructure to send responses to client.
        :type responder: u1db.remote.HTTPResponder
        """
        self._shared_db = state.open_database(SHARED_DB_NAME)
        self._lock_doc_id = '%s%s' % (SHARED_DB_LOCK_DOC_ID_PREFIX, uuid)
        self._lock = FilesystemLock(
            os.path.join(
                tempfile.gettempdir(),
                hashlib.sha512(self._lock_doc_id).hexdigest()))
        self._state = state
        self._responder = responder

    @http_app.http_method(content=str)
    def put(self, content=None):
        """
        Handle a PUT request to the lock document.

        A lock is a document in the shared db with doc_id equal to
        'lock-<uuid>' and the timestamp of its creation as content. This
        method obtains a threaded-lock and creates a lock document if it does
        not exist or if it has expired.

        It returns '201 Created' and a pair containing a token to unlock and
        the lock timeout, or '403 AlreadyLockedError' and the remaining amount
        of seconds the lock will still be valid.

        :param content: The content of the PUT request. It is only here
                        because PUT requests with empty content are considered
                        invalid requests by u1db.
        :type content: str
        """
        # obtain filesystem lock
        if not self._try_obtain_filesystem_lock():
            self._responder.send_response_json(
                LockTimedOutError.status,  # error: request timeout
                error=LockTimedOutError.wire_description)
            return

        created_lock = False
        now = time.time()
        token = hashlib.sha256(os.urandom(10)).hexdigest()  # for releasing
        lock_doc = self._shared_db.get_doc(self._lock_doc_id)
        remaining = self._remaining(lock_doc, now)

        # if there's no lock, create one
        if lock_doc is None:
            lock_doc = self._shared_db.create_doc(
                {
                    self.TIMESTAMP_KEY: now,
                    self.LOCK_TOKEN_KEY: token,
                },
                doc_id=self._lock_doc_id)
            created_lock = True
        else:
            if remaining == 0:
                # lock expired, create new one
                lock_doc.content = {
                    self.TIMESTAMP_KEY: now,
                    self.LOCK_TOKEN_KEY: token,
                }
                self._shared_db.put_doc(lock_doc)
                created_lock = True

        self._try_release_filesystem_lock()

        # send response to client
        if created_lock is True:
#.........这里部分代码省略.........
开发者ID:Moscarda,项目名称:soledad,代码行数:101,代码来源:lock_resource.py


示例11: realCheck

 def realCheck():
     localLock = FilesystemLock(workingDirectory + ".lock")
     self.assertTrue(localLock.lock())
     # Stop is not called, as it ought to have been called before
     self.assertEqual(0, fakeReactor.stopCount)
开发者ID:JohnDoes95,项目名称:project_parser,代码行数:5,代码来源:test_disttrial.py


示例12: getContext

    def getContext(self):
        self.method = SSL.TLSv1_METHOD
        ctx = ssl.ClientContextFactory.getContext(self)
        ctx.set_verify(
            SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT,
            verifyCallback
        )
        #print dir(ctx)
        #raise SystemExit
        return ctx


from os import path

if __name__ == '__main__':
    lock = FilesystemLock("treestatusbot.lock")
    if isLocked("treestatusbot.lock"):
        raise SystemExit("There's already a bot running. If this is not the "
                         "case, please remove treestatusbot.lock manually")
    else:
        lock.lock()
    def unlock():
        lock.unlock()

    f = GaiaBotFactory()
    reactor.connectSSL(SERVER, int(PORT), f, CtxFactory())
    print "Connecting to", SERVER, PORT
    # run bot
    reactor.addSystemEventTrigger('before', 'shutdown', unlock)
    reactor.run()
开发者ID:djmitche,项目名称:treestatusbot,代码行数:30,代码来源:main.py


示例13: obtain_lock

def obtain_lock():
    scriptname = os.path.basename(__file__)
    lockfile = os.path.join(tempfile.gettempdir(), scriptname + '.lock')
    lock = FilesystemLock(lockfile)
    return lock.lock()
开发者ID:leapcode,项目名称:leap_platform,代码行数:5,代码来源:soledad_sync.py



注:本文中的twisted.python.lockfile.FilesystemLock类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python log.addObserver函数代码示例发布时间:2022-05-27
下一篇:
Python hashlib.sha1函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap