Package omero :: Package plugins :: Module prefs
[hide private]
[frames] | no frames]

Source Code for Module omero.plugins.prefs

  1  #!/usr/bin/env python 
  2  """ 
  3     prefs plugin 
  4   
  5     Plugin read by omero.cli.Cli during initialization. The method(s) 
  6     defined here will be added to the Cli class for later use. 
  7   
  8     The pref plugin makes use of prefs.class from the common component. 
  9   
 10     Copyright 2007 Glencoe Software, Inc. All rights reserved. 
 11     Use is subject to license terms supplied in LICENSE.txt 
 12   
 13  """ 
 14   
 15  import sys, os 
 16  import portalocker 
 17   
 18  from exceptions import Exception 
 19  from path import path 
 20  from omero.cli import CLI 
 21  from omero.cli import BaseControl 
 22  from omero.config import ConfigXml 
 23  from omero_ext.argparse import FileType 
 24  from omero_ext.strings import shlex 
 25  from omero.util import edit_path, get_user_dir 
 26  from omero.util.decorators import wraps 
 27  import omero.java 
 28   
 29  HELP="""Commands for server configuration. 
 30   
 31  A config.xml file will be modified under your etc/grid 
 32  directory. If you do not have one, "upgrade" will create 
 33  a new 4.2 configuration file. 
 34   
 35  The configuration values are used by bin/omero admin {start,deploy} 
 36  to set properties on launch. See etc/grid/(win)default.xml. The "Profile" 
 37  block contains a reference to "__ACTIVE__" which is the current value 
 38  in config.xml 
 39   
 40  Environment variables: 
 41      OMERO_CONFIG - Changes the active profile 
 42   
 43  """ 
44 45 -def getprefs(args, dir):
46 """ 47 Kept around temporarily for upgrading users from pre-4.2 configurations. 48 """ 49 if not isinstance(args,list): 50 raise Exception("Not a list") 51 cmd = ["prefs"]+list(args) 52 return omero.java.run(cmd, chdir=dir)
53
54 -def with_config(func):
55 """ 56 opens a config and passes it as the second argument. 57 """ 58 def open_and_close_config(*args, **kwargs): 59 args = list(args) 60 self = args[0] 61 argp = args[1] 62 config = None 63 if len(args) == 2: 64 config = self.open_config(argp) 65 args.append(config) 66 try: 67 return func(*args, **kwargs) 68 finally: 69 if config: 70 config.close()
71 return wraps(func)(open_and_close_config) 72
73 74 -class PrefsControl(BaseControl):
75
76 - def _configure(self, parser):
77 parser.add_argument("--source", help=""" 78 Which configuration file should be used. By default, OMERO.grid 79 will use the file in etc/grid/config.xml. If you would like to 80 configure your system to use $HOME/omero/config.xml, you will 81 need to modify the application descriptor. 82 """) 83 84 sub = parser.sub() 85 86 all = sub.add_parser("all", help="""List all properties in the current config.xml file.""") 87 all.set_defaults(func=self.all) 88 89 default = sub.add_parser("def", help="""List (or set) the current properties. See 'all' for a list of available properties.""") 90 default.set_defaults(func=self.default) 91 default.add_argument("NAME", nargs="?", help="""Name of the profile which should be made the new active profile.""") 92 93 get = sub.add_parser("get", help="""Get keys from the current profile. All by default""") 94 get.set_defaults(func=self.get) 95 get.add_argument("KEY", nargs="*") 96 97 set = sub.add_parser("set", help="""Set key-value pair in the current profile. Omit the value to remove the key.""") 98 set.set_defaults(func=self.set) 99 set.add_argument("KEY") 100 set.add_argument("VALUE", nargs="?", help="Value to be set. If it is missing, the key will be removed") 101 102 drop = sub.add_parser("drop", help="""Removes the profile from the configuration file""") 103 drop.set_defaults(func=self.drop) 104 drop.add_argument("NAME") 105 106 keys = sub.add_parser("keys", help="""List all keys for the current profile""") 107 keys.set_defaults(func=self.keys) 108 109 load = sub.add_parser("load", help="""Read into current profile from a file or standard in""") 110 load.set_defaults(func=self.load) 111 load.add_argument("-q", action="store_true", help="No error on conflict") 112 load.add_argument("file", nargs="+", type=FileType('r'), default=sys.stdin, help="Read from files or standard in") 113 114 edit = parser.add(sub, self.edit, "Presents the properties for the current profile in your editor. Saving them will update your profile.") 115 version = parser.add(sub, self.version, "Prints the configuration version for the current profile.") 116 path = parser.add(sub, self.path, "Prints the file that is used for configuration") 117 lock = parser.add(sub, self.lock, "Acquires the config file lock and holds it") 118 upgrade = parser.add(sub, self.upgrade, "Creates a 4.2 config.xml file based on your current Java Preferences") 119 old = parser.add(sub, self.old, "Delegates to the old configuration system using Java preferences") 120 old.add_argument("target", nargs="*")
121
122 - def open_config(self, args):
123 if args.source: 124 cfg_xml = path(args.source) 125 if not cfg_xml.exists(): 126 self.ctx.die(124, "File not found: %s" % args.source) 127 else: 128 grid_dir = self.ctx.dir / "etc" / "grid" 129 if grid_dir.exists(): 130 cfg_xml = grid_dir / "config.xml" 131 else: 132 self.ctx.err("%s not found; using %s" % (grid_dir, usr_xml)) 133 userdir = path(get_user_dir()) 134 usr_xml = userdir / "omero"/ "config.xml" 135 cfg_xml = usr_xml 136 try: 137 return ConfigXml(str(cfg_xml)) 138 except portalocker.LockException: 139 self.ctx.die(112, "Could not acquire lock on %s" % cfg_xml)
140 141 @with_config
142 - def all(self, args, config):
143 for k, v in config.properties(None, True): 144 self.ctx.out(k)
145 146 @with_config
147 - def default(self, args, config):
148 if args.NAME: 149 config.default(args.NAME) 150 else: 151 self.ctx.out(config.default(args.NAME))
152 153 @with_config
154 - def drop(self, args, config):
155 try: 156 config.remove(args.NAME) 157 except KeyError: 158 self.ctx.err("Unknown configuration: %s" % args.NAME)
159 160 @with_config
161 - def get(self, args, config):
162 orig = sorted(list(config.keys())) 163 keys = sorted(list(args.KEY)) 164 if not keys: 165 keys = orig 166 for k in config.IGNORE: 167 k in keys and keys.remove(k) 168 169 for k in keys: 170 if k not in orig: 171 continue 172 if args.KEY and len(args.KEY) == 1: 173 self.ctx.out(config[k]) 174 else: 175 self.ctx.out("%s=%s" % (k, config[k]))
176 177 @with_config
178 - def set(self, args, config):
179 if "=" in args.KEY and args.VALUE is None: 180 k, v = args.KEY.split("=", 1) 181 self.ctx.err(""" "=" in key name. Did you mean "...set %s %s"?""" % (k, v)) 182 elif args.VALUE is None: 183 del config[args.KEY] 184 else: 185 config[args.KEY] = args.VALUE
186 187 @with_config
188 - def keys(self, args, config):
189 for k in config.keys(): 190 if k not in config.IGNORE: 191 self.ctx.out(k)
192 193 @with_config
194 - def load(self, args, config):
195 keys = None 196 if not args.q: 197 keys = config.keys() 198 199 for f in args.file: 200 try: 201 previous = None 202 for line in f: 203 if previous: 204 line = previous + line 205 previous = self.handle_line(line, config, keys) 206 finally: 207 f.close()
208 209 @with_config
210 - def edit(self, args, config, edit_path = edit_path):
211 from omero.util.temp_files import create_path, remove_path 212 start_text = "# Edit your preferences below. Comments are ignored\n" 213 for k in sorted(config.keys()): 214 start_text += ("%s=%s\n" % (k, config[k])) 215 temp_file = create_path() 216 try: 217 edit_path(temp_file, start_text) 218 except RuntimeError, re: 219 self.ctx.die(954, "%s: Failed to edit %s" % (getattr(re, "pid", "Unknown"), temp_file)) 220 args.NAME = config.default() 221 self.drop(args, config) 222 args.file = [open(str(temp_file), "r")] 223 args.q = True 224 self.load(args, config) 225 remove_path(temp_file)
226 227 @with_config
228 - def version(self, args, config):
229 self.ctx.out(config.version(config.default()))
230 231 @with_config
232 - def path(self, args, config):
233 self.ctx.out(config.filename)
234 235 @with_config
236 - def lock(self, args, config):
237 self.ctx.input("Press enter to unlock")
238 239 @with_config
240 - def upgrade(self, args, config):
241 self.ctx.out("Importing pre-4.2 preferences") 242 txt = getprefs(["get"], str(self.ctx.dir / "lib")) 243 for line in txt.split("\n"): 244 self.handle_line(line, config, None) 245 246 # Upgrade procedure for 4.2 247 MSG = """Manually modify them via "omero config old set ..." and re-run""" 248 m = config.as_map() 249 for x in ("keyStore", "keyStorePassword", "trustStore", "trustStorePassword"): 250 old = "omero.ldap." + x 251 new = "omero.security." + x 252 if old in m: 253 config[new] = config[old] 254 255 attributes, values = [], [] 256 if "omero.ldap.attributes" in m: 257 attributes = config["omero.ldap.attributes"] 258 attributes = attributes.split(",") 259 if "omero.ldap.values" in m: 260 values = config["omero.ldap.values"] 261 values = values.split(",") 262 263 if len(attributes) != len(values): 264 raise ValueError("%s != %s\nLDAP properties in pre-4.2 configuration are invalid.\n%s" % (attributes, values, MSG)) 265 pairs = zip(attributes, values) 266 if pairs: 267 if len(pairs) == 1: 268 user_filter = "(%s=%s)" % (tuple(pairs[0])) 269 else: 270 user_filter = "(&%s)" % ["(%s=%s)" % tuple(pair) for pair in pairs] 271 config["omero.ldap.user_filter"] = user_filter 272 273 if "omero.ldap.groups" in m: 274 raise ValueError("Not currently handling omero.ldap.groups\n%s" % MSG) 275 276 config["omero.config.upgraded"] = "4.2.0"
277
278 - def handle_line(self, line, config, keys):
279 line = line.strip() 280 if not line or line.startswith("#"): 281 return None 282 if line.endswith("\\"): 283 return line[:-1] 284 285 parts = line.split("=", 1) 286 if len(parts[0]) == 0: 287 return 288 if len(parts) == 1: 289 parts.append("") 290 if keys and parts[0] in keys: 291 self.ctx.die(502, "Duplicate property: %s (%s => %s)"\ 292 % (parts[0], config[parts[0]], parts[1])) 293 keys.append(parts[0]) 294 config[parts[0]] = parts[1]
295
296 - def old(self, args):
297 self.ctx.out(getprefs(args.target, str(self.ctx.dir / "lib")))
298 299 try: 300 register("config", PrefsControl, HELP) 301 except NameError: 302 if __name__ == "__main__": 303 cli = CLI() 304 cli.register("config", PrefsControl, HELP) 305 cli.invoke(sys.argv[1:]) 306