(file) Return to localize.py CVS log (file) (dir) Up to [Development] / JSOC

   1 arta  1.15 #!/usr/bin/python
   2 arta  1.1  
   3 arta  1.13 # When run with the -s flag, localize.py configures the SUMS-server component of NetDRMS.
   4 arta  1.15 from __future__ import print_function
   5 arta  1.1  import sys
   6            import getopt
   7            import re
   8 arta  1.6  import os
   9            import stat
  10 arta  1.13 import filecmp
  11 arta  1.6  import xml.etree.ElementTree as ET
  12 arta  1.1  from subprocess import check_output, CalledProcessError
  13            
  14            # Constants
  15            VERS_FILE = 'jsoc_version.h'
  16            SDP_CFG = 'configsdp.txt'
  17            NET_CFG = 'config.local'
  18            NET_CFGMAP = 'config.local.map'
  19            RET_SUCCESS = 0
  20            RET_NOTDRMS = 1
  21            
  22 arta  1.2  PREFIX = """# This file was auto-generated by localize.py. Please do not edit it directly (running
  23            # configure will run localize.py, which will then overwrite any edits manually performed).
  24            """
  25 arta  1.1  
  26 arta  1.2  C_PREFIX = """/* This file was auto-generated by localize.py. Please do not edit it directly (running
  27             * configure will run localize.py, which will then overwrite any edits manually performed). */
  28 arta  1.1  """
  29            
  30 arta  1.2  PERL_BINPATH = '#!/usr/bin/perl\n'
  31            
  32            PERL_INTIAL = """package drmsparams;
  33                
  34            use warnings;
  35            use strict;
  36            """
  37            
  38            PERL_FXNS_A = """sub new
  39 arta  1.1  {
  40                my($clname) = shift;
  41                
  42                my($self) = 
  43                {
  44                    _paramsH => undef
  45                };
  46                
  47                bless($self, $clname);
  48 arta  1.9      $self->{_paramsH} = {};
  49                $self->initialize();
  50 arta  1.1      
  51                return $self;
  52            }
  53                
  54            sub DESTROY
  55            {
  56                my($self) = shift;
  57            }
  58 arta  1.2  """
  59            
  60            PERL_FXNS_B = """sub get
  61            {
  62                my($self) = shift;
  63                my($name) = shift;
  64                my($rv);
  65 arta  1.1      
  66 arta  1.2      if (exists($self->{_paramsH}->{$name}))
  67                {
  68                    return $self->{_paramsH}->{$name};
  69                }
  70                else
  71                {
  72                    return undef;
  73                }
  74            }
  75            1;"""
  76 arta  1.1  
  77 arta  1.18 PY_BINPATH = '#/usr/bin/python\n'
  78            
  79            PY_FXNS_A = """
  80            class DRMSParams:
  81                def __init__(self):
  82                    self.params = {}
  83                    self.initialize()
  84                    
  85                def __del__(self):
  86                    del self.params
  87                    
  88                def initialize(self):
  89            """
  90            
  91            PY_FXNS_B = """    def get(self, name):
  92                    if name in self.params:
  93 arta  1.20             return self.params[name]
  94 arta  1.18         else:
  95                        return None
  96            """
  97            
  98 arta  1.13 SUMRM_COMMENT = """# This is the configuration file for the sum_rm program. It was auto-generated by the DRMS master configure script.
  99            # It controls the behavior of the sum_rm program, and is loaded each time sum_rm runs. To change the
 100            # parameter values in this configuration file, modify config.local, then re-run configure. This configuration
 101            # file will be updated only if parameters affecting it are modified. If such changes are made to config.local,
 102            # please make sure that the sum_rm service is disabled while configure in running.
 103            """
 104            
 105            SUMRM_DOC = """# sum_rm removes end-of-life SUMS data files to prevent disk-partitions from becomming 100% full. 
 106            # sum_svc, the main SUMS service, starts this daemon when it is launched. Within an infinite loop, sum_rm sleeps
 107            # for SLEEP number of seconds (defined below). When it awakes, it loads the sum_rm configuration file. For each SU,
 108            # it then examines the 'effective_date' column within the sum_partn_alloc table of the SUMS database. It does so by
 109            # sorting all SUs by effective date (this date is actually an expiration date - the SU is good until the end of that day),
 110            # and then, starting with the SU with the oldest effective date, it deletes the SUs. It continues deleting SUs until one
 111            # of three conditions is met:
 112            #
 113            #   (a) The disk has at least PART_PERCENT_FREE percent free space.
 114            #   (b) All SUs have effective_date values in the future.
 115            #   (c) At least 600 SUs have been deleted (this is defined in the LIMIT statement in the file SUMLIB_RmDoX.pgc).
 116            #
 117            # After sum_rm stops deleteing SUs, it then sleeps for SLEEP seconds, completing the first iteration of the
 118            # infinite loop.
 119 arta  1.13 """
 120            
 121            SUMRM_PARTN_PERCENT_FREE = """
 122            # This is the percentage at which all disk partitions are to be kept free.
 123            # If not specified, this defaults to 3. For example, setting PART_PERCENT_FREE = 5 will allow all partitions to
 124            # fill to 95% full. Dividing the number of unused blocks by the total number of blocks, and rounding up,
 125            # will result in the number specified by PART_PERCENT_FREE.
 126            #
 127            # NOTE : This behavior was previously controlled by the MAX_FREE_{n} family of parameters. {n} referred to the
 128            # disk-partition number and the value of parameter MAX_FREE_{n} was the MINIMUM number of free MB in the
 129            # partition [No clue why the word MAX was used]. As of NetDRMS 7.0, MAX_FREE_{n} has no effect."""
 130            
 131            SUMRM_SLEEP = """
 132            # The value is the number of seconds to sleep between iterations of the main loop in sum_rm."""
 133            
 134            SUMRM_LOG = """
 135            # The value is the log file (opened only at sum_rm startup; the sum_rm pid is appended to this file name)."""
 136            
 137            SUMRM_MAIL = """
 138            # The value is the email address of the recipient to be notified in case of a problem."""
 139            
 140 arta  1.13 SUMRM_NOOP = """
 141            # If the value is set to anything other than 0, then sum_rm is rendered inactive. Otherwise, sum_rm is active."""
 142            
 143            SUMRM_USER = """
 144            # The value designates the linux user who is allowed to run sum_rm."""
 145            
 146            SUMRM_NORUN = """
 147            # This pair of paramters defines a window of time, during which sum_rm will become torpid - in this
 148            # window, sum_rm will not scan for SUs to delete, not will it delete any SUs. Each value is an integer, 0-23, that
 149            # represents an hour of the day. For example, if NORUN_START=8 and NORUN_STOP=10, then between 8am and 10am
 150            # local time, sum_rm will be dormant. To disable this behavior, set both parameters to the same value."""
 151 arta  1.6  
 152            RULESPREFIX = """# Standard things
 153            sp 		:= $(sp).x
 154            dirstack_$(sp)	:= $(d)
 155            d		:= $(dir)
 156            """
 157            
 158            RULESSUFFIX = """dir	:= $(d)/example
 159            -include		$(SRCDIR)/$(dir)/Rules.mk
 160            dir	:= $(d)/cookbook
 161            -include		$(SRCDIR)/$(dir)/Rules.mk
 162            dir	:= $(d)/myproj
 163            -include		$(SRCDIR)/$(dir)/Rules.mk
 164            
 165            # Standard things
 166            d		:= $(dirstack_$(sp))
 167            sp		:= $(basename $(sp))
 168            """
 169            
 170            TARGETPREFIX = """$(PROJOBJDIR):\n\t+@[ -d $@ ] || mkdir -p $@"""
 171            
 172 arta  1.3  ICC_MAJOR = 9
 173            ICC_MINOR = 0
 174            GCC_MAJOR = 3
 175            GCC_MINOR = 0
 176            IFORT_MAJOR = 9
 177            IFORT_MINOR = 0
 178            GFORT_MAJOR = 4
 179            GFORT_MINOR = 2
 180            
 181            
 182 arta  1.1  # Read arguments
 183            #  d - localization directory
 184            #  b - base name of all parameter files (e.g., -b drmsparams --> drmsparams.h, drmsparams.mk, drmsparams.pm, etc.)
 185 arta  1.13 #  s - configure a NetDRMS server (i.e., SUMS server). Otherwise, do client configuration only. A server
 186            #      configuration will modify something that only the production user has access to. An example is the sum_rm.cfg
 187            #      file. To modify that file, the user running configure must be running configure on the SUMS-server host, and
 188            #      must have write permission on sum_rm.cfg.
 189 arta  1.1  def GetArgs(args):
 190                rv = bool(0)
 191                optD = {}
 192                
 193                try:
 194 arta  1.13         opts, remainder = getopt.getopt(args, "hd:b:s",["dir=", "base="])
 195 arta  1.1      except getopt.GetoptError:
 196                    print('Usage:')
 197                    print('localize.py [-h] -d <localization directory> -b <parameter file base>')
 198                    rv = bool(1)
 199                
 200                if rv == bool(0):
 201                    for opt, arg in opts:
 202                        if opt == '-h':
 203                            print('localize.py [-h] -d <localization directory> -b <parameter file base>')
 204                        elif opt in ("-d", "--dir"):
 205                            regexp = re.compile(r"(\S+)/?")
 206                            matchobj = regexp.match(arg)
 207                            if matchobj is None:
 208                                rv = bool(1)
 209                            else:
 210                                optD['dir'] = matchobj.group(1)
 211                        elif opt in ("-b", "--base"):
 212                            optD['base'] = arg
 213 arta  1.13             elif opt in ("-s"):
 214                            optD['server'] = ""
 215 arta  1.1              else:
 216                            optD[opt] = arg
 217            	
 218                return optD
 219            
 220            def createMacroStr(key, val, keyColLen, status):
 221                if keyColLen < len(key):
 222                    status = bool(1)
 223                    return None
 224                else:
 225                    nsp = keyColLen - len(key)
 226                    spaces = str()
 227                    for isp in range(nsp):
 228                        spaces += ' '
 229                    status = bool(0)
 230                    return '#define ' + key + spaces + val + '\n'
 231            
 232            def createPerlConst(key, val, keyColLen, status):
 233                if keyColLen < len(key):
 234                    status = bool(1)
 235                    return None
 236 arta  1.1      else:
 237                    nsp = keyColLen - len(key)
 238                    spaces = str()
 239                    for isp in range(nsp):
 240                        spaces += ' '
 241                    status = bool(0)
 242                    return 'use constant ' + key + ' => ' + spaces + val + ';\n'
 243            
 244 arta  1.18 def createPyConst(key, val, keyColLen, status):
 245                if keyColLen < len(key):
 246                    status = bool(1)
 247                    return None
 248                else:
 249                    nsp = keyColLen - len(key)
 250                    spaces = str()
 251                    for isp in range(nsp):
 252                        spaces += ' '
 253                    status = bool(0)
 254                    return key + ' = ' + spaces + val + '\n'
 255            
 256 arta  1.3  def isSupportedPlat(plat):
 257                regexp = re.compile(r"\s*(^x86_64|^ia32|^ia64|^avx)", re.IGNORECASE)
 258                matchobj = regexp.match(plat);
 259                    
 260                if not matchobj is None:
 261                    return bool(1);
 262                else:
 263                    return bool(0);
 264            
 265 arta  1.6  def processMakeParam(mDefs, key, val, platDict, machDict):
 266 arta  1.3      varMach = None
 267                regexp = re.compile(r"(\S+):(\S+)")
 268                matchobj = regexp.match(key)
 269                if not matchobj is None:
 270                    varName = matchobj.group(1)
 271                    varMach = matchobj.group(2)
 272                else:
 273                    varName = key
 274                
 275                varValu = val
 276                    
 277                if varMach is None:
 278                    mDefs.extend(list('\n' + varName + ' = ' + varValu))
 279                else:
 280                    if isSupportedPlat(varMach):
 281                        # The guard will compare varValu to $JSOC_MACHINE.
 282                        if not varMach in platDict:
 283                            platDict[varMach] = {}
 284                        platDict[varMach][varName] = varValu
 285                    else:
 286                        # The guard will compare varValu to $MACHINETYPE (this is just the hostname of the machine on which localize.py is running).
 287 arta  1.3              if not varMach in machDict:
 288                            machDict[varMach] = {}
 289                        machDict[varMach][varName] = varValu
 290            
 291 arta  1.18 def processParam(cfgfile, line, regexpQuote, regexp, keymap, defs, cDefs, mDefsGen, mDefsMake, perlConstSection, perlInitSection, pyConstSection, pyInitSection, platDict, machDict, section):
 292 arta  1.1      status = 0
 293                        
 294                if ''.join(section) == 'defs' or not cfgfile:
 295                    matchobj = regexp.match(line)
 296                    if not matchobj is None:
 297                        # We have a key-value line
 298                        keyCfgSp = matchobj.group(1)
 299                        val = matchobj.group(2)
 300                        
 301                        # Must map the indirect name to the actual name
 302                        if keymap:
 303                            # Map to actual name only if the keymap is not empty (which signifies NA).
 304                            if keyCfgSp in keymap:
 305                                key = keymap[keyCfgSp]
 306                            elif keyCfgSp == 'LOCAL_CONFIG_SET' or keyCfgSp == 'DRMS_SAMPLE_NAMESPACE':
 307 arta  1.6                      # Ignore parameters that are not useful and shouldn't have been there in the first place. But
 308                                # they have been released to the world, so we have to account for them.
 309 arta  1.1                      return bool(0)
 310                            elif not cfgfile:
 311                                # Should not be doing mapping for addenda
 312                                key = keyCfgSp
 313                            else:
 314                                raise Exception('badKeyMapKey', keyCfgSp)
 315                        else:
 316                            key = keyCfgSp
 317                        
 318                        matchobj = regexpQuote.match(key)
 319                        if not matchobj is None:
 320                            quote = matchobj.group(1)
 321                            key = matchobj.group(2)
 322            
 323                            # master defs dictionary
 324                            defs[key] = val
 325                            
 326                            # C header file
 327                            if quote == "q":
 328                                # Add double-quotes
 329                                cDefs.extend(list(createMacroStr(key, '"' + val + '"', 40, status)))
 330 arta  1.1                  elif quote == "p":
 331                                # Add parentheses
 332                                cDefs.extend(list(createMacroStr(key, '(' + val + ')', 40, status)))
 333                            elif quote == "a":
 334                                # Leave as-is
 335                                cDefs.extend(list(createMacroStr(key, val, 40, status)))
 336                            else:
 337                                # Unknown quote type
 338                                raise Exception('badQuoteQual', key)
 339                            
 340                            if status:
 341                                raise Exception('paramNameTooLong', key)
 342                            
 343                            # Make file - val should never be quoted; just use as is
 344 arta  1.4                  mDefsGen.extend(list('\n' + key + ' = ' + val))
 345 arta  1.1                  
 346                            # Perl file - val should ALWAYS be single-quote quoted
 347                            # Save const info to a string
 348                            perlConstSection.extend(list(createPerlConst(key, "'" + val + "'", 40, status)))
 349                            
 350 arta  1.18                 # Python file
 351                            pyConstSection.extend(list(createPyConst(key, "'" + val + "'", 40, status)))
 352                            
 353 arta  1.1                  if status:
 354                                raise Exception('paramNameTooLong', key)
 355                            
 356                            # Save initialization information as a string. Now that we've defined
 357                            # constants (the names of which are the parameter names) 
 358                            # we can refer to those in the init section. The key variable holds the
 359                            # name of the constant.
 360 arta  1.9                  perlInitSection.extend(list("\n  $self->{_paramsH}->{'" + key + "'} = " + key + ';'))
 361 arta  1.18                 
 362                            # The amount of indenting matters! This is Python.
 363                            pyInitSection.extend(list("        self.params['" + key + "'] = " + key + '\n'))
 364 arta  1.1              else:
 365                            # No quote qualifier
 366                            raise Exception('missingQuoteQual', key)
 367 arta  1.3      elif ''.join(section) == 'make' and cfgfile:
 368                    # Configure the remaining make variables defined in the __MAKE__ section of the configuration file. Third-party
 369                    # library make variables are specified in the __MAKE__ section.
 370                    matchobj = regexp.match(line)
 371                    if not matchobj is None:
 372                        # We have a key-value line
 373                        key = matchobj.group(1)
 374                        val = matchobj.group(2)
 375            
 376                        # This information is for making make variables only. We do not need to worry about quoting any values
 377                        defs[key] = val
 378 arta  1.4              processMakeParam(mDefsMake, key, val, platDict, machDict)
 379 arta  1.1      
 380                return bool(0)
 381            
 382            # We have some extraneous line or a newline - ignore.
 383            
 384 arta  1.6  def processXML(xml, projRules, projTarget):
 385                rv = bool(0)
 386                
 387                # <projects>
 388                root = ET.fromstring(xml)
 389                
 390                # Iterate through each proj child.
 391                for proj in root.iter('proj'):
 392                    # Rules.mk
 393                    nameElem = proj.find('name')
 394                    rulesStr = 'dir     := $(d)/' + nameElem.text + '\n-include          $(SRCDIR)/$(dir)/Rules.mk\n'
 395                    
 396                    # make doesn't support logical operations in ifeq conditionals (you can't do ifeq (A AND B)), 
 397                    # so we need to write:
 398                    #   ifeq (A)
 399                    #      ifeq (B)
 400                    #        <do something>
 401                    #      endif
 402                    #   endif
 403                        
 404                    rulesPref = '';
 405 arta  1.6          rulesSuff = '';
 406                
 407                    filters = proj.find('filters')
 408                    if filters is not None:
 409                        for filter in filters.findall('filter'):
 410                            rulesPref += 'ifeq ($(' + filter.find('name').text + '),' + filter.find('value').text + ')\n'
 411                            rulesSuff += 'endif\n'
 412                        
 413                    if len(rulesPref) > 0 and len(rulesSuff) > 0:
 414                        projRules.extend(list(rulesPref))
 415                        projRules.extend(list(rulesStr))
 416                        projRules.extend(list(rulesSuff))
 417                    else:
 418                        projRules.extend(list(rulesStr))
 419                    
 420                    # target.mk
 421                    subdirs = proj.find('subdirs')
 422                    if subdirs is not None:
 423                        for subdir in subdirs.findall('subdir'):
 424                            targetStr = '\n\t+@[ -d $@/' + nameElem.text + '/' + subdir.text + ' ] || mkdir -p $@/' + nameElem.text + '/' + subdir.text
 425                            projTarget.extend(list(targetStr))
 426 arta  1.6  
 427                return rv
 428            
 429            def determineSection(line, regexpDefs, regexpMake, regexpProjMkRules, regexpProj, regexpProjCfg):
 430                matchobj = regexpDefs.match(line)
 431                if not matchobj is None:
 432                    return 'defs'
 433                    
 434                matchobj = regexpMake.match(line)
 435                if not matchobj is None:
 436                    return 'make'
 437                    
 438                matchobj = regexpProjMkRules.match(line)
 439                if not matchobj is None:
 440                    return 'projmkrules'
 441                    
 442                matchobj = regexpProj.match(line)
 443                if not matchobj is None:
 444                    return 'proj'
 445                    
 446                matchobj = regexpProjCfg.match(line)
 447 arta  1.6      if not matchobj is None:
 448                    return 'projcfg'
 449            
 450                return None
 451            
 452 arta  1.1  # defs is a dictionary containing all parameters (should they be needed in this script)
 453 arta  1.6  # projCfg is the list containing the configure script content.
 454            # projMkRules is the list containing the make_basic.mk content.
 455            # projRules is the list containing the Rules.mk content.
 456            # projTargert is the list containing the target.mk content.
 457 arta  1.18 def parseConfig(fin, keymap, addenda, defs, cDefs, mDefsGen, mDefsMake, projCfg, projMkRules, projRules, projTarget, perlConstSection, perlInitSection, pyConstSection, pyInitSection):
 458 arta  1.1      rv = bool(0)
 459                
 460                # Open required config file (config.local)
 461                try:
 462                    # Examine each line, looking for key=value pairs.
 463                    regexpDefs = re.compile(r"^__DEFS__")
 464                    regexpMake = re.compile(r"^__MAKE__")
 465 arta  1.6          regexpProjMkRules = re.compile(r"__PROJ_MK_RULES__")
 466                    regexpProj = re.compile(r"^__PROJ__")
 467                    regexpProjCfg = re.compile(r"^__PROJCFG__")
 468 arta  1.1          regexpComm = re.compile(r"^\s*#")
 469 arta  1.6          regexpSp = re.compile(r"^s*$")
 470 arta  1.1          regexpQuote = re.compile(r"^\s*(\w):(.+)")
 471 arta  1.6          regexpCustMkBeg = re.compile(r"^_CUST_")
 472                    regexpCustMkEnd = re.compile(r"^_ENDCUST_")
 473                    regexpDiv = re.compile(r"^__")
 474 arta  1.11         regexp = re.compile(r"^\s*(\S+)\s+(\S.*)")
 475 arta  1.1          
 476 arta  1.3          platDict = {}
 477                    machDict = {}
 478 arta  1.6          
 479                    xml = None
 480 arta  1.1          
 481                    # Process the parameters in the configuration file
 482                    if not fin is None:
 483                        for line in fin:
 484 arta  1.6                  matchobj = regexpComm.match(line)
 485                            if not matchobj is None:
 486                                # Skip comment line
 487                                continue
 488                            
 489                            matchobj = regexpSp.match(line)
 490                            if not matchobj is None:
 491                                # Skip whitespace line
 492                                continue
 493 arta  1.1              
 494 arta  1.6                  newSection = determineSection(line, regexpDefs, regexpMake, regexpProjMkRules, regexpProj, regexpProjCfg)
 495                            if not newSection is None:
 496                                section = newSection
 497                
 498                            if section == 'make':
 499 arta  1.10 
 500 arta  1.6                      # There are some blocks of lines in the __MAKE__ section that must be copied ver batim to the output make file. 
 501                                # The blocks are defined by _CUST_/_ENDCUST_ tags.
 502                                matchobj = regexpCustMkBeg.match(line)
 503                                    
 504                                if not matchobj is None:
 505                                    mDefsMake.extend(list('\n'))
 506                                    for line in fin:
 507                                        matchobj = regexpCustMkEnd.match(line)
 508                                        if not matchobj is None:
 509                                            break;
 510                                        mDefsMake.extend(list(line))
 511                                    newSection = determineSection(line, regexpDefs, regexpMake, regexpProjMkRules, regexpProj, regexpProjCfg)
 512                                    if not newSection is None:
 513                                        section = newSection
 514                                    continue
 515                                # Intentional fall through to next if statement
 516                            if section == 'defs' or section == 'make':
 517                                iscfg = bool(1)
 518 arta  1.18                     ppRet = processParam(iscfg, line, regexpQuote, regexp, keymap, defs, cDefs, mDefsGen, mDefsMake, perlConstSection, perlInitSection, pyConstSection, pyInitSection, platDict, machDict, section)
 519 arta  1.10                     
 520 arta  1.6                      if ppRet:
 521 arta  1.10                         break
 522 arta  1.6                  elif section == 'projcfg':
 523                                # Copy the line ver batim to the projCfg list (configure)
 524                                for line in fin:
 525                                    matchobj = regexpDiv.match(line)
 526                                    if not matchobj is None:
 527                                        break;
 528                                    projCfg.extend(list(line))
 529                                newSection = determineSection(line, regexpDefs, regexpMake, regexpProjMkRules, regexpProj, regexpProjCfg)
 530                                if not newSection is None:
 531                                    section = newSection
 532                                continue
 533                            elif section == 'projmkrules':
 534                                # Copy the line ver batim to the projMkRules list (make_basic.mk)
 535                                for line in fin:
 536                                    matchobj = regexpDiv.match(line)
 537                                    if not matchobj is None:
 538                                        break;
 539                                    projMkRules.extend(list(line))
 540                                newSection = determineSection(line, regexpDefs, regexpMake, regexpProjMkRules, regexpProj, regexpProjCfg)
 541                                if not newSection is None:
 542                                    section = newSection
 543 arta  1.6                      continue
 544                            elif section == 'proj':
 545                                # Must parse xml and use the project-specific information to populate the Rules.mk and target.mk files.
 546                                # Collect all xml lines for now, then process after file-read loop.
 547                                if xml is None:
 548                                    xml = line
 549                                else:
 550                                    xml += line
 551                            else:
 552 arta  1.10                     # Unknown section
 553 arta  1.6                      raise Exception('unknownSection', section)
 554 arta  1.1      except Exception as exc:
 555 arta  1.17         if len(exc.args) >= 2:
 556                        msg = exc.args[0]
 557                    else:
 558                        # re-raise the exception
 559                        raise
 560 arta  1.1          if msg == 'badKeyMapKey':
 561                        # If we are here, then there was a non-empty keymap, and the parameter came from
 562                        # the configuration file.
 563 arta  1.6              violator = exc.args[1]
 564 arta  1.17             print('Unknown parameter name ' + "'" + violator + "'" + ' in ' + fin.name + '.', file=sys.stderr)
 565 arta  1.1              rv = bool(1)
 566                    elif msg == 'badQuoteQual':
 567                        # The bad quote qualifier came from the configuration file, not the addenda, since
 568                        # we will have fixed any bad qualifiers in the addenda (which is populated by code).
 569 arta  1.6              violator = exc.args[1]
 570 arta  1.17             print('Unknown quote qualifier ' + "'" + violator + "'" + ' in ' + fin.name + '.', file=sys.stderr)
 571 arta  1.1              rv = bool(1)
 572                    elif msg == 'missingQuoteQual':
 573 arta  1.6              violator = exc.args[1]
 574 arta  1.17             print('Missing quote qualifier for parameter ' + "'" + violator + "'" + ' in ' + fin.name + '.', file=sys.stderr)
 575 arta  1.1              rv = bool(1)
 576                    elif msg == 'paramNameTooLong':
 577 arta  1.6              violator = exc.args[1]
 578 arta  1.1              print('Macro name ' + "'" + violator + "' is too long.", file=sys.stderr)
 579                        rv = bool(1)
 580 arta  1.6          elif msg == 'unknownSection':
 581                        violator = exc.args[1]
 582                        print('Unknown section ' + "'" + violator + "' in configuration file.", file=sys.stderr)
 583                        rv = bool(1)
 584 arta  1.1          else:
 585                        # re-raise the exception
 586                        raise
 587            
 588 arta  1.6      if not rv:
 589                    if not xml is None:
 590                        # Process xml.
 591                        projRules.extend(list(RULESPREFIX))
 592                        projTarget.extend(list(TARGETPREFIX))            
 593                        rv = processXML(xml, projRules, projTarget)
 594                        projRules.extend(RULESSUFFIX)
 595            
 596                # Process addenda - these are parameters that are not configurable and must be set in the 
 597                # NetDRMS build.
 598                if not rv:
 599                    iscfg = bool(0)
 600                    for key in addenda:
 601                        item = key + ' ' + addenda[key]
 602 arta  1.18             ppRet = processParam(iscfg, item, regexpQuote, regexp, keymap, defs, cDefs, mDefsGen, mDefsMake, perlConstSection, perlInitSection, pyConstSection, pyInitSection, platDict, machDict, 'defs')
 603 arta  1.6              if ppRet:
 604                            break;
 605            
 606 arta  1.4      # Put information collected in platDict and machDict into mDefs. Must do this here, and not in processParam, since
 607                # we need to parse all platform-specific make variables before grouping them into platform categories.
 608 arta  1.3      if not rv:
 609                    for plat in platDict:
 610 arta  1.4              mDefsMake.extend(list('\nifeq ($(JSOC_MACHINE), linux_' + plat.lower() + ')'))
 611 arta  1.3              for var in platDict[plat]:
 612 arta  1.4                  mDefsMake.extend(list('\n' + var + ' = ' + platDict[plat][var]))
 613                        mDefsMake.extend(list('\nendif\n'))
 614 arta  1.3                               
 615                if not rv:
 616                    for mach in machDict:
 617 arta  1.4              mDefsMake.extend(list('\nifeq ($(MACHTYPE), ' + mach + ')'))
 618 arta  1.7              for var in machDict[mach]:
 619                            mDefsMake.extend(list('\n' + var + ' = ' + machDict[mach][var]))
 620 arta  1.4              mDefsMake.extend(list('\nendif\n'))
 621 arta  1.1      return rv
 622            
 623            def getMgrUIDLine(defs, uidParam):
 624                rv = bool(0)
 625                
 626                cmd = 'id -u ' + defs['SUMS_MANAGER']
 627                try:
 628                    ret = check_output(cmd, shell=True)
 629                    uidParam['q:SUMS_MANAGER_UID'] = ret.decode("utf-8")
 630                except ValueError:
 631                    print('Unable to run cmd: ' + cmd + '.')
 632                    rv = bool(1)
 633                except CalledProcessError:
 634                    print('Command ' + "'" + cmd + "'" + ' ran improperly.')
 635                    rv = bool(1)
 636            
 637                return rv
 638            
 639 arta  1.3  def isVersion(maj, min, majDef, minDef):
 640                res = 0
 641                
 642                if maj > majDef or (maj == majDef and min >= minDef):
 643                    res = 1
 644                
 645                return res
 646            
 647            def configureComps(defs, mDefs):
 648                rv = bool(0)
 649 arta  1.6      autoConfig = bool(1)
 650            
 651                if 'AUTOSELCOMP' in defs:
 652                    autoConfig = (not defs['AUTOSELCOMP'] == '0')
 653 arta  1.3      
 654                if autoConfig:
 655                    hasicc = bool(0)
 656                    hasgcc = bool(0)
 657                    hasifort = bool(0)
 658                    hasgfort = bool(0)
 659                    
 660                    # Try icc.
 661 arta  1.12         cmd = 'icc --version 2>&1'
 662 arta  1.3          try:
 663                        ret = check_output(cmd, shell=True)
 664                        ret = ret.decode("utf-8")
 665                    except CalledProcessError:
 666                        print('Command ' + "'" + cmd + "'" + ' ran improperly.')
 667                        rv = bool(1)
 668                    
 669 arta  1.6          if not rv:
 670 arta  1.12             regexp = re.compile(r"\s*\S+\s+\S+\s+(\d+)[.](\d+)", re.DOTALL)
 671 arta  1.3              matchobj = regexp.match(ret)
 672                        if matchobj is None:
 673                            raise Exception('unexpectedIccRet', ret)
 674                        else:
 675                            major = matchobj.group(1)
 676                            minor = matchobj.group(2)
 677                            if isVersion(int(major), int(minor), ICC_MAJOR, ICC_MINOR):
 678                                hasicc = bool(1)
 679 arta  1.19 
 680 arta  1.3          # Try gcc.
 681                    if not hasicc:
 682 arta  1.19             rv = bool(0)
 683 arta  1.3              cmd = 'gcc -v 2>&1'
 684                        try:
 685                            ret = check_output(cmd, shell=True)
 686                            ret = ret.decode("utf-8")
 687                        except CalledProcessError:
 688                            print('Command ' + "'" + cmd + "'" + ' ran improperly.')
 689                            rv = bool(1)
 690            
 691 arta  1.19             if not rv:
 692 arta  1.3                  regexp = re.compile(r".+gcc\s+version\s+(\d+)\.(\d+)", re.DOTALL)
 693                            matchobj = regexp.match(ret)
 694                            if matchobj is None:
 695                                raise Exception('unexpectedGccRet', ret)
 696                            else:
 697                                major = matchobj.group(1)
 698                                minor = matchobj.group(2)
 699                                if isVersion(int(major), int(minor), GCC_MAJOR, GCC_MINOR):
 700                                    hasgcc = bool(1)
 701            
 702                    # Try ifort.
 703 arta  1.19         rv = bool(0)
 704 arta  1.12         cmd = 'ifort --version 2>&1'
 705 arta  1.3          try:
 706                        ret = check_output(cmd, shell=True)
 707                        ret = ret.decode("utf-8")
 708                    except CalledProcessError:
 709                        print('Command ' + "'" + cmd + "'" + ' ran improperly.')
 710                        rv = bool(1)
 711            
 712 arta  1.6          if not rv:
 713 arta  1.12             regexp = re.compile(r"\s*\S+\s+\S+\s+(\d+)\.(\d+)", re.DOTALL)
 714 arta  1.3              matchobj = regexp.match(ret)
 715                        if matchobj is None:
 716                            raise Exception('unexpectedIfortRet', ret)
 717                        else:
 718                            major = matchobj.group(1)
 719                            minor = matchobj.group(2)
 720                            if isVersion(int(major), int(minor), IFORT_MAJOR, IFORT_MINOR):
 721                                hasifort = bool(1)
 722                    
 723                    # Try gfortran
 724                    if not hasifort:
 725 arta  1.19             rv = bool(0)
 726 arta  1.3              cmd = 'gfortran -v 2>&1'
 727                        try:
 728                            ret = check_output(cmd, shell=True)
 729                            ret = ret.decode("utf-8")
 730                        except CalledProcessError:
 731                            print('Command ' + "'" + cmd + "'" + ' ran improperly.')
 732                            rv = bool(1)
 733            
 734 arta  1.19             if not rv:
 735 arta  1.3                  regexp = re.compile(r".+gcc\s+version\s+(\d+)\.(\d+)", re.DOTALL)
 736                            matchobj = regexp.match(ret)
 737                            if matchobj is None:
 738                                raise Exception('unexpectedGfortranRet', ret)
 739                            else:
 740                                major = matchobj.group(1)
 741                                minor = matchobj.group(2)
 742                                if isVersion(int(major), int(minor), GFORT_MAJOR, GFORT_MINOR):
 743                                    hasgfort = bool(1)
 744                    
 745 arta  1.19         # Append the compiler make variables to the make file
 746                    rv = bool(0)
 747                    
 748 arta  1.3          if not hasicc and not hasgcc:
 749                        print('Fatal error: Acceptable C compiler not found! You will be unable to build the DRMS library.', file=sys.stderr)
 750                        rv = bool(1)
 751                    elif hasicc:
 752                        mDefs.extend(list('\nCOMPILER = icc'))
 753                    else:
 754                        mDefs.extend(list('\nCOMPILER = gcc'))
 755            
 756                    if not hasifort and not hasgfort:
 757                        print('Warning: Acceptable Fortran compiler not found! Fortran interface will not be built, and you will be unable to build Fortran modules.', file=sys.stderr)
 758                    elif hasifort:
 759                        mDefs.extend(list('\nFCOMPILER = ifort'))
 760                    else:
 761                        mDefs.extend(list('\nFCOMPILER = gfortran'))
 762                
 763                    # Environment overrides. These get written, regardless of the disposition of auto-configuration.
 764 arta  1.9          mDefs.extend(list('\nifneq ($(JSOC_COMPILER),)\n  COMPILER = $(JSOC_COMPILER)\nendif'))
 765                    mDefs.extend(list('\nifneq ($(JSOC_FCOMPILER),)\n  FCOMPILER = $(JSOC_FCOMPILER)\nendif'))
 766 arta  1.3  
 767                return rv
 768            
 769 arta  1.18 def writeParamsFiles(base, cfile, mfile, pfile, pyfile, cDefs, mDefsGen, mDefsMake, mDefsComps, perlConstSection, perlInitSection, pyConstSection, pyInitSection):
 770 arta  1.1      rv = bool(0)
 771 arta  1.4  
 772                # Merge mDefsGen, mDefsMake, and mDefsComps into a single string with compiler configuration first, general parameters next, then
 773                # make-specific make variables (e.g., third-party library information) last.
 774                mDefs = '\n# Compiler Selection\n' + ''.join(mDefsComps) + '\n\n# General Parameters\n' + ''.join(mDefsGen) + '\n\n# Parameters to Configure make\n' + ''.join(mDefsMake)
 775 arta  1.1      
 776                try:
 777 arta  1.18         with open(cfile, 'w') as cout, open(mfile, 'w') as mout, open(pfile, 'w') as pout, open(pyfile, 'w') as pyout:
 778 arta  1.1              # C file of macros
 779 arta  1.2              print(C_PREFIX, file=cout)
 780                        print('/* This file contains a set of preprocessor macros - one for each configuration parameter. */\n', file=cout)
 781 arta  1.1              buf = '__' + base.upper() + '_H'
 782                        print('#ifndef ' + buf, file=cout)
 783                        print('#define ' + buf, file=cout)
 784                        print(''.join(cDefs), file=cout)
 785                        print('#endif', file=cout)
 786                        
 787                        # Make file of make variables
 788 arta  1.2              print(PREFIX, file=mout)
 789 arta  1.4              print('# This file contains a set of make-variable values. The first section contains compiler-selection variables, the second contains general configuration variables, and the third section contains variables that configure how make is run.', file=mout)
 790                        print(mDefs, file=mout)
 791 arta  1.1              
 792 arta  1.2              # Perl module
 793                        print(PERL_BINPATH, file=pout)
 794                        print(PREFIX, file=pout)
 795                        print('# This file contains a set of constants - one for each configuration parameter.\n', file=pout)
 796                        print(PERL_INTIAL, file=pout)
 797 arta  1.1              print(''.join(perlConstSection), file=pout)
 798 arta  1.2              print(PERL_FXNS_A, file=pout)
 799 arta  1.1              print('sub initialize', file=pout)
 800                        print('{', file=pout)
 801 arta  1.2              print('  my($self) = shift;', file=pout, end='')
 802 arta  1.1              print('', file=pout)
 803                        print(''.join(perlInitSection), file=pout)
 804 arta  1.2              print('}\n', file=pout)
 805                        print(PERL_FXNS_B, file=pout)
 806 arta  1.18 
 807                        # Python module
 808                        print(PY_BINPATH, file=pyout)
 809                        print(PREFIX, file=pyout)
 810                        print('# This file contains a set of constants - one for each configuration parameter.\n', file=pyout)
 811                        print(''.join(pyConstSection), file=pyout)
 812                        print(PY_FXNS_A, file=pyout, end='')
 813                        print(''.join(pyInitSection), file=pyout)
 814                        print(PY_FXNS_B, file=pyout)
 815            
 816 arta  1.1      except IOError as exc:
 817 arta  1.6          type, value, traceback = sys.exc_info()
 818                    print(exc.strerror, file=sys.stderr)
 819                    print('Unable to open ' + "'" + value.filename + "'.", file=sys.stderr)        
 820                    rv = bool(1)
 821            
 822                return rv
 823            
 824            def writeProjFiles(pCfile, pMfile, pRfile, pTfile, projCfg, projMkRules, projRules, projTarget):
 825                rv = bool(0)
 826            
 827                try:
 828                    if projCfg:
 829                        with open(pCfile, 'w') as cout:
 830                            # configure
 831                            print(''.join(projCfg), file=cout)
 832                    
 833                    if projMkRules:
 834                        with open(pMfile, 'w') as mout:
 835                            # make_basic.mk
 836                            print(PREFIX, file=mout)
 837                            print(''.join(projMkRules), file=mout)
 838 arta  1.6      
 839                    if projRules:
 840                        with open(pRfile, 'w') as rout:
 841                            # Rules.mk
 842                            print(PREFIX, file=rout)
 843                            print(''.join(projRules), file=rout)
 844                    
 845                    if projTarget:
 846                        with open(pTfile, 'w') as tout:
 847                            # target.mk
 848                            print(PREFIX, file=tout)
 849 arta  1.10                 print(''.join(projTarget), file=tout)
 850 arta  1.6      except IOError as exc:
 851                    type, value, traceback = sys.exc_info()
 852                    print(exc.strerror, file=sys.stderr)
 853                    print('Unable to open ' + "'" + value.filename + "'.", file=sys.stderr)
 854 arta  1.1          rv = bool(1)
 855            
 856 arta  1.6      if not rv:
 857 arta  1.10         if os.path.exists(pCfile):
 858                        try:
 859                            os.chmod(pCfile, stat.S_IRWXU | stat.S_IRGRP | stat.S_IROTH)
 860                        except OSError as exc:
 861                            type, value, traceback = sys.exc_info()
 862                            print('Unable to chmod file ' + "'" + value.filename + "'.", file=sys.stderr)
 863                            print(exc.strerror, file=sys.stderr)
 864                            rv = bool(1)
 865 arta  1.6  
 866 arta  1.1      return rv
 867 arta  1.3  
 868 arta  1.13 def generateSumRmCfg(defs):
 869                rv = bool(0)
 870                # ACK! Remember that Rick renamed these parameters. The ones in config.local are the aliases - do not use those.
 871                # Use the ones that those map to (defined in config.local.map).
 872                cFileTmp = defs['SUMLOG_BASEDIR'] + '/' + '.sum_rm.cfg.tmp'
 873                cFile = defs['SUMLOG_BASEDIR'] + '/' + 'sum_rm.cfg'
 874            
 875                # Write a temporary file sum_rm configuration file.
 876                try:
 877                    with open(cFileTmp, 'w') as fout:
 878                        # Print comment at the top of the configuration file.
 879                        print(SUMRM_COMMENT, file=fout)
 880                        print(SUMRM_DOC, file=fout)
 881                        print(SUMRM_PARTN_PERCENT_FREE, file=fout)
 882                        if 'SUMRM_PART_PERCENT_FREE' in defs:
 883                            print('PART_PERCENT_FREE=' + defs['SUMRM_PART_PERCENT_FREE'], file=fout)
 884                        else:
 885                            print('PART_PERCENT_FREE=3', file=fout)
 886            
 887                        print(SUMRM_SLEEP, file=fout)
 888                        if 'SUMRM_SLEEP' in defs:
 889 arta  1.13                 print('SLEEP=' + defs['SUMRM_SLEEP'], file=fout)
 890                        else:
 891                            print('SLEEP=300', file=fout)
 892            
 893                        print(SUMRM_LOG, file=fout)
 894                        if 'SUMRM_LOG' in defs:
 895                            print('LOG=' + defs['SUMRM_LOG'], file=fout)
 896                        else:
 897                            print('LOG=/tmp/sum_rm.log', file=fout)
 898            
 899                        print(SUMRM_MAIL, file=fout)
 900                        # No default for mail - don't send nothing to nobody unless the operator has asked for notifications.
 901                        if 'SUMRM_MAIL' in defs:
 902                            print('MAIL=' + defs['SUMRM_MAIL'], file=fout)
 903                        else:
 904                            print('# MAIL=president@whitehouse.gov', file=fout)
 905            
 906                        print(SUMRM_NOOP, file=fout)
 907                        if 'SUMRM_NOOP' in defs:
 908                            print('NOOP=' + defs['SUMRM_NOOP'], file=fout)
 909                        else:
 910 arta  1.13                 print('NOOP=0', file=fout)
 911            
 912                        print(SUMRM_USER, file=fout)
 913                        if 'SUMRM_USER' in defs:
 914                            print('USER=' + defs['SUMRM_USER'], file=fout)
 915                        else:
 916                            print('USER=production', file=fout)
 917            
 918                        print(SUMRM_NORUN, file=fout)
 919                        # Default norun window is to have no such window. This can be accomplished by simply not providing either argument.
 920                        if 'SUMRM_NORUN_START' in defs or 'SUMRM_NORUN_STOP' in defs:
 921                            if 'SUMRM_NORUN_START' in defs:
 922                                print('NORUN_START=' + defs['SUMRM_NORUN_START'], file=fout)
 923                            else:
 924                                print('NORUN_START=0', file=fout)
 925                            if 'SUMRM_NORUN_STOP' in defs:
 926                                print('NORUN_STOP=' + defs['SUMRM_NORUN_STOP'], file=fout)
 927                            else:
 928                                print('NORUN_STOP=0', file=fout)
 929                        else:
 930                            print('# NORUN_START=0', file=fout)
 931 arta  1.13                 print('# NORUN_STOP=0', file=fout)
 932                        
 933                except OSError:
 934                    print('Unable to open sum_rm temporary configuration file ' + cFileTmp + 'for writing.', file=sys.stderr)
 935                    rv = bool(1)
 936            
 937                # If the content of the temporary file differs from the content of the existing configuration file, then overwrite
 938                # the original file. Otherwise, delete the temporary file
 939                if not rv:
 940                    try:
 941                        if filecmp.cmp(cFile, cFileTmp):
 942                            # Files identical - delete temporary file
 943                            try:
 944                                os.remove(cFileTmp)
 945                            
 946                            except OSError as exc:
 947                                print('Unable to remove temporary file ' + exc.filename + '.', file=sys.stderr)
 948                                print(exc.strerr, file=sys.stderr)
 949                        else:
 950                            # Replace original with temporary file
 951                            try:
 952 arta  1.13                     os.rename(cFileTmp, cFile)
 953            
 954                            except OSError as exc:
 955                                print('Unable to update sum_rm configuration file ' + cFile + '.', file=sys.stderr)
 956                                print(exc.strerr, file=sys.stderr)
 957                                rv = bool(1)
 958                    except OSError as exc:
 959                        # One of the files doesn't exist.
 960                        if exc.filename == cFile:
 961                            # We are ok - there might be no configuration file yet.
 962                            # Replace original with temporary file
 963                            try:
 964                                os.rename(cFileTmp, cFile)
 965            
 966                            except OSError as exc:
 967                                print('Unable to update sum_rm configuration file ' + cFile + '.', file=sys.stderr)
 968                                print(exc.strerr, file=sys.stderr)
 969                                rv = bool(1)
 970                        else:
 971                            # There is a problem with the temp file - bail.
 972                            print('Unable to update sum_rm configuration file ' + cFile + '.', file=sys.stderr)
 973 arta  1.13                 print(exc.strerr, file=sys.stderr)
 974                            rv = bool(1)
 975            
 976                return rv
 977            
 978 arta  1.18 def configureNet(cfgfile, cfile, mfile, pfile, pyfile, pCfile, pMfile, pRfile, pTfile, base, keymap, createSumRmCfg):
 979 arta  1.1      rv = bool(0)
 980                
 981                defs = {}
 982                cDefs = list()
 983 arta  1.4      mDefsGen = list()
 984                mDefsMake = list()
 985                mDefsComps = list()
 986 arta  1.6      projCfg = list()
 987                projMkRules = list()
 988                projRules = list()
 989                projTarget = list()
 990 arta  1.1      perlConstSection = list()
 991                perlInitSection = list()
 992 arta  1.18     pyConstSection = list()
 993                pyInitSection = list()
 994 arta  1.2      addenda = {}
 995                
 996 arta  1.6      # There are three parameters that were not included in the original config.local parameter set, for some reason.
 997                # Due to this omission, then are not configurable, and must be set in the script.
 998 arta  1.2      addenda['a:USER'] = 'NULL'
 999                addenda['a:PASSWD'] = 'NULL'
1000                addenda['p:DSDS_SUPPORT'] = '0'
1001 arta  1.6      
1002                # This parameter is not configurable. BUILD_TYPE is used to distinguish between a NetDRMS and an JSOC-SDP build.
1003 arta  1.2      addenda['a:BUILD_TYPE'] = 'NETDRMS' # Means a non-Stanford build. This will set two additional macros used by make:
1004                                                    #   __LOCALIZED_DEFS__ and NETDRMS_BUILD. The former is to support legacy code
1005                                                    #   which incorrectly used this macro, and the latter is for future use. 
1006                                                    #   __LOCALIZED_DEFS__ is deprecated and should not be used in new code.
1007 arta  1.1  
1008                try:
1009                    with open(cfgfile, 'r') as fin:
1010 arta  1.3              # Process configuration parameters
1011 arta  1.18             rv = parseConfig(fin, keymap, addenda, defs, cDefs, mDefsGen, mDefsMake, projCfg, projMkRules, projRules, projTarget, perlConstSection, perlInitSection, pyConstSection, pyInitSection)
1012 arta  1.6              if not rv:
1013 arta  1.3                  # Must add a parameter for the SUMS_MANAGER UID (for some reason). This must be done after the
1014                            # config file is processed since an input to getMgrUIDLine() is one of the config file's
1015                            # parameter values.
1016 arta  1.1                  uidParam = {}
1017                            rv = getMgrUIDLine(defs, uidParam)
1018                            if rv == bool(0):
1019 arta  1.18                     rv = parseConfig(None, keymap, uidParam, defs, cDefs, mDefsGen, None, projCfg, projMkRules, projRules, projTarget, perlConstSection, perlInitSection, pyConstSection, pyInitSection)
1020 arta  1.3              # Configure the compiler-selection make variables.
1021 arta  1.6              if not rv:
1022 arta  1.4                  rv = configureComps(defs, mDefsComps)
1023 arta  1.1  
1024 arta  1.3              # Write out the parameter files.
1025 arta  1.6              if not rv:
1026 arta  1.18                 rv = writeParamsFiles(base, cfile, mfile, pfile, pyfile, cDefs, mDefsGen, mDefsMake, mDefsComps, perlConstSection, perlInitSection, pyConstSection, pyInitSection)
1027 arta  1.13 
1028 arta  1.6              # Write out the project-specific make files (make_basic.mk, Rules.mk, and target.mk).
1029                        if not rv:
1030                            rv = writeProjFiles(pCfile, pMfile, pRfile, pTfile, projCfg, projMkRules, projRules, projTarget)
1031 arta  1.13 
1032                        # Write out the sum_rm.cfg file.
1033                        if not rv and createSumRmCfg:
1034                            rv = generateSumRmCfg(defs)
1035 arta  1.1      except IOError as exc:
1036 arta  1.6          print(exc.strerror, file=sys.stderr)
1037                    print('Unable to read configuration file ' + cfgfile + '.', file=sys.stderr)
1038 arta  1.3      except Exception as exc:
1039 arta  1.16         if len(exc.args) >= 2:
1040 arta  1.14             type, msg = exc.args
1041                    else:
1042                        # re-raise the exception
1043                        raise
1044            
1045 arta  1.3          if type == 'unexpectedIccRet':
1046                        print('icc -V returned this unexpected message:\n' + msg, file=sys.stderr)
1047                        rv = bool(1)
1048                    elif type == 'unexpectedGccRet':
1049                        print('gcc -v returned this unexpected message:\n' + msg, file=sys.stderr)
1050                        rv = bool(1)
1051                    elif type == 'unexpectedIfortRet':
1052                        print('ifort -V returned this unexpected message:\n' + msg, file=sys.stderr)
1053                        rv = bool(1)
1054                    elif type == 'unexpectedGfortranRet':
1055                        print('gfortran -v returned this unexpected message:\n' + msg, file=sys.stderr)
1056                        rv = bool(1)
1057                    else:
1058                        # re-raise the exception
1059                        raise
1060 arta  1.1          
1061 arta  1.2      return rv
1062 arta  1.1  
1063 arta  1.18 def configureSdp(cfgfile, cfile, mfile, pfile, pyfile, pCfile, pMfile, pRfile, pTfile, base):
1064 arta  1.1      rv = bool(0)
1065                
1066                defs = {}
1067                cDefs = list()
1068 arta  1.5      mDefsGen = list()
1069                mDefsMake = list()
1070 arta  1.6      projCfg = list()
1071                projMkRules = list()
1072                projRules = list()
1073                projTarget = list()
1074 arta  1.5      mDefsComps = list()
1075 arta  1.1      perlConstSection = list()
1076                perlInitSection = list()
1077 arta  1.18     pyConstSection = list()
1078                pyInitSection = list()
1079            
1080 arta  1.2      addenda = {}
1081                
1082 arta  1.6      # There are three parameters that were not included in the original config.local parameter set, for some reason.
1083                # Due to this omission, then are not configurable, and must be set in the script.
1084 arta  1.5      addenda['a:USER'] = 'NULL'
1085                addenda['a:PASSWD'] = 'NULL'
1086                addenda['p:DSDS_SUPPORT'] = '1'
1087 arta  1.6      
1088                # This parameter is not configurable. BUILD_TYPE is used to distinguish between a NetDRMS and an JSOC-SDP build.
1089 arta  1.5      addenda['a:BUILD_TYPE'] = 'JSOC_SDP' # Means a Stanford build. This will set one additional macro used by make: JSOC_SDP_BUILD.
1090 arta  1.1      
1091                try:
1092                    with open(cfgfile, 'r') as fin:
1093 arta  1.18             rv = parseConfig(fin, None, addenda, defs, cDefs, mDefsGen, mDefsMake, projCfg, projMkRules, projRules, projTarget, perlConstSection, perlInitSection, pyConstSection, pyInitSection)
1094 arta  1.6              
1095                        if not rv:
1096 arta  1.2                  # Must add a parameter for the SUMS_MANAGER UID (for some reason)
1097                            uidParam = {}
1098                            rv = getMgrUIDLine(defs, uidParam)
1099 arta  1.6                  if not rv:
1100 arta  1.18                     rv = parseConfig(None, None, uidParam, defs, cDefs, mDefsGen, None, projCfg, projMkRules, projRules, projTarget, perlConstSection, perlInitSection, pyConstSection, pyInitSection)
1101 arta  1.6  
1102 arta  1.5                  # Configure the compiler-selection make variables.
1103 arta  1.6                  if not rv:
1104 arta  1.5                      rv = configureComps(defs, mDefsComps)
1105 arta  1.3                  
1106 arta  1.6                  # Write out the parameter files.
1107                            if not rv:
1108 arta  1.18                     rv = writeParamsFiles(base, cfile, mfile, pfile, pyfile, cDefs, mDefsGen, mDefsMake, mDefsComps, perlConstSection, perlInitSection, pyConstSection, pyInitSection)
1109 arta  1.6  
1110                            # Write out the project-specific make files (make_basic.mk, Rules.mk, and target.mk).
1111                            if not rv:
1112                                rv = writeProjFiles(pCfile, pMfile, pRfile, pTfile, projCfg, projMkRules, projRules, projTarget)
1113 arta  1.13 
1114                            # At Stanford, skip the creation of the sum_rm configuration file. config.local will still
1115                            # have the SUMRM parameters, but they will not be used.
1116 arta  1.1      except IOError as exc:
1117 arta  1.6          print(exc.strerror, file=sys.stderr)
1118                    print('Unable to read configuration file ' + cfgfile + '.', file=sys.stderr)
1119 arta  1.5      except Exception as exc:
1120 arta  1.17         if len(exc.args) >= 2:
1121                        type = exc.args[0]
1122                    else:
1123                        # re-raise the exception
1124                        raise
1125                    
1126 arta  1.5          if type == 'unexpectedIccRet':
1127 arta  1.6              msg = exc.args[1]
1128 arta  1.5              print('icc -V returned this unexpected message:\n' + msg, file=sys.stderr)
1129                        rv = bool(1)
1130                    elif type == 'unexpectedGccRet':
1131 arta  1.6              msg = exc.args[1]
1132 arta  1.5              print('gcc -v returned this unexpected message:\n' + msg, file=sys.stderr)
1133                        rv = bool(1)
1134                    elif type == 'unexpectedIfortRet':
1135 arta  1.6              msg = exc.args[1]
1136 arta  1.5              print('ifort -V returned this unexpected message:\n' + msg, file=sys.stderr)
1137                        rv = bool(1)
1138                    elif type == 'unexpectedGfortranRet':
1139 arta  1.6              msg = exc.args[1]
1140 arta  1.5              print('gfortran -v returned this unexpected message:\n' + msg, file=sys.stderr)
1141                        rv = bool(1)
1142                    else:
1143                        # re-raise the exception
1144                        raise
1145                    
1146 arta  1.2      return rv
1147            
1148 arta  1.1  # Beginning of program
1149            rv = RET_SUCCESS
1150            net = bool(1)
1151            
1152            # Parse arguments
1153            if __name__ == "__main__":
1154                optD = GetArgs(sys.argv[1:])
1155            
1156            if not(optD is None):
1157                # Ensure we are configuring a DRMS tree
1158                cdir = os.path.realpath(os.getcwd())
1159                versfile = cdir + '/base/' + VERS_FILE
1160            
1161                if not os.path.isfile(versfile):
1162                    rv = RET_NOTDRMS
1163            
1164            # Determine whether we are localizing a Stanford build, or a NetDRMS build. If configsdp.txt exists, then
1165            # it is a Stanford build, otherwise it is a NetDRMS build.
1166            if rv == RET_SUCCESS:
1167                stanfordFile = cdir + '/' + SDP_CFG
1168                if os.path.isfile(stanfordFile):
1169 arta  1.1          net = bool(0)
1170                
1171                cfile = optD['dir'] + '/' + optD['base'] + '.h'
1172                mfile = optD['dir'] + '/' + optD['base'] + '.mk'
1173                pfile = optD['dir'] + '/' + optD['base'] + '.pm'
1174 arta  1.18     pyfile = optD['dir'] + '/' + optD['base'] + '.py'
1175 arta  1.6      pCfile = optD['dir'] + '/configure'
1176                pMfile = optD['dir'] + '/make_basic.mk'
1177                pRfile = optD['dir'] + '/Rules.mk'
1178                pTfile = optD['dir'] + '/target.mk'
1179 arta  1.1  
1180                if net:
1181                    try:
1182                        with open(NET_CFGMAP, 'r') as fin:
1183                            regexpComm = re.compile(r"^\s*#")
1184                            regexp = re.compile(r"^\s*(\S+)\s+(\w:\S+)")
1185                            # Must map from config.local namespace to DRMS namespace (e.g., the names used for the C macros)
1186                            keymap = {}
1187                            for line in fin:
1188                                matchobj = regexpComm.match(line)
1189                                if not matchobj is None:
1190                                    # Skip comment line
1191                                    continue
1192            
1193                                matchobj = regexp.match(line)
1194                                if not(matchobj is None):
1195                                    # We have a key-value line
1196                                    key = matchobj.group(1)
1197                                    val = matchobj.group(2)
1198                                    keymap[key] = val
1199                    except OSError:
1200 arta  1.1              sys.stderr.write('Unable to read configuration map-file ' + NET_CFGMAP + '.')
1201                        rv = bool(1)
1202            
1203                    # We also need to set the UID of the SUMS manager. We have the name of the
1204                    # SUMS manager (it is in the configuration file)
1205 arta  1.18         configureNet(NET_CFG, cfile, mfile, pfile, pyfile, pCfile, pMfile, pRfile, pTfile, optD['base'], keymap, 'server' in optD)
1206 arta  1.1      else:
1207 arta  1.8          # A Stanford user can override the parameters in configsdp.txt by copying that file to config.local, 
1208                    # and then editing config.local. So, if config.local exists, use that.
1209                    if os.path.isfile(cdir + '/' + NET_CFG):
1210 arta  1.18             configureSdp(NET_CFG, cfile, mfile, pfile, pyfile, pCfile, pMfile, pRfile, pTfile, optD['base'])
1211 arta  1.8          else:
1212 arta  1.18             configureSdp(SDP_CFG, cfile, mfile, pfile, pyfile, pCfile, pMfile, pRfile, pTfile, optD['base'])

Karen Tian
Powered by
ViewCVS 0.9.4