Example #1
0
    def cluster_id(self, path, readonly=False):
        dirpath = os.path.dirname(os.path.abspath(path))
        log.info('Opening {} for locking'.format(dirpath))
        with utils.Directory(dirpath) as d:
            log.info('Taking exclusive lock on {}'.format(dirpath))
            with d.lock():
                if readonly:
                    zkid = None
                else:
                    zkid = str(uuid.uuid4()).encode('ascii')

                zkid = self._consensus('/cluster-id', zkid, ANYONE_READ)
                zkid = zkid.decode('ascii')

                if os.path.exists(path):
                    fileid = utils.read_file_line(path)
                    if fileid == zkid:
                        log.info(
                            'Cluster ID in ZooKeeper and file are the same: {}'
                            .format(zkid))
                        return zkid

                log.info(
                    'Writing cluster ID from ZK to {} via rename'.format(path))

                tmppath = path + '.tmp'
                with open(tmppath, 'w') as f:
                    f.write(zkid + '\n')
                os.rename(tmppath, path)

                log.info('Wrote cluster ID to {}'.format(path))

                return zkid
Example #2
0
def _write_file(path, data, mode, owner='root'):
    dirpath = os.path.dirname(os.path.abspath(path))
    log.info('Opening {} for locking'.format(dirpath))
    with utils.Directory(dirpath) as d:
        log.info('Taking exclusive lock on {}'.format(dirpath))
        with d.lock():
            umask_original = os.umask(0)
            try:
                flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC
                log.info('Writing {} with mode {:o}'.format(path, mode))
                tmppath = path + '.tmp'
                with os.fdopen(os.open(tmppath, flags, mode), 'wb') as f:
                    f.write(data)
                os.rename(tmppath, path)
                user = pwd.getpwnam(owner)
                os.chown(path, user.pw_uid, user.pw_gid)
            finally:
                os.umask(umask_original)