Skip to content

Instantly share code, notes, and snippets.

@emilroz
Last active August 29, 2015 14:11
Show Gist options
  • Save emilroz/89a5dc77b663d8c1a9c1 to your computer and use it in GitHub Desktop.
Save emilroz/89a5dc77b663d8c1a9c1 to your computer and use it in GitHub Desktop.
Check for permission issues with thumbnails.
'''
Copyright (C) 2014 Glencoe Software, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'''
import omero
from omero.gateway import BlitzGateway
from omero.rtypes import rlong, rint
from datetime import datetime
import math
import sys
from omero_ext import argparse
import logging
import logging.handlers
handler = logging.StreamHandler()
FORMAT = "%(asctime)s %(levelname)-7s [%(name)16s] %(message)s"
handler.setFormatter(logging.Formatter(FORMAT))
logger = logging.getLogger("")
logger.setLevel(logging.INFO)
logger.addHandler(handler)
def findDirtyThumbs(offset, number, userId, queryService, ctx, dirtyList):
params = omero.sys.ParametersI()
params.addId(userId)
params.page(offset, number)
pixelsQuery = "select p.id from Pixels as p " \
"where p.details.owner.id = :id " \
"order by p.id desc"
pixelsIds = queryService.projection(pixelsQuery, params, ctx)
pixelsIds = [p[0] for p in pixelsIds]
paramsThumbs = omero.sys.ParametersI()
paramsThumbs.addIds(pixelsIds)
paramsThumbs.add("oid", rlong(userId))
thumbnailQuery = "select t.id, t.pixels.id, t.details.updateEvent.time " \
"from Thumbnail as t " \
"where t.pixels.id in (:ids) " \
"and t.details.owner.id = :oid " \
"order by t.pixels.id desc"
thumbs = queryService.projection(thumbnailQuery, paramsThumbs, ctx)
paramsRender = omero.sys.ParametersI()
paramsRender.addIds(pixelsIds)
paramsRender.add("oid", rlong(userId))
renderDefQuery = "select r.id, r.pixels.id, r.details.updateEvent.time " \
"from RenderingDef as r " \
"where r.pixels.id in (:ids) " \
"and r.details.owner.id = :oid " \
"order by r.pixels.id desc"
renderingDefs = queryService.projection(renderDefQuery, paramsRender, ctx)
thumbs = dict(
[(thumb[1].val, [thumb[0].val, thumb[2].val]) for thumb in thumbs])
renderingDefs = dict(
[(renderingDef[1].val, [renderingDef[0].val, renderingDef[2].val])
for renderingDef in renderingDefs])
counter = 0
for ID in pixelsIds:
if ID.val not in thumbs:
counter += 1
logger.warning(("%i No thumb for %i" % (counter, ID.val)))
dirtyList.append(ID.val)
continue
if ID.val not in renderingDefs:
counter += 1
logger.warning(("%i No renderingDef for %i"
% (counter, ID.val)))
dirtyList.append(ID.val)
continue
timeThumb = datetime.fromtimestamp(thumbs[ID.val][1] / 1000.0)
timeRenderingDef = datetime.fromtimestamp(renderingDefs[ID.val][1]
/ 1000.0)
if timeRenderingDef > timeThumb:
counter += 1
logger.warning(("%i Timestamp issue for %i"
% (counter, ID.val)))
dirtyList.append(ID.val)
logger.info(("Batch Done. Dirt found: %i" % len(dirtyList)))
def refreshDirtyThumbs(dirtyList, thumbnailStore):
step = 100.0
logger.info(("Refreshing thumbnails in batches of %i" % step))
numberOfDirts = len(dirtyList)
if numberOfDirts < step:
thumbnailStore.getThumbnailByLongestSideSet(rint(96), dirtyList)
else:
numberOfBatches = int(math.ceil(numberOfDirts / step))
logger.info(("Refreshing thumbnails in %i batches."
% numberOfBatches))
step = int(step)
for i in range(numberOfBatches):
logger.info(("Refreshing thumbnails batch: %i" % i))
if i * step > numberOfDirts:
break
thumbnailStore. \
getThumbnailByLongestSideSet(
rint(96), dirtyList[i * step: (i + 1) * step])
logger.info(("%i thumbnails refreshed" % numberOfDirts))
def checkThumbnails(conn, args, logger):
adminService = conn.getAdminService()
groups = adminService.lookupGroups()
group = filter(lambda x: x.name.val == args.g, groups)[0]
user = conn.getUser()
logger.info("Connected as user: %i, fixing group: %i"
% (user.id, group.id.val))
conn.setGroupForSession(group.id.val)
queryService = conn.getQueryService()
thumbnailStore = conn.createThumbnailStore()
ctx = {'omero.group': '%d' % group.id.val}
params = omero.sys.ParametersI()
params.addId(user.getId())
params.add("gid", rlong(group.id.val))
countQuery = "select count(p) from Pixels as p " \
"where p.details.owner.id = :id " \
"and p.details.group.id = :gid"
count = queryService.projection(countQuery, params, ctx)[0][0].val
step = 1000.0
numberOfBatches = int(math.ceil(count / step))
dirtyList = []
totalDirt = 0
for i in range(numberOfBatches - 1):
logger.info(("Looking for dirt in batch %i" % i))
findDirtyThumbs(i * step, step, user.getId(),
queryService, ctx, dirtyList)
if len(dirtyList) > 0:
totalDirt += len(dirtyList)
if not args.no_refresh:
refreshDirtyThumbs(dirtyList, thumbnailStore)
dirtyList = []
logger.info(("Proccessed dirt: %i" % totalDirt))
def parseArguments(parser):
parser.add_argument('-s', help='server')
parser.add_argument('-p', default='4064', help='port', type=int)
parser.add_argument('-u', help='user')
parser.add_argument('-w', help='password')
parser.add_argument('-g',
help='Group name to interogate')
parser.add_argument('-d', help='change logging level to debug',
action='store_true')
parser.add_argument('--no_refresh', help='Just print to console',
action='store_true')
return parser.parse_args()
parser = argparse.ArgumentParser()
args = parseArguments(parser)
if __name__ == "__main__":
if args.d:
logger.setLevel(logging.DEBUG)
conn = BlitzGateway(args.u, args.w,
host=args.s, port=args.p)
connected = conn.connect()
if not connected:
logger.info("Connection failed, check connection details.")
sys.exit(1)
try:
conn.keepAlive()
checkThumbnails(conn, args, logger)
finally:
conn._closeSession()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment