Пример #1
0
def write_cluster(cluster):
    if not os.path.isdir(globals.CONFIG_DIR):
        try:
            os.mkdir(globals.CONFIG_DIR)
        except:
            fail("failed to create directory: {}".format(globals.CONFIG_DIR))

    # initialize locking - NOTE: make sure to release_local() prior to all exceptions/returns)
    lock = Lock(globals.CLUSTER_FILE_LOCK)

    # get lock (for concurrent datamodel access across)
    lock.get_lock()

    current_clusters = get_clusters(None)
    if len(current_clusters) == 0:
        current_clusters.append(cluster)
        with open(globals.CLUSTER_FILE, 'w') as outfile:
            json.dump(current_clusters, outfile)
    else:
        update_clusters = []
        flag_found = False
        for c in current_clusters:
            if c['name'] == cluster['name']:
                update_clusters.append(cluster)
                flag_found = True
            else:
                update_clusters.append(c)
        if not flag_found:
            update_clusters.append(cluster)
        with open(globals.CLUSTER_FILE, 'w') as outfile:
            json.dump(update_clusters, outfile)

    # release lock
    lock.release_lock()
Пример #2
0
    def _kickGC(self):
        # don't bother if an instance already running (this is just an
        # optimization to reduce the overhead of forking a new process if we
        # don't have to, but the process will check the lock anyways)
        lockRunning = Lock(cleanup.LOCK_TYPE_RUNNING, self.uuid)
        if not lockRunning.acquireNoblock():
            if cleanup.should_preempt(self.session, self.uuid):
                util.SMlog(
                    "Aborting currently-running coalesce of garbage VDI")
                try:
                    if not cleanup.abort(self.uuid, soft=True):
                        util.SMlog("The GC has already been scheduled to "
                                   "re-start")
                except util.CommandException as e:
                    if e.code != errno.ETIMEDOUT:
                        raise
                    util.SMlog('failed to abort the GC')
                finally:
                    return
            else:
                util.SMlog("A GC instance already running, not kicking")
                return
        else:
            lockRunning.release()

        util.SMlog("Kicking GC")
        cleanup.gc(self.session, self.uuid, True)
Пример #3
0
def main(package_id, dryrun):
    logger.info(f'package_id={package_id}')

    lock = Lock('/tmp/poll_manager.lock')
    if lock.locked:
        logger.error('Lock file {} exists, exiting...'.format(lock.lock_file))
        return 1
    else:
        lock.acquire()
        logger.warning('Lock file {} acquired'.format(lock.lock_file))

    try:
        scope, identifier, revision = package_id.split('.')

        connection = connect()
        event = get_package_info(connection, scope, identifier, revision)

        if event:
            qm = QueueManager()

            msg = f"Enqueue: {event.package} - {event.datetime} - " + \
                  f"{event.owner} - {event.doi} - {event.method}"
            logger.warning(msg)
            if not dryrun:
                qm.enqueue(event=event)
            else:
                msg = f"DRYRUN: qm.enqueue(event=event)"
                logger.info(msg)

    except AdapterRequestFailureException as e:
        logger.error(e)

    lock.release()
    logger.warning('Lock file {} released'.format(lock.lock_file))
    return 0
Пример #4
0
def write_auth_profile(auth):
    """Write authorization file to disk"""

    # initialize locking - NOTE: make sure to release_local() prior to all exceptions/returns)
    lock = Lock(globals.AUTH_PROFILE_FILE_LOCK)

    # get lock (for concurrent datamodel access across)
    lock.get_lock()

    current_profile = get_auth_profiles()
    if len(current_profile) == 0:
        current_profile.append(auth)
        with open(globals.AUTH_PROFILE_FILE, 'w') as outfile:
            json.dump(current_profile, outfile)
    else:
        update_profile = []
        flag_found = False
        for profile in current_profile:
            if profile['auth_name'] == auth['auth_name']:
                update_profile.append(auth)
                flag_found = True
            else:
                update_profile.append(profile)
        if not flag_found:
            update_profile.append(auth)
        with open(globals.AUTH_PROFILE_FILE, 'w') as outfile:
            json.dump(update_profile, outfile)

    # release lock
    lock.release_lock()
Пример #5
0
def daemonize(args, callback):
    with DaemonContext():
        create_process = False
        lock = Lock(LOCKFILE, os.getpid(), args.name, args.sea_ep[0],
                    args.sea_ep[1], args.port)
        if lock.is_locked():
            lock_pid = lock.get_pid()
            if not lock.is_same_file(args.name, args.sea_ep[0],
                                    args.sea_ep[1]) \
                    or not is_process_running(lock_pid):
                try:
                    os.kill(lock_pid, signal.SIGQUIT)
                except OSError:
                    pass
                except TypeError:
                    pass
                lock.break_lock()
                create_process = True
        else:
            create_process = True

        if create_process:
            lock.acquire()
            callback(args.name, season=args.sea_ep[0], episode=args.sea_ep[1],
                     serve=True, port=args.port)
            lock.release()
Пример #6
0
def main():
    lock = Lock()
    lock.set_server_url("http://192.168.0.17:5000/validate-pin")
    lock.set_wifi_conf("GOT", "MASTER2D")
    lock.connect_to_wifi()
    lock.set_rc522_uid_addr(0x08)
    lock.run()
Пример #7
0
    def lock_file(self):
        '''Handle the mc1.Lock object. Public objects:
        lock = mfc1.Lock
        lockstate = Status of the lock file.
                    '' = No status.
                    'written' = Lock file is written
                    'deleted' = Lock file is deleted
                    'exit' = Program exit

        '''
        userid = wx.GetUserId()
        wxpath = wx.StandardPaths.Get()
        userdir = wxpath.GetDocumentsDir()
        self.lock = Lock(path=userdir, userid=userid)
        self.lockstate = ''
        if self.lock.one_instance('mindfulclock1'):
            # One instance.
            self.lock.write_lock()
            self.lockstate = 'written'
        else:
            # More than one instance.
            if self.start_question():
                # Start the clock.
                self.lock.write_lock()
                self.lockstate = 'written'
            else:
                # Exit the program.
                self.lockstate = 'exit'
Пример #8
0
def main():

    lock = Lock('/tmp/poll_manager.lock')
    if lock.locked:
        logger.error('Lock file {} exists, exiting...'.format(lock.lock_file))
        return 1
    else:
        lock.acquire()
        logger.warn('Lock file {} acquired'.format(lock.lock_file))

    url = properties.PASTA_BASE_URL + '/changes/eml?'
    qm = QueueManager()

    fromDate = None
    dt = qm.get_last_datetime()
    if dt is not None:
        fromDate = datetime.strftime(dt, '%Y-%m-%dT%H:%M:%S.%f')

    if fromDate is None:
        bootstrap(url=url)
    else:
        parse(url=url, fromDate=fromDate)

    lock.release()
    logger.warn('Lock file {} released'.format(lock.lock_file))
    return 0
Пример #9
0
    def load(self, sr_uuid):
        self.ops_exclusive = FileSR.OPS_EXCLUSIVE
        self.lock = Lock(vhdutil.LOCK_TYPE_SR, self.uuid)
        self.sr_vditype = SR.DEFAULT_TAP
        self.driver_config = DRIVER_CONFIG
        if not self.dconf.has_key('server'):
            raise xs_errors.XenError('ConfigServerMissing')
        self.remoteserver = self.dconf['server']
        self.nosubdir = False
        if self.sr_ref and self.session is not None:
            self.sm_config = self.session.xenapi.SR.get_sm_config(self.sr_ref)
        else:
            self.sm_config = self.srcmd.params.get('sr_sm_config') or {}
        self.nosubdir = self.sm_config.get('nosubdir') == "true"
        if self.dconf.has_key('serverpath'):
            self.remotepath = os.path.join(self.dconf['serverpath'],
                                           not self.nosubdir and sr_uuid
                                           or "").encode('utf-8')
        self.path = os.path.join(SR.MOUNT_BASE, sr_uuid)

        # Handle optional dconf attributes
        self.transport = DEFAULT_TRANSPORT
        if self.dconf.has_key('useUDP') and self.dconf['useUDP'] == 'true':
            self.transport = "udp"
        self.nfsversion = nfs.validate_nfsversion(self.dconf.get('nfsversion'))
        if 'options' in self.dconf:
            self.options = self.dconf['options']
        else:
            self.options = ''
Пример #10
0
def detachThin(session, lvmCache, srUuid, vdiUuid):
    """Shrink the VDI to the minimal size if no one is using it"""
    lvName = LV_PREFIX[vhdutil.VDI_TYPE_VHD] + vdiUuid
    path = os.path.join(VG_LOCATION, VG_PREFIX + srUuid, lvName)
    lock = Lock(vhdutil.LOCK_TYPE_SR, srUuid)
    _tryAcquire(lock)

    vdiRef = session.xenapi.VDI.get_by_uuid(vdiUuid)
    vbds = session.xenapi.VBD.get_all_records_where( \
            "field \"VDI\" = \"%s\"" % vdiRef)
    numPlugged = 0
    for vbdRec in vbds.values():
        if vbdRec["currently_attached"]:
            numPlugged += 1

    if numPlugged > 1:
        raise util.SMException("%s still in use by %d others" % \
                (vdiUuid, numPlugged - 1))
    lvmCache.activate(NS_PREFIX_LVM + srUuid, vdiUuid, lvName, False)
    try:
        newSize = calcSizeLV(vhdutil.getSizePhys(path))
        deflate(lvmCache, lvName, newSize)
    finally:
        lvmCache.deactivate(NS_PREFIX_LVM + srUuid, vdiUuid, lvName, False)
    lock.release()
def test_release_free_resource():
    """
    TestCase Senario:
    trying to send a release request for a free resource which is not allowed
    so the wrong message response is expected.
    """
    #targeted resource and client_address
    resource_name = 'resourceX'
    client_address = '127.0.0.1'
    client_lock = Lock(resource_name, client_address)
    status = client_lock.check_status()

    #initiate socket s and send the release request for resourceX
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((HOST, PORT))
    s.sendall('release resourceX')
    data = s.recv(1024)

    #expecting error message as a response
    assert data == 'resource is already free.'

    # the status of the resource was free and still free
    assert client_lock.check_status() == 'free'

    #close the socket client
    s.close()
Пример #12
0
 def OnAddedToSpace(self, ballpark, dbspacecomponent):
     persister = Persister(ballpark.solarsystemID, self.itemID,
                           dbspacecomponent)
     bountyEscrowBonus, bounties = persister.GetStateForSystem()
     iskRegistry = IskRegistry(bounties)
     iskMover = IskMover(ballpark.broker.account)
     itemCreator = GetItemCreator(ballpark.inventory2, ballpark,
                                  self.attributes.tagTypeIDs.keys())
     escrow = Escrow(self, ballpark, iskRegistry, iskMover, itemCreator,
                     persister)
     item = ballpark.inventory2.GetItem(self.itemID)
     eventLogger = EventLogger(ballpark.broker.eventLog,
                               ballpark.solarsystemID, item.ownerID,
                               self.itemID)
     notifier = Notifier(ballpark.broker.notificationMgr)
     self.rangeNotifier = RangeNotifier(ballpark.solarsystemID, ballpark,
                                        ballpark.broker.machoNet,
                                        self.GetWallclockTime)
     ballpark.proximityRegistry.RegisterForProximity(
         self.itemID, 30000, self.rangeNotifier.PlayerInRange)
     lock = Lock(self)
     self.warpScrambler = WarpScrambler(self.itemID, lock, ballpark.dogmaLM)
     self.Initialize(ballpark, escrow, lock, persister, eventLogger,
                     notifier)
     self.escrow.SetBonus(bountyEscrowBonus)
Пример #13
0
 def get_agencies(cls, truncate=True):
     """
     Get a list of agencies
     """
     with Lock("agencies"):
         request_params = {
             'command': 'agencyList',
         }
         agencies_xml, api_call = cls.request(request_params, 'agency')
         if not agencies_xml:
             return []
         db.session.begin()
         if truncate:
             db.session.query(Agency).delete()
         agencies = []
         for agency in agencies_xml:
             region = Region.get_or_create(db.session,
                                           title=agency.get('regionTitle'))
             a = Agency.get_or_create(db.session,
                                      tag=agency.get('tag'),
                                      title=agency.get('title'),
                                      short_title=agency.get('shortTitle'),
                                      region=region,
                                      api_call=api_call)
             agencies.append(a)
         db.session.commit()
         return agencies
Пример #14
0
def daemonize(args, callback):
    with DaemonContext():
        from touchandgo.logger import log_set_up
        log_set_up(True)
        log = logging.getLogger('touchandgo.daemon')
        log.info("running daemon")
        create_process = False
        lock = Lock(LOCKFILE, os.getpid(), args.name, args.sea_ep[0],
                    args.sea_ep[1], args.port)
        if lock.is_locked():
            log.debug("lock active")
            lock_pid = lock.get_pid()
            if not lock.is_same_file(args.name, args.sea_ep[0],
                                     args.sea_ep[1]) \
                    or not is_process_running(lock_pid):
                try:
                    log.debug("killing process %s" % lock_pid)
                    os.kill(lock_pid, signal.SIGQUIT)
                except OSError:
                    pass
                except TypeError:
                    pass
                lock.break_lock()
                create_process = True
        else:
            create_process = True

        if create_process:
            log.debug("creating proccess")
            lock.acquire()
            callback()
            lock.release()
        else:
            log.debug("same daemon process")
Пример #15
0
 def testStateUnlocked(self):
     testState2: bool = False
     lock2 = Lock(state=testState2)
     lock2.set_needKey = testState2
     self.assertEqual(lock2._state,
                      False)  #It isn't being called here either
     self.assertEqual(lock2._needKey, False)
Пример #16
0
 def load(self, sr_uuid):
     self.ops_exclusive = OPS_EXCLUSIVE
     self.lock = Lock(vhdutil.LOCK_TYPE_SR, self.uuid)
     self.sr_vditype = vhdutil.VDI_TYPE_VHD
     if not self.dconf.has_key('location') or not self.dconf['location']:
         raise xs_errors.XenError('ConfigLocationMissing')
     self.path = self.dconf['location']
     self.attached = False
Пример #17
0
 def __init__(self, name, is_master_callback, lost_master_callback):
     self.lock = Lock(name,
                      lock_callback=self._lock,
                      lock_lost_callback=self._lost_lock)
     self.master_callback = is_master_callback
     self.lost_master_callback = lost_master_callback
     self.running = False
     self.condition = threading.Condition()
Пример #18
0
 def checkLocked(obj, ns):
     """Lock-protected access"""
     lock = Lock(obj, ns)
     lock.acquire()
     try:
         return RefCounter.check(obj, ns)
     finally:
         lock.release()
Пример #19
0
    def load(self, sr_uuid):
        self.ops_exclusive = FileSR.OPS_EXCLUSIVE
        self.lock = Lock(vhdutil.LOCK_TYPE_SR, self.uuid)
        self.sr_vditype = SR.DEFAULT_TAP

        self.path = os.path.join(SR.MOUNT_BASE, sr_uuid)
        self.vgname = EXT_PREFIX + sr_uuid
        self.remotepath = os.path.join("/dev", self.vgname, sr_uuid)
        self.attached = self._checkmount()
        self.driver_config = DRIVER_CONFIG
Пример #20
0
 def setReadonly(self, lvName, readonly):
     path = self._getPath(lvName)
     if self.lvs[lvName].readonly != readonly:
         uuids = util.findall_uuid(path)
         ns = lvhdutil.NS_PREFIX_LVM + uuids[0]
         lock = Lock(uuids[1], ns)
         lock.acquire()
         lvutil.setReadonly(path, readonly)
         lock.release()
         self.lvs[lvName].readonly = readonly
Пример #21
0
    def acquire_lock(self, sid, lock_type, tran_id):
        # Find the corresponding rid given the sid.
        if self.index[self.key].contains_key(sid):
            rid = self.index[self.key].locate(sid)[0]
        else:
            print("Acquire_Lock_Error: Provided SID is not valid!!!!!!!")
            return False

        self.lock.acquire()

        # If the record already has a lock list. Check if it contains a exclusive
        # lock and check if the exclusive lock belongs to the same transaction.
        if len(self.page_directory[rid]) == 3:
            # Shallow copy the lock list
            lock_list = self.page_directory[rid][2]
            # The lock list might be empty when we release all locks.
            # Doesn't mean there were no lock appended before.
            if lock_list.head is not None:
                if lock_list.has_exlock():
                    print("A:LKJF:LKAJFA")
                    if not lock_list.same_exlock_tranID(tran_id):
                        print(
                            "Adding lock after an exclusive lock. Lock appending failed and abort the transaction."
                        )
                        self.lock.release()
                        return False
                else:
                    if not lock_list.has_lock(tran_id, lock_type):
                        new_lock = Lock(lock_type, tran_id)
                        lock_list.append_list(new_lock)
            else:
                new_lock = Lock(lock_type, tran_id)
                lock_list.append_list(new_lock)

        # If the record doesn't have a lock list, make a lock list and append the lock.
        else:
            self.page_directory[rid].append(Lock_List())
            new_lock = Lock(lock_type, tran_id)
            self.page_directory[rid][2].append_list(new_lock)

        self.lock.release()
        return True
def test_lock_resourceX_then_close_connection():
    """
    TestCase Senario:
    the client try to lock the resourceX then this client close the connection.
    when the connection between the client and the server is down, the server should release the
    lock on the resourceX automatically
    """
    #targeted resource and client_address
    resource_name = 'resourceX'
    resource_id = get_resource_id_by_name(resource_name)[0]
    client_address = '127.0.0.1'
    client_lock = Lock(resource_name, client_address)
    status = client_lock.check_status()

    #initiate socket s and send the request access to resourceX
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((HOST, PORT))
    if status == 'free':
        s.sendall('lock resourceX')
        data = s.recv(1024)

        # make sure the access is granted
        assert data == 'You have an exclusive access to resource resourceX'
        assert client_lock.check_status() == 'busy'

        # make sure this operation stored into the db
        #select operations
        # client_ip_address, operation_time, operation_type
        operations = get_operations_by_resource_id(resource_id)
        assert len(operations) == 1
        assert operations[0][0] == client_address
        assert operations[0][2] == "lock"

        # the client terminate the connection
        s.close()

        #delete operations
        delete_operation_by_resource_id(resource_id)
    elif status == 'busy':
        s.sendall('lock resourceX')
        data = s.recv(1024)

        # make sure the resourceX is busy
        assert data == 'required resource is busy now, you have to wait a while'
        assert client_lock.check_status() == 'busy'

        # the client terminate the connection
        s.close()

    # sleep for 5 seconds to make sure the server cleaning up is done
    time.sleep(5)

    # make sure the server make resourceX free after the client terminates the connection
    assert client_lock.check_status() == 'free'
Пример #23
0
 def setReadonly(self, lvName, readonly):
     path = self._getPath(lvName)
     if self.lvs[lvName].readonly != readonly:
         uuids = util.findall_uuid(path)
         ns = lvhdutil.NS_PREFIX_LVM + uuids[0]
         # Taking this lock is needed to avoid a race condition
         # with tap-ctl open (which is now taking the same lock)
         lock = Lock("lvchange-p", ns)
         lock.acquire()
         lvutil.setReadonly(path, readonly)
         lock.release()
         self.lvs[lvName].readonly = readonly
Пример #24
0
 def __init__(self,
              woodType: str = DEFAULT_WOOD,
              height: float = DEFAULT_HEIGHT,
              width: float = DEFAULT_WIDTH,
              lockdiameter: float = Lock.DEFAULT_DIAMETER,
              state: bool = Lock.DEFAULT_STATE,
              handlediameter: float = Handle.DEFAULT_DIAMETER):
     self._woodType: str = woodType
     self._height: float = height
     self._width: float = width
     self._lock: Lock = Lock(lockdiameter)
     self._handle: Handle = Handle(handlediameter)
Пример #25
0
 def recoverSite(self):
     # reset timestamp:
     self.timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
     self.isRunning = True
     for ID in self.variables:
         self.lockTable[ID] = Lock()
     # note the isReplicated() here!
     for ID in self.isReady:
         if not self.isReplicated(ID):
             self.isReady[ID] = True
         else:
             self.isReady[ID] = False
Пример #26
0
    def __init__(self):
        self.pir = MyPiPIR(MyPiPIR.DEFAULT)
        self.led = MyPiLed(MyPiLed.RED)
        self.buzzer = MyPiBuzzer(MyPiBuzzer.DEFAULT)
        self.locks = []
        self.tries = 0
        self.max_tries = 3
        self.locks.append(Lock('Vault'))

        self.logger = MyLogger("SecuritySystem")
        self.check_interval = self.__class__.CHECK_INTERVAL
        self.enabled = False
Пример #27
0
    def load(self, sr_uuid):
        self.lock = Lock(vhdutil.LOCK_TYPE_SR, self.uuid)
        self.sr_vditype = SR.DEFAULT_TAP
        if not self.dconf.has_key('server'):
            raise xs_errors.XenError('ConfigServerMissing')
        self.remoteserver = self.dconf['server']
        self.path = os.path.join(SR.MOUNT_BASE, sr_uuid)

        # Test for the optional 'nfsoptions' dconf attribute
        self.transport = DEFAULT_TRANSPORT
        if self.dconf.has_key('useUDP') and self.dconf['useUDP'] == 'true':
            self.transport = "udp"
Пример #28
0
 def load(self, sr_uuid):
     self.ops_exclusive = OPS_EXCLUSIVE
     self.lock = Lock(vhdutil.LOCK_TYPE_SR, self.uuid)
     self.sr_vditype = vhdutil.VDI_TYPE_VHD
     if not self.dconf.has_key('location') or  not self.dconf['location']:
         raise xs_errors.XenError('ConfigLocationMissing')
     self.remotepath = self.dconf['location']
     self.path = os.path.join(SR.MOUNT_BASE, sr_uuid)
     self.linkpath = self.path
     self.mountpoint = self.path
     self.attached = False
     self.driver_config = DRIVER_CONFIG
Пример #29
0
 def activate(self, ns, ref, lvName, binary):
     lock = Lock(ref, ns)
     lock.acquire()
     try:
         count = RefCounter.get(ref, binary, ns)
         if count == 1:
             try:
                 self.activateNoRefcount(lvName)
             except util.CommandException:
                 RefCounter.put(ref, binary, ns)
                 raise
     finally:
         lock.release()
Пример #30
0
 def __init__(self, siteNum):
     self.isRunning = True
     self.isRecovered = True
     self.siteNum = siteNum
     # key: VariableID, value: Variable, this is for fast query data by ID
     self.variables = {}
     # key: VariableID, value: Lock(s)
     # Locks keep tracking of who locked, who is waiting and what's the current lock type.
     self.lockTable = {}
     # key: VariableID, value: boolean, ready or not
     # Note this isReady is to determine whether a variable's value is valid for read.
     self.isReady = {}
     self.timeStamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
     # initialize the site here.
     for i in range(1, 21):
         v = Variable(i)
         if i % 2 == 0:
             self.variables["x" + str(i)] = v
             self.lockTable["x" + str(i)] = Lock()
             self.isReady["x" + str(i)] = True
         elif (i + 1) % 10 == self.siteNum:
             self.variables["x" + str(i)] = v
             self.lockTable["x" + str(i)] = Lock()
             self.isReady["x" + str(i)] = True