3 # Copyright (C) 2010-2013 CEA/DEN
5 # This library is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU Lesser General Public
7 # License as published by the Free Software Foundation; either
8 # version 2.1 of the License.
10 # This library is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 # Lesser General Public License for more details.
15 # You should have received a copy of the GNU Lesser General Public
16 # License along with this library; if not, write to the Free Software
17 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
26 from src import ElementTree as etree
29 parser = src.options.Options()
30 parser.add_option('n', 'name', 'string', 'name',
31 _('Optional: The name of the application (default is APPLICATION.virtual_app.name or '
33 parser.add_option('c', 'catalog', 'string', 'catalog',
34 _('Optional: The resources catalog to use'))
35 parser.add_option('t', 'target', 'string', 'target',
36 _('Optional: The directory where to create the application (default is '
37 'APPLICATION.workdir)'))
38 parser.add_option('', 'gencat', 'string', 'gencat',
39 _("Optional: Create a resources catalog for the specified machines "
40 "(separated with ',')\n\tNOTICE: this command will ssh to retrieve "
41 "information to each machine in the list"))
42 parser.add_option('m', 'module', 'list2', 'modules',
43 _("Optional: the restricted list of module(s) to include in the "
45 parser.add_option('', 'use_mesa', 'boolean', 'use_mesa',
46 _("Optional: Create a launcher that will use mesa products\n\t"
47 "It can be usefull whan salome is used on a remote machine through ssh"))
50 # Creates an alias for runAppli.
51 def make_alias(appli_path, alias_path, force=False):
52 assert len(alias_path) > 0, "Bad name for alias"
53 if os.path.exists(alias_path) and not force:
54 raise src.SatException(_("Cannot create the alias '%s'\n") % alias_path)
55 else: # find relative path
56 os.symlink(appli_path, alias_path)
59 # add the definition of a module to out stream.
60 def add_module_to_appli(out, module, has_gui, module_path, logger, flagline):
61 if not os.path.exists(module_path):
63 logger.write("\n", 3, False)
65 logger.write(" " + src.printcolors.printcWarning(_(
66 "WARNING: module %s not installed") % module) + "\n", 3)
68 out.write(' <module name="%s" gui="%s" path="%s"/>\n' % (module,
74 # Creates the config file to create an application with the list of modules.
75 def create_config_file(config, modules, env_file, logger):
78 if 'SAMPLES' in config.APPLICATION.products:
79 samples = src.product.get_product_config(config, 'SAMPLES').source_dir
81 config_file = src.get_tmp_filename(config, "appli_config.xml")
82 f = open(config_file, "w")
84 f.write('<application>\n')
85 if env_file.endswith("cfg"):
86 f.write('<context path="%s"/>\n' % env_file)
88 f.write('<prerequisites path="%s"/>\n' % env_file)
89 f.write('<resources path="CatalogResources.xml"/>\n')
90 f.write('<modules>\n')
94 mm = src.product.get_product_config(config, m)
95 # do not include in virtual application application module!
96 if src.get_property_in_product_cfg(mm, "is_salome_application") == "yes":
98 # do not include products that do not compile
99 if not src.product.product_compiles(mm):
102 if src.product.product_is_smesh_plugin(mm):
105 if 'install_dir' in mm and bool(mm.install_dir):
106 if src.product.product_is_cpp(mm):
108 for aa in src.product.get_product_components(mm):
109 install_dir = os.path.join(config.APPLICATION.workdir,
111 mp = os.path.join(install_dir, aa)
112 flagline = add_module_to_appli(f,
121 gui = src.get_cfg_param(mm, "has_gui", "yes")
122 flagline = add_module_to_appli(f, m, gui, mp, logger, flagline)
124 f.write('</modules>\n')
125 f.write('<samples path="%s"/>\n' % samples)
126 f.write('</application>\n')
132 # Customizes the application by editing SalomeApp.xml.
133 def customize_app(config, appli_dir, logger):
134 if 'configure' not in config.APPLICATION.virtual_app \
135 or len(config.APPLICATION.virtual_app.configure) == 0:
138 # shortcut to get an element (section or parameter) from parent.
139 def get_element(parent, name, strtype):
140 for c in parent.getchildren():
141 if c.attrib['name'] == name:
144 # element not found create it
145 elt = add_simple_node(parent, strtype)
146 elt.attrib['name'] = name
149 # shortcut method to create a node
150 def add_simple_node(parent, node_name, text=None):
151 n = etree.Element(node_name)
154 n.text = text.strip("\n\t").decode("UTF-8")
156 sys.stderr.write("################ %s %s\n" % (node_name, text))
162 app_file = os.path.join(appli_dir, "SalomeApp.xml")
163 tree = etree.parse(app_file)
164 document = tree.getroot()
165 assert document is not None, "document tag not found"
167 logger.write("\n", 4)
168 for section_name in config.APPLICATION.virtual_app.configure:
169 for parameter_name in config.APPLICATION.virtual_app.configure[section_name]:
170 parameter_value = config.APPLICATION.virtual_app.configure[section_name][parameter_name]
171 logger.write(" configure: %s/%s = %s\n" % (section_name,
174 section = get_element(document, section_name, "section")
175 parameter = get_element(section, parameter_name, "parameter")
176 parameter.attrib['value'] = parameter_value
179 f = open(app_file, "w")
180 f.write("<?xml version='1.0' encoding='utf-8'?>\n")
181 f.write(etree.tostring(document, encoding='utf-8'))
185 # Generates the application with the config_file.
186 def generate_application(config, appli_dir, config_file, logger):
187 target_dir = os.path.dirname(appli_dir)
189 install_KERNEL_dir = src.product.get_product_config(config,
190 'KERNEL').install_dir
191 script = os.path.join(install_KERNEL_dir, "bin", "salome", "appli_gen.py")
192 if not os.path.exists(script):
193 raise src.SatException(_("KERNEL is not installed"))
195 # Add SALOME python in the environment in order to avoid python version
196 # problems at appli_gen.py call
197 if 'Python' in config.APPLICATION.products:
198 envi = src.environment.SalomeEnviron(config,
199 src.environment.Environ(
202 envi.set_a_product('Python', logger)
204 command = "python %s --prefix=%s --config=%s" % (script,
207 logger.write("\n>" + command + "\n", 5, False)
208 res = subprocess.call(command,
211 env=envi.environ.environ,
212 stdout=logger.logTxtFile,
213 stderr=subprocess.STDOUT)
216 raise src.SatException(_("Cannot create application, code = %d\n") % res)
222 def write_step(logger, message, level=3, pad=50):
223 logger.write("%s %s " % (message, '.' * (pad - len(message.decode("UTF-8")))), level)
227 # Creates a SALOME application.
228 def create_application(config, appli_dir, catalog, logger, display=True):
230 SALOME_modules = get_SALOME_modules(config)
232 warn = ['KERNEL', 'GUI']
235 if w not in SALOME_modules:
236 msg = _("WARNING: module %s is required to create application\n") % w
237 logger.write(src.printcolors.printcWarning(msg), 2)
239 # generate the launch file
240 retcode = generate_launch_file(config,
247 cmd = src.printcolors.printcLabel("%s/salome" % appli_dir)
250 logger.write("\n", 3, False)
251 logger.write(_("To launch the application, type:\n"), 3, False)
252 logger.write(" %s" % (cmd), 3, False)
253 logger.write("\n", 3, False)
256 def get_SALOME_modules(config):
258 for product in config.APPLICATION.products:
259 product_info = src.product.get_product_config(config, product)
260 if (src.product.product_is_salome(product_info) or
261 src.product.product_is_generated(product_info)):
262 l_modules.append(product)
266 # Obsolescent way of creating the application.
267 # This method will use appli_gen to create the application directory.
268 def generate_launch_file(config, appli_dir, catalog, logger, l_SALOME_modules):
271 if len(catalog) > 0 and not os.path.exists(catalog):
272 raise IOError(_("Catalog not found: %s") % catalog)
274 write_step(logger, _("Creating environment files"))
275 status = src.KO_STATUS
277 VersionSalome = src.get_salome_version(config)
278 if VersionSalome>=820:
279 # for salome 8+ we use a salome context file for the virtual app
288 # generate only shells the user wants (by default bash, csh, batch)
289 # the environ command will only generate file compatible
290 # with the current system.
291 environ.write_all_source_files(config,
295 status = src.OK_STATUS
297 logger.write(src.printcolors.printc(status) + "\n", 2, False)
299 # build the application (the name depends upon salome version
300 env_file = os.path.join(config.APPLICATION.workdir, "env_launch." + env_ext)
302 write_step(logger, _("Building application"), level=2)
303 cf = create_config_file(config, l_SALOME_modules, env_file, logger)
305 # create the application directory
306 os.makedirs(appli_dir)
308 # generate the application
309 status = src.KO_STATUS
311 retcode = generate_application(config, appli_dir, cf, logger)
312 customize_app(config, appli_dir, logger)
313 status = src.OK_STATUS
315 logger.write(src.printcolors.printc(status) + "\n", 2, False)
317 # copy the catalog if one
319 shutil.copy(catalog, os.path.join(appli_dir, "CatalogResources.xml"))
326 # Generates the catalog from a list of machines.
327 def generate_catalog(machines, config, logger):
328 # remove empty machines
329 machines = map(lambda l: l.strip(), machines)
330 machines = filter(lambda l: len(l) > 0, machines)
332 src.printcolors.print_value(logger,
333 _("Generate Resources Catalog"),
336 cmd = '"cat /proc/cpuinfo | grep MHz ; cat /proc/meminfo | grep MemTotal"'
337 user = getpass.getuser()
339 catfile = src.get_tmp_filename(config, "CatalogResources.xml")
340 catalog = file(catfile, "w")
341 catalog.write("<!DOCTYPE ResourcesCatalog>\n<resources>\n")
343 logger.write(" ssh %s " % (k + " ").ljust(20, '.'), 4)
346 ssh_cmd = 'ssh -o "StrictHostKeyChecking no" %s %s' % (k, cmd)
347 p = subprocess.Popen(ssh_cmd, shell=True,
348 stdin=subprocess.PIPE,
349 stdout=subprocess.PIPE,
350 stderr=subprocess.PIPE)
353 if p.returncode != 0:
354 logger.write(src.printcolors.printc(src.KO_STATUS) + "\n", 4)
355 logger.write(" " + src.printcolors.printcWarning(p.stderr.read()),
358 logger.write(src.printcolors.printc(src.OK_STATUS) + "\n", 4)
359 lines = p.stdout.readlines()
360 freq = lines[0][:-1].split(':')[-1].split('.')[0].strip()
361 nb_proc = len(lines) -1
362 memory = lines[-1].split(':')[-1].split()[0].strip()
363 memory = int(memory) / 1000
365 catalog.write(" <machine\n")
366 catalog.write(" protocol=\"ssh\"\n")
367 catalog.write(" nbOfNodes=\"1\"\n")
368 catalog.write(" mode=\"interactif\"\n")
369 catalog.write(" OS=\"LINUX\"\n")
370 catalog.write(" CPUFreqMHz=\"%s\"\n" % freq)
371 catalog.write(" nbOfProcPerNode=\"%s\"\n" % nb_proc)
372 catalog.write(" memInMB=\"%s\"\n" % memory)
373 catalog.write(" userName=\"%s\"\n" % user)
374 catalog.write(" name=\"%s\"\n" % k)
375 catalog.write(" hostname=\"%s\"\n" % k)
376 catalog.write(" >\n")
377 catalog.write(" </machine>\n")
379 catalog.write("</resources>\n")
383 ##################################################
386 # Describes the command
388 '''method that is called when salomeTools is called with --help option.
390 :return: The text to display for the application command description.
393 return _("The application command creates a SALOME application.\n"
394 "WARNING: it works only for SALOME 6. Use the \"launcher\" "
395 "command for newer versions of SALOME\n\nexample:\nsat application"
400 def run(args, runner, logger):
401 '''method that is called when salomeTools is called with application
405 (options, args) = parser.parse_args(args)
408 src.check_config_has_application( runner.cfg )
410 application = src.printcolors.printcLabel(runner.cfg.VARS.application)
411 logger.write(_("Building application for %s\n") % application, 1)
413 # if section APPLICATION.virtual_app does not exists create one
414 if "virtual_app" not in runner.cfg.APPLICATION:
415 msg = _("The section APPLICATION.virtual_app is not defined in the product.")
416 logger.write(src.printcolors.printcError(msg), 1)
417 logger.write("\n", 1)
420 # get application dir
421 target_dir = runner.cfg.APPLICATION.workdir
423 target_dir = options.target
425 # set list of modules
427 runner.cfg.APPLICATION.virtual_app['modules'] = options.modules
429 # activate mesa use in the generated application
431 src.activate_mesa_property(runner.cfg)
433 # set name and application_name
435 runner.cfg.APPLICATION.virtual_app['name'] = options.name
436 runner.cfg.APPLICATION.virtual_app['application_name'] = options.name + "_appdir"
438 application_name = src.get_cfg_param(runner.cfg.APPLICATION.virtual_app,
440 runner.cfg.APPLICATION.virtual_app.name + "_appdir")
441 appli_dir = os.path.join(target_dir, application_name)
443 src.printcolors.print_value(logger,
444 _("Application directory"),
449 catalog, catalog_src = "", ""
451 # use catalog specified in the command line
452 catalog = options.catalog
454 # generate catalog for given list of computers
455 catalog_src = options.gencat
456 catalog = generate_catalog(options.gencat.split(","),
458 elif 'catalog' in runner.cfg.APPLICATION.virtual_app:
459 # use catalog specified in the product
460 if runner.cfg.APPLICATION.virtual_app.catalog.endswith(".xml"):
462 catalog = runner.cfg.APPLICATION.virtual_app.catalog
464 # catalog as a list of computers
465 catalog_src = runner.cfg.APPLICATION.virtual_app.catalog
466 mlist = filter(lambda l: len(l.strip()) > 0,
467 runner.cfg.APPLICATION.virtual_app.catalog.split(","))
469 catalog = generate_catalog(runner.cfg.APPLICATION.virtual_app.catalog.split(","),
472 # display which catalog is used
474 catalog = os.path.realpath(catalog)
475 if len(catalog_src) > 0:
476 src.printcolors.print_value(logger,
477 _("Resources Catalog"),
481 src.printcolors.print_value(logger,
482 _("Resources Catalog"),
486 logger.write("\n", 3, False)
490 # remove previous application
491 if os.path.exists(appli_dir):
492 write_step(logger, _("Removing previous application directory"))
495 shutil.rmtree(appli_dir)
498 logger.write(src.printcolors.printc(rres) + "\n", 3, False)
500 # generate the application
502 try: # try/except/finally not supported in all version of python
503 retcode = create_application(runner.cfg, appli_dir, catalog, logger)
504 except Exception as exc:
505 details.append(str(exc))
508 logger.write("\n", 3, False)