Hide keyboard shortcuts

Hot-keys 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

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", "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 

98 try: 

99 config = Config(other) 

100 except RuntimeError: 

101 raise RuntimeError("A BpsConfig could not be loaded from other: %s" % other) 

102 self.update(config) 

103 

104 if isinstance(other, BpsConfig): 

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

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

107 else: 

108 if search_order is None: 

109 search_order = [] 

110 self.search_order = search_order 

111 self.formatter = BpsFormatter() 

112 

113 # Make sure search sections exist 

114 for key in self.search_order: 

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

116 self[key] = {} 

117 

118 def copy(self): 

119 """Make a copy of config. 

120 

121 Returns 

122 ------- 

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

124 A duplicate of itself. 

125 """ 

126 return BpsConfig(self) 

127 

128 def __getitem__(self, name): 

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

130 

131 Parameters 

132 ---------- 

133 name : `str` 

134 Key to look for in config 

135 

136 Returns 

137 ------- 

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

139 Value from config if found. 

140 """ 

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

142 

143 return val 

144 

145 def __contains__(self, name): 

146 """Check whether name is in config. 

147 

148 Parameters 

149 ---------- 

150 name : `str` 

151 Key to look for in config. 

152 

153 Returns 

154 ------- 

155 found : `bool` 

156 Whether name was in config or not. 

157 """ 

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

159 return found 

160 

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

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

163 

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

165 search order of config sections. 

166 

167 Parameters 

168 ---------- 

169 key : `str` 

170 Key to look for in config. 

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

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

173 

174 ``"curvals"`` 

175 Means to pass in values for search order key 

176 (curr_<sectname>) or variable replacements. 

177 (`dict`, optional) 

178 ``"default"`` 

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

180 ``"replaceEnvVars"`` 

181 If search result is string, whether to replace environment 

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

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

184 ``"expandEnvVars"`` 

185 If search result is string, whether to replace environment 

186 variables inside it with current environment value. 

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

188 ``"replaceVars"`` 

189 If search result is string, whether to replace variables 

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

191 ``"required"`` 

192 If replacing variables, whether to raise exception if 

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

194 

195 Returns 

196 ------- 

197 found : `bool` 

198 Whether name was in config or not. 

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

200 Value from config if found. 

201 """ 

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

203 

204 if opt is None: 

205 opt = {} 

206 

207 found = False 

208 value = "" 

209 

210 # start with stored current values 

211 curvals = None 

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

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

214 else: 

215 curvals = {} 

216 

217 # override with current values passed into function if given 

218 if "curvals" in opt: 

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

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

221 curvals[ckey] = cval 

222 

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

224 

225 if key in curvals: 

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

227 found = True 

228 value = curvals[key] 

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

230 found = True 

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

232 else: 

233 for sect in self.search_order: 

234 if Config.__contains__(self, sect): 

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

236 search_sect = Config.__getitem__(self, sect) 

237 if "curr_" + sect in curvals: 

238 currkey = curvals["curr_" + sect] 

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

240 if Config.__contains__(search_sect, currkey): 

241 search_sect = Config.__getitem__(search_sect, currkey) 

242 

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

244 if Config.__contains__(search_sect, key): 

245 found = True 

246 value = Config.__getitem__(search_sect, key) 

247 break 

248 else: 

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

250 

251 # lastly check root values 

252 if not found: 

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

254 if Config.__contains__(self, key): 

255 found = True 

256 value = Config.__getitem__(self, key) 

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

258 

259 if not found and "default" in opt: 

260 value = opt["default"] 

261 found = True # ???? 

262 

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

264 print("\n\nError: search for %s failed" % (key)) 

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

266 print("\topt = ", opt) 

267 print("\tcurvals = ", curvals) 

268 print("\n\n") 

269 raise KeyError("Error: Search failed (%s)" % key) 

270 

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

272 

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

274 if found and isinstance(value, str): 

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

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

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

278 value = expandvars(value) 

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

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

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

282 

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

284 # default only applies to original search key 

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

286 # the recursive calls), temporarily remove default value 

287 # and put it back. 

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

289 

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

291 # replace them. 

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

293 

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

295 

296 # Replace any temporary env place holders. 

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

298 

299 # if default was originally in opt 

300 if default != _NO_SEARCH_DEFAULT_VALUE: 

301 opt["default"] = default 

302 

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

304 

305 if found and isinstance(value, Config): 

306 value = BpsConfig(value) 

307 

308 return found, value