Coverage for python/lsst/ctrl/bps/bps_config.py: 14%

Shortcuts on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

130 statements  

1# This file is part of ctrl_bps. 

2# 

3# Developed for the LSST Data Management System. 

4# This product includes software developed by the LSST Project 

5# (https://www.lsst.org). 

6# See the COPYRIGHT file at the top-level directory of this distribution 

7# for details of code ownership. 

8# 

9# This program is free software: you can redistribute it and/or modify 

10# it under the terms of the GNU General Public License as published by 

11# the Free Software Foundation, either version 3 of the License, or 

12# (at your option) any later version. 

13# 

14# This program is distributed in the hope that it will be useful, 

15# but WITHOUT ANY WARRANTY; without even the implied warranty of 

16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 

17# GNU General Public License for more details. 

18# 

19# You should have received a copy of the GNU General Public License 

20# along with this program. If not, see <https://www.gnu.org/licenses/>. 

21 

22"""Configuration class that adds order to searching sections for value, 

23expands environment variables and other config variables. 

24""" 

25 

26__all__ = ["BPS_SEARCH_ORDER", "BpsConfig", "BpsFormatter"] 

27 

28 

29from os.path import expandvars 

30import logging 

31import copy 

32import string 

33import re 

34from importlib.resources import path as resources_path 

35 

36from lsst.daf.butler.core.config import Config 

37 

38from . import etc 

39 

40_LOG = logging.getLogger(__name__) 

41 

42BPS_SEARCH_ORDER = ["bps_cmdline", "payload", "cluster", "pipetask", "site", "bps_defined"] 

43 

44# Need a string that won't be a valid default value 

45# to indicate whether default was defined for search. 

46# And None is a valid default value. 

47_NO_SEARCH_DEFAULT_VALUE = "__NO_SEARCH_DEFAULT_VALUE__" 

48 

49 

50class BpsFormatter(string.Formatter): 

51 """String formatter class that allows BPS config search options. 

52 """ 

53 def get_field(self, field_name, args, kwargs): 

54 _, val = args[0].search(field_name, opt=args[1]) 

55 return val, field_name 

56 

57 def get_value(self, key, args, kwargs): 

58 _, val = args[0].search(key, opt=args[1]) 

59 return val 

60 

61 

62class BpsConfig(Config): 

63 """Contains the configuration for a BPS submission. 

64 

65 Parameters 

66 ---------- 

67 other : `str`, `dict`, `Config`, `BpsConfig` 

68 Path to a yaml file or a dict/Config/BpsConfig containing configuration 

69 to copy. 

70 search_order : `list` [`str`], optional 

71 Root section names in the order in which they should be searched. 

72 """ 

73 def __init__(self, other, search_order=None): 

74 # In BPS config, the same setting can be defined multiple times in 

75 # different sections. The sections are search in a pre-defined 

76 # order. Hence, a value which is found first effectively overrides 

77 # values in later sections, if any. To achieve this goal, 

78 # the special methods __getitem__ and __contains__ were redefined to 

79 # use a custom search function internally. For this reason we can't 

80 # use super().__init__(other) as the super class defines its own 

81 # __getitem__ which is utilized during the initialization process ( 

82 # e.g. in expressions like self[<key>]). However, this function will 

83 # be overridden by the one defined here, in the subclass. Instead 

84 # we just initialize internal data structures and populate them 

85 # using the inherited update() method which does not rely on super 

86 # class __getitem__ method. 

87 super().__init__() 

88 

89 if isinstance(other, str): 

90 # First load default config from ctrl_bps, then override with 

91 # user config. 

92 with resources_path(etc, "bps_defaults.yaml") as bps_defaults: 

93 tmp_config = Config(str(bps_defaults)) 

94 user_config = Config(other) 

95 tmp_config.update(user_config) 

96 other = tmp_config 

97 if search_order is None: 

98 search_order = BPS_SEARCH_ORDER 

99 

100 try: 

101 config = Config(other) 

102 except RuntimeError: 

103 raise RuntimeError(f"A BpsConfig could not be loaded from other: {other}") 

104 self.update(config) 

105 

106 if isinstance(other, BpsConfig): 

107 self.search_order = copy.deepcopy(other.search_order) 

108 self.formatter = copy.deepcopy(other.formatter) 

109 else: 

110 if search_order is None: 

111 search_order = [] 

112 self.search_order = search_order 

113 self.formatter = BpsFormatter() 

114 

115 # Make sure search sections exist 

116 for key in self.search_order: 

117 if not Config.__contains__(self, key): 

118 self[key] = {} 

119 

120 def copy(self): 

121 """Make a copy of config. 

122 

123 Returns 

124 ------- 

125 copy : `lsst.ctrl.bps.BpsConfig` 

126 A duplicate of itself. 

127 """ 

128 return BpsConfig(self) 

129 

130 def __getitem__(self, name): 

131 """Return the value from the config for the given name. 

132 

133 Parameters 

134 ---------- 

135 name : `str` 

136 Key to look for in config 

137 

138 Returns 

139 ------- 

140 val : `str`, `int`, `lsst.ctrl.bps.BpsConfig`, ... 

141 Value from config if found. 

142 """ 

143 _, val = self.search(name, {}) 

144 

145 return val 

146 

147 def __contains__(self, name): 

148 """Check whether name is in config. 

149 

150 Parameters 

151 ---------- 

152 name : `str` 

153 Key to look for in config. 

154 

155 Returns 

156 ------- 

157 found : `bool` 

158 Whether name was in config or not. 

159 """ 

160 found, _ = self.search(name, {}) 

161 return found 

162 

163 def search(self, key, opt=None): 

164 """Search for key using given opt following hierarchy rules. 

165 

166 Search hierarchy rules: current values, a given search object, and 

167 search order of config sections. 

168 

169 Parameters 

170 ---------- 

171 key : `str` 

172 Key to look for in config. 

173 opt : `dict` [`str`, `Any`], optional 

174 Options dictionary to use while searching. All are optional. 

175 

176 ``"curvals"`` 

177 Means to pass in values for search order key 

178 (curr_<sectname>) or variable replacements. 

179 (`dict`, optional) 

180 ``"default"`` 

181 Value to return if not found. (`Any`, optional) 

182 ``"replaceEnvVars"`` 

183 If search result is string, whether to replace environment 

184 variables inside it with special placeholder (<ENV:name>). 

185 By default set to False. (`bool`) 

186 ``"expandEnvVars"`` 

187 If search result is string, whether to replace environment 

188 variables inside it with current environment value. 

189 By default set to False. (`bool`) 

190 ``"replaceVars"`` 

191 If search result is string, whether to replace variables 

192 inside it. By default set to True. (`bool`) 

193 ``"required"`` 

194 If replacing variables, whether to raise exception if 

195 variable is undefined. By default set to False. (`bool`) 

196 

197 Returns 

198 ------- 

199 found : `bool` 

200 Whether name was in config or not. 

201 value : `str`, `int`, `lsst.ctrl.bps.BpsConfig`, ... 

202 Value from config if found. 

203 """ 

204 _LOG.debug("search: initial key = '%s', opt = '%s'", key, opt) 

205 

206 if opt is None: 

207 opt = {} 

208 

209 found = False 

210 value = "" 

211 

212 # start with stored current values 

213 curvals = None 

214 if Config.__contains__(self, "current"): 

215 curvals = copy.deepcopy(Config.__getitem__(self, "current")) 

216 else: 

217 curvals = {} 

218 

219 # override with current values passed into function if given 

220 if "curvals" in opt: 

221 for ckey, cval in list(opt["curvals"].items()): 

222 _LOG.debug("using specified curval %s = %s", ckey, cval) 

223 curvals[ckey] = cval 

224 

225 _LOG.debug("curvals = %s", curvals) 

226 

227 # There's a problem with the searchobj being a BpsConfig 

228 # and its handling of __getitem__. Until that part of 

229 # BpsConfig is rewritten, force the searchobj to a Config. 

230 if "searchobj" in opt: 

231 opt["searchobj"] = Config(opt["searchobj"]) 

232 

233 if key in curvals: 

234 _LOG.debug("found %s in curvals", key) 

235 found = True 

236 value = curvals[key] 

237 elif "searchobj" in opt and key in opt["searchobj"]: 

238 found = True 

239 value = opt["searchobj"][key] 

240 else: 

241 for sect in self.search_order: 

242 if Config.__contains__(self, sect): 

243 _LOG.debug("Searching '%s' section for key '%s'", sect, key) 

244 search_sect = Config.__getitem__(self, sect) 

245 if "curr_" + sect in curvals: 

246 currkey = curvals["curr_" + sect] 

247 _LOG.debug("currkey for section %s = %s", sect, currkey) 

248 if Config.__contains__(search_sect, currkey): 

249 search_sect = Config.__getitem__(search_sect, currkey) 

250 

251 _LOG.debug("%s %s", key, search_sect) 

252 if Config.__contains__(search_sect, key): 

253 found = True 

254 value = Config.__getitem__(search_sect, key) 

255 break 

256 else: 

257 _LOG.debug("Missing search section '%s' while searching for '%s'", sect, key) 

258 

259 # lastly check root values 

260 if not found: 

261 _LOG.debug("Searching root section for key '%s'", key) 

262 if Config.__contains__(self, key): 

263 found = True 

264 value = Config.__getitem__(self, key) 

265 _LOG.debug("root value='%s'", value) 

266 

267 if not found and "default" in opt: 

268 value = opt["default"] 

269 found = True # ???? 

270 

271 if not found and opt.get("required", False): 

272 print(f"\n\nError: search for {key} failed") 

273 print("\tcurrent = ", self.get("current")) 

274 print("\topt = ", opt) 

275 print("\tcurvals = ", curvals) 

276 print("\n\n") 

277 raise KeyError(f"Error: Search failed {key}") 

278 

279 _LOG.debug("found=%s, value=%s", found, value) 

280 

281 _LOG.debug("opt=%s %s", opt, type(opt)) 

282 if found and isinstance(value, str): 

283 if opt.get("expandEnvVars", True): 

284 _LOG.debug("before format=%s", value) 

285 value = re.sub(r"<ENV:([^>]+)>", r"$\1", value) 

286 value = expandvars(value) 

287 elif opt.get("replaceEnvVars", False): 

288 value = re.sub(r"\${([^}]+)}", r"<ENV:\1>", value) 

289 value = re.sub(r"\$(\S+)", r"<ENV:\1>", value) 

290 

291 if opt.get("replaceVars", True): 

292 # default only applies to original search key 

293 # Instead of doing deep copies of opt (especially with 

294 # the recursive calls), temporarily remove default value 

295 # and put it back. 

296 default = opt.pop("default", _NO_SEARCH_DEFAULT_VALUE) 

297 

298 # Temporarily replace any env vars so formatter doesn't try to 

299 # replace them. 

300 value = re.sub(r"\${([^}]+)}", r"<BPSTMP:\1>", value) 

301 

302 value = self.formatter.format(value, self, opt) 

303 

304 # Replace any temporary env place holders. 

305 value = re.sub(r"<BPSTMP:([^>]+)>", r"${\1}", value) 

306 

307 # if default was originally in opt 

308 if default != _NO_SEARCH_DEFAULT_VALUE: 

309 opt["default"] = default 

310 

311 _LOG.debug("after format=%s", value) 

312 

313 if found and isinstance(value, Config): 

314 value = BpsConfig(value) 

315 

316 return found, value