<s> """<STR_LIT>""" <EOL> from changes . config import db <EOL> from changes . models import CachedSnapshotImage , Plan , PlanStatus , Snapshot , SnapshotImage , Step <EOL> from datetime import datetime <EOL> from flask import current_app <EOL> import sqlalchemy <EOL> def get_current_datetime ( ) : <EOL> """<STR_LIT>""" <EOL> return datetime . utcnow ( ) <EOL> def get_plans_for_cluster ( cluster ) : <EOL> """<STR_LIT>""" <EOL> plans = set ( ) <EOL> q = db . session . query ( Plan , Step ) <EOL> q = q . filter ( Plan . id == Step . plan_id , Plan . status == PlanStatus . active ) <EOL> for plan , step in q . all ( ) : <EOL> if step . data and step . data . get ( '<STR_LIT>' , None ) == cluster : <EOL> plans . add ( plan ) <EOL> return plans <EOL> def get_cached_snapshot_images ( cluster ) : <EOL> """<STR_LIT>""" <EOL> now = get_current_datetime ( ) <EOL> plan_ids = [ plan . id for plan in get_plans_for_cluster ( cluster ) ] <EOL> if not plan_ids : <EOL> return [ ] <EOL> return db . session . query ( SnapshotImage ) . filter ( <EOL> sqlalchemy . or_ ( <EOL> CachedSnapshotImage . expiration_date == None , <EOL> now <= CachedSnapshotImage . expiration_date , <EOL> ) , <EOL> CachedSnapshotImage . id == SnapshotImage . id , <EOL> SnapshotImage . plan_id . in_ ( plan_ids ) <EOL> ) . all ( ) <EOL> def _cache_image ( snapshot_image ) : <EOL> """<STR_LIT>""" <EOL> return db . session . merge ( <EOL> CachedSnapshotImage ( id = snapshot_image . id , expiration_date = None ) <EOL> ) <EOL> def cache_snapshot ( snapshot ) : <EOL> """<STR_LIT>""" <EOL> now = get_current_datetime ( ) <EOL> CachedSnapshotImage . query . filter ( <EOL> CachedSnapshotImage . expiration_date == None , <EOL> CachedSnapshotImage . id == SnapshotImage . id , <EOL> SnapshotImage . snapshot_id == Snapshot . id , <EOL> Snapshot . project_id == snapshot . project_id <EOL> ) . update ( dict ( expiration_date = now + current_app . config [ '<STR_LIT>' ] ) ) <EOL> images = SnapshotImage . query . filter ( SnapshotImage . snapshot_id == snapshot . id ) <EOL> cached_snapshot_images = [ _cache_image ( image ) for image in images ] <EOL> db . session . add_all ( cached_snapshot_images ) <EOL> db . session . commit ( ) <EOL> def get_relevant_snapshot_images ( snapshot_id ) : <EOL> """<STR_LIT>""" <EOL> steps = Step . query . filter ( <EOL> Plan . id == SnapshotImage . plan_id , <EOL> Step . plan_id == Plan . id , <EOL> SnapshotImage . snapshot_id == snapshot_id <EOL> ) . all ( ) <EOL> clusters = set ( ) <EOL> for step in steps : <EOL> if step . data and '<STR_LIT>' in step . data : <EOL> clusters . add ( step . data [ '<STR_LIT>' ] ) <EOL> return dict ( [ ( cluster , get_cached_snapshot_images ( cluster ) ) for cluster in clusters ] ) <EOL> def clear_expired ( ) : <EOL> """<STR_LIT>""" <EOL> now = get_current_datetime ( ) <EOL> CachedSnapshotImage . query . filter ( <EOL> CachedSnapshotImage . expiration_date < now <EOL> ) . delete ( ) <EOL> db . session . commit ( ) </s>
