Debian Codegraph @

biomaj/schema_version.py

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 import pkg_resources
2 import string
3 import random
4 import os
5 import sys
6 from biomaj.bank import Bank
7 from biomaj.mongo_connector import MongoConnector
8 from biomaj_core.config import BiomajConfig
9 from biomaj_core.utils import Utils
10
11 import logging
12
13
14 class SchemaVersion:
15
16 """
17 BioMAJ database schema version. This package can be used to make some schema modification if needed during
18 incremental software version.
19 """
20
21 VERSION = None
22
23 @staticmethod
24 def migrate_pendings():
25 """
26 Migrate database
27
28 3.0.18: Check the actual BioMAJ version and if older than 3.0.17, do the 'pending' key migration
29 """
30 if BiomajConfig.global_config is None:
31 try:
32 BiomajConfig.load_config()
33 except Exception as err:
34 print("* SchemaVersion: Can't find config file: " + str(err))
35 return None
36 if MongoConnector.db is None:
37 MongoConnector(BiomajConfig.global_config.get('GENERAL', 'db.url'),
38 BiomajConfig.global_config.get('GENERAL', 'db.name'))
39
40 schema = MongoConnector.db_schema
41 banks = MongoConnector.banks
42 users = MongoConnector.users
43 schema_version = SchemaVersion.get_dbschema_version(schema)
44 moderate = int(schema_version.split('.')[1])
45 minor = int(schema_version.split('.')[2])
46
47 if moderate == 0 and minor <= 17:
48 print("Migrate from release: %s" % schema_version)
49 # Update pending releases
50 bank_list = banks.find()
51 updated = 0
52 for bank in bank_list:
53 if 'pending' in bank:
54 # Check we have an old pending type
55 if type(bank['pending']) == dict:
56 updated += 1
57 pendings = []
58 for release in sorted(bank['pending'], key=lambda r: bank['pending'][r]):
59 pendings.append({'release': str(release), 'id': bank['pending'][str(release)]})
60 if len(pendings) > 0:
61 banks.update({'name': bank['name']},
62 {'$set': {'pending': pendings}})
63 else:
64 # We remove old type for 'pending'
65 banks.update({'name': bank['name']},
66 {'$unset': {'pending': ""}})
67
68 print("Migration: %d bank(s) updated" % updated)
69 if moderate < 1:
70 updated = 0
71 user_list = users.find()
72 for user in user_list:
73 if 'apikey' not in user:
74 updated += 1
75 api_key = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(10))
76 users.update({'_id': user['_id']}, {'$set': {'apikey': api_key}})
77 print("Migration: %d user(s) updated" % updated)
78 # production size
79 bank_list = banks.find()
80 updated = 0
81 for bank in bank_list:
82 for prod in bank['production']:
83 '''
84 { "_id" : ObjectId("54edb10856e8bb11340b5f51"), "production" : [
85 { "freeze" : false, "remoterelease" : "2003-11-26", "session" : 1427809848.560108,
86 "data_dir" : "/db", "formats" : [ ], "release" : "2003-11-26",
87 "dir_version" : "ncbi/blast/alu",
88 "prod_dir" : "alu-2003-11-26", "types" : [ ], "size" : 319432 } ] }
89 '''
90 if 'size' not in prod or prod['size'] == 0:
91 logging.info('Calculate size for bank %s' % (bank['name']))
92 if 'data_dir' not in prod or not prod['data_dir'] or 'prod_dir' not in prod or not prod['prod_dir'] or 'dir_version' not in prod or not prod['dir_version']:
93 logging.warn('no production directory information for %s, skipping...' % (bank['name']))
94 continue
95 prod_dir = os.path.join(prod['data_dir'], prod['dir_version'], prod['prod_dir'])
96 if not os.path.exists(prod_dir):
97 logging.warn('production directory %s does not exists for %s, skipping...' % (prod_dir, bank['name']))
98 continue
99 dir_size = Utils.get_folder_size(prod_dir)
100 banks.update({'name': bank['name'], 'production.release': prod['release']}, {'$set': {'production.$.size': dir_size}})
101 updated += 1
102 print("Migration: %d bank production info updated" % updated)
103
104 @staticmethod
105 def add_property(bank=None, prop=None, value=None, cfg=None):
106 """
107 Update properties field for banks.
108
109 :param bank: Bank name to update, default all
110 :type bank: str
111 :param prop: New property to add
112 :type prop: str
113 :param value: Property value, if cfg set, value taken
114 from bank configuration cfg key
115 :type value: str
116 :param cfg: Bank configuration key value is taken from
117 :type cfg: str
118
119 :raise Exception: If not configuration file found
120 :returns: True/False
121 :rtype: bool
122 """
123 if BiomajConfig.global_config is None:
124 try:
125 BiomajConfig.load_config()
126 except Exception as err:
127 print("* SchemaVersion: Can't find config file: " + str(err))
128 return False
129 if prop is None:
130 print("Property key is required", file=sys.stderr)
131 return False
132
133 if MongoConnector.db is None:
134 MongoConnector(BiomajConfig.global_config.get('GENERAL', 'db.url'),
135 BiomajConfig.global_config.get('GENERAL', 'db.name'))
136
137 schema = MongoConnector.db_schema
138 banks = MongoConnector.banks
139 schema_version = SchemaVersion.get_dbschema_version(schema)
140 moderate = int(schema_version.split('.')[1])
141 minor = int(schema_version.split('.')[2])
142
143 if moderate <= 1 and minor <= 0:
144 bank_list = []
145 if bank is None:
146 bank_list = banks.find()
147 else:
148 bank_list = [banks.find_one({'name': bank})]
149 updated = 0
150 for bank in bank_list:
151 if 'properties' in bank:
152 b = Bank(bank['name'], no_log=True)
153 new_prop = 'properties.' + prop
154 new_value = value
155 if new_value is None:
156 if cfg is not None:
157 new_value = b.config.get(cfg)
158 else:
159 print("[%s] With value set to None, you must set cfg to get "
160 "corresponding value" % str(bank['name']), file=sys.stderr)
161 continue
162 banks.update({'name': bank['name']},
163 {'$set': {new_prop: new_value}})
164 updated += 1
165 else:
166 logging.warn("Bank %s does not have 'properties' field!" % str(bank['name']))
167
168 print("Add property: %d bank(s) updated" % updated)
169
170 @staticmethod
171 def get_dbschema_version(schema):
172 """
173 Get the version of the actual schema version stored in database
174
175 :param schema: Mongo schema info
176 :type schema: MongoDB collection
177 :returns: moderate, minor
178 :rtype: int, int
179
180 """
181 schema_version = schema.find_one({'id': 1})
182 if schema_version is None:
183 schema_version = {'id': 1, 'version': '3.0.0'}
184 schema.insert(schema_version)
185 return schema_version['version']
186
187 @staticmethod
188 def set_version(version=None):
189 """
190 Set BioMAJ current installed version in db_schema collection if version is None
191
192 :param version: db_schema collection version to set
193 :type version: str
194 """
195 installed_version = version
196 if installed_version is None:
197 installed_version = pkg_resources.get_distribution("biomaj").version
198 if BiomajConfig.global_config is None:
199 try:
200 BiomajConfig.load_config()
201 except Exception as err:
202 print("* SchemaVersion: Can't find config file: " + str(err))
203 return None
204 if MongoConnector.db is None:
205 MongoConnector(BiomajConfig.global_config.get('GENERAL', 'db.url'),
206 BiomajConfig.global_config.get('GENERAL', 'db.name'))
207 schema = MongoConnector.db_schema
208 schema.update_one({'id': 1}, {'$set': {'version': installed_version}})
209 print("Schema version set to %s" % str(installed_version))