buildframework/helium/sf/python/pythoncore/lib/ccm/__init__.py
changeset 628 7c4a911dc066
parent 588 c7c26511138f
child 645 b8d81fa19e7d
equal deleted inserted replaced
588:c7c26511138f 628:7c4a911dc066
    39 
    39 
    40 
    40 
    41 VALID_OBJECT_STATES = ('working', 'checkpoint', 'public', 'prep', 'integrate', 'sqa', 'test','released')
    41 VALID_OBJECT_STATES = ('working', 'checkpoint', 'public', 'prep', 'integrate', 'sqa', 'test','released')
    42 STATIC_OBJECT_STATES = ('integrate', 'sqa', 'test','released')
    42 STATIC_OBJECT_STATES = ('integrate', 'sqa', 'test','released')
    43 CCM_SESSION_LOCK = os.path.join(tempfile.gettempdir(), "ccm_session.lock")
    43 CCM_SESSION_LOCK = os.path.join(tempfile.gettempdir(), "ccm_session.lock")
    44 
    44 if os.path == '\\':
    45 def _execute(command, timeout=None):
    45     # on windows platform we need insulation of session opening
       
    46     # so the _router.adr doesn't get modified while
       
    47     # opening a session. This must be in a common location.
       
    48     TEMPDIR = os.path.join(os.environ['SYSTEMROOT'], 'temp')
       
    49     if not os.path.exists(TEMPDIR):
       
    50         TEMPDIR = os.environ['TEMP']
       
    51     CCM_SESSION_LOCK = os.path.join(TEMPDIR, "ccm_session.lock")
       
    52 
       
    53 def execute(command, timeout=None):
    46     """ Runs a command and returns the result data. """
    54     """ Runs a command and returns the result data. """
    47     targ = ""
    55     targ = ""
    48     if timeout is not None:
    56     if timeout is not None:
    49         targ = "--timeout=%s" % timeout
    57         targ = "--timeout=%s" % timeout
    50     process = subprocess.Popen("python -m timeout_launcher %s -- %s" % (targ, command), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)
    58     process = subprocess.Popen("python -m timeout_launcher %s -- %s" % (targ, command), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)
    70     def __init__(self, session):
    78     def __init__(self, session):
    71         self._session = session
    79         self._session = session
    72         self.status = None
    80         self.status = None
    73         self._output = None
    81         self._output = None
    74         self._output_str = None
    82         self._output_str = None
       
    83         self.error = None
    75     
    84     
    76     def _setoutput(self, output):
    85     def _setoutput(self, output):
    77         """set output"""
    86         """set output"""
    78         self._output = output
    87         self._output = output
    79         
    88         
   114         
   123         
   115     def __seterror(self, error):
   124     def __seterror(self, error):
   116         """ Internal function to allow overloading, you must override _seterror.
   125         """ Internal function to allow overloading, you must override _seterror.
   117         """
   126         """
   118         # the error output is automatically converted to ascii before any treatment 
   127         # the error output is automatically converted to ascii before any treatment 
   119         if isinstance(error, unicode):
   128         if error is not None:
   120             self._error_str = error.encode('ascii', 'replace')
   129             if isinstance(error, unicode):
   121         else:
   130                 self._error_str = error.encode('ascii', 'replace')
   122             self._error_str = error.decode('ascii', 'ignore')
   131             else:
   123         _logger.debug("error ---->")
   132                 self._error_str = error.decode('ascii', 'ignore')
   124         for line in self._error_str.splitlines():
   133             _logger.debug("error ---->")
   125             _logger.debug(line)
   134             for line in self._error_str.splitlines():
   126         _logger.debug("<----")
   135                 _logger.debug(line)
   127         self._seterror(self._error_str)
   136             _logger.debug("<----")
       
   137             self._seterror(self._error_str)
   128                 
   138                 
   129     def _geterror(self):
   139     def _geterror(self):
   130         """ Returns the content of _output. """
   140         """ Returns the content of _output. """
   131         _logger.debug("_geterror")
   141         _logger.debug("_geterror")
   132         return self._error
   142         return self._error
   604         """ retrieve the database path from current session status. """
   614         """ retrieve the database path from current session status. """
   605         _logger.debug("AbstractSession: __find_dbpath")
   615         _logger.debug("AbstractSession: __find_dbpath")
   606         if (self.dbpath != None):            
   616         if (self.dbpath != None):            
   607             return
   617             return
   608         result = self.execute("status")
   618         result = self.execute("status")
   609         for match in re.finditer(r'(?:(?:Graphical)|(?:Command)) Interface\s+@\s+(?P<ccmaddr>\w+:\d+(?:\:\d+\.\d+\.\d+\.\d+)+)(?P<current_session>\s+\(current\s+session\))?\s*\nDatabase:\s*(?P<dbpath>\S+)', result.output, re.M | re.I):
   619         
   610             dictionary = match.groupdict()
   620         gotsession = False
   611             if (dictionary['current_session'] != None):
   621         for line in result.output.splitlines():
   612                 _logger.debug("AbstractSession: __find_dbpath: Found dbpath: %s" % dictionary['dbpath'])
   622             if gotsession:
   613                 self.dbpath = dictionary['dbpath']
   623                 gotsession = False
   614         assert self.dbpath != None
   624                 if 'Database:' in line:
       
   625                     self.dbpath = line.replace('Database:', '').strip()
       
   626                     _logger.debug("AbstractSession: __find_dbpath: Found dbpath: %s" % self.dbpath)
       
   627             if '(current session)' in line:
       
   628                 gotsession = True
       
   629         if not self.dbpath:
       
   630             raise Exception('self.dbpath is None ' + result.output)
   615     
   631     
   616     def execute(self, _, result=None):
   632     def execute(self, _, result=None):
   617         """ Abstract function that should implement the execution of ccm command
   633         """ Abstract function that should implement the execution of ccm command
   618             line call.
   634             line call.
   619         """
   635         """
   737         if CCM_BIN == None:
   753         if CCM_BIN == None:
   738             raise CCMException("Could not find CM/Synergy executable in the path.")
   754             raise CCMException("Could not find CM/Synergy executable in the path.")
   739         command = "%s start -m -q -nogui -n %s -pw %s -h %s -d %s" % \
   755         command = "%s start -m -q -nogui -n %s -pw %s -h %s -d %s" % \
   740                     (CCM_BIN, username, password, engine, dbpath)
   756                     (CCM_BIN, username, password, engine, dbpath)
   741         _logger.debug('Starting new session:' + command.replace(password, "***"))
   757         _logger.debug('Starting new session:' + command.replace(password, "***"))
   742         (result, status) = _execute(command, timeout=timeout)
   758         (result, status) = execute(command, timeout=timeout)
   743         if status != 0:
   759         if status != 0:
   744             raise Exception("Error creating a session: result:\n%s\nCommand: %s" % (result, command.replace(password, "***")))
   760             raise CCMException("Error creating a session: result:\n%s\nCommand: %s" % (result, command.replace(password, "***")))
   745         session_addr = result.strip()
   761         session_addr = result.strip()
   746         _logger.debug(session_addr)
   762         _logger.debug(session_addr)
   747         if not re.match(r'[a-zA-Z0-9_\-.]+:\d+:\d+\.\d+\.\d+\.\d+(:\d+\.\d+\.\d+\.\d+)?', session_addr):
   763         if not re.match(r'[a-zA-Z0-9_\-.]+:\d+:\d+\.\d+\.\d+\.\d+(:\d+\.\d+\.\d+\.\d+)?', session_addr):
   748             raise Exception("Error creating a session: result:\n%s" % result)
   764             raise CCMException("Error creating a session: result:\n%s" % result)
   749         return Session(username, engine, dbpath, session_addr)        
   765         return Session(username, engine, dbpath, session_addr)        
   750             
   766             
   751     def execute(self, cmdline, result=None):
   767     def execute(self, cmdline, result=None):
   752         """ Executes a Synergy CLI operation. """
   768         """ Executes a Synergy CLI operation. """
   753         if self._session_addr == None:
   769         if self._session_addr == None:
   759         error = ""
   775         error = ""
   760         try:
   776         try:
   761             if result == None:
   777             if result == None:
   762                 result = Result(self)
   778                 result = Result(self)
   763             if os.sep == '\\':
   779             if os.sep == '\\':
   764                 command = "set CCM_ADDR=" + self._session_addr + " && " + CCM_BIN + " %s" % cmdline
   780                 command = "set CCM_ADDR=" + self._session_addr + " && \"" + CCM_BIN + "\" %s" % cmdline
   765             else:
   781             else:
   766                 command = "export CCM_ADDR=" + self._session_addr + " && " + CCM_BIN + " %s" % cmdline
   782                 command = "export CCM_ADDR=" + self._session_addr + " && " + CCM_BIN + " %s" % cmdline
   767             _logger.debug('Execute > ' + command)
   783             _logger.debug('Execute > ' + command)
   768 
   784 
   769             if hasattr(result, 'error'):
   785             if hasattr(result, 'error'):
  1909     else:
  1925     else:
  1910         # looking for router address using GSCM database
  1926         # looking for router address using GSCM database
  1911         router_address = None
  1927         router_address = None
  1912         if database == None and dbpath != None:
  1928         if database == None and dbpath != None:
  1913             database = os.path.basename(dbpath)
  1929             database = os.path.basename(dbpath)
  1914         
  1930                 
  1915         lock = fileutils.Lock(CCM_SESSION_LOCK)
  1931         lock = fileutils.Lock(CCM_SESSION_LOCK)
  1916         try:
  1932         try:
       
  1933             _logger.info("Locking " + CCM_SESSION_LOCK)
  1917             lock.lock(wait=True)
  1934             lock.lock(wait=True)
  1918             # if we have the database name we can switch to the correct Synergy router
  1935             # if we have the database name we can switch to the correct Synergy router
  1919             if database != None:
  1936             if database != None:
  1920                 _logger.info('Getting router address.')
  1937                 _logger.info('Getting router address.')
  1921                 router_address = nokia.gscm.get_router_address(database)
  1938                 router_address = nokia.gscm.get_router_address(database)
  1930                         routerfile.close()
  1947                         routerfile.close()
  1931         
  1948         
  1932             # If no existing sessions were available, start a new one
  1949             # If no existing sessions were available, start a new one
  1933             _logger.info('Opening session.')
  1950             _logger.info('Opening session.')
  1934             new_session = Session.start(username, password, engine, dbpath)
  1951             new_session = Session.start(username, password, engine, dbpath)
       
  1952             _logger.info("Unlocking " + CCM_SESSION_LOCK)
  1935             lock.unlock()
  1953             lock.unlock()
  1936             return new_session
  1954             return new_session
  1937         finally:
  1955         finally:
       
  1956             _logger.info("Unlocking " + CCM_SESSION_LOCK)
  1938             lock.unlock()
  1957             lock.unlock()
  1939     raise CCMException("Cannot open session for user '%s'" % username)
  1958     raise CCMException("Cannot open session for user '%s'" % username)
  1940 
  1959 
  1941 
  1960 
  1942 def get_role_for_purpose(session, purpose):
  1961 def get_role_for_purpose(session, purpose):
  1967     _logger.debug('Querying for existing Synergy sessions')
  1986     _logger.debug('Querying for existing Synergy sessions')
  1968     if CCM_BIN == None:
  1987     if CCM_BIN == None:
  1969         raise CCMException("Could not find CM/Synergy executable in the path.")
  1988         raise CCMException("Could not find CM/Synergy executable in the path.")
  1970     command = "%s status" % (CCM_BIN)
  1989     command = "%s status" % (CCM_BIN)
  1971 
  1990 
       
  1991     _logger.info("Locking " + CCM_SESSION_LOCK)
  1972     lock = fileutils.Lock(CCM_SESSION_LOCK)
  1992     lock = fileutils.Lock(CCM_SESSION_LOCK)
  1973     result = ""
  1993     result = ""
  1974     output = []
  1994     output = []
  1975     try:
  1995     try:
  1976         # if we have the database name we can switch to the correct Synergy router
  1996         # if we have the database name we can switch to the correct Synergy router
  1987                     routerfile = open(os.path.join(os.path.dirname(CCM_BIN), "../etc/_router.adr"), "w+")
  2007                     routerfile = open(os.path.join(os.path.dirname(CCM_BIN), "../etc/_router.adr"), "w+")
  1988                     routerfile.write("%s\n" % router_address)
  2008                     routerfile.write("%s\n" % router_address)
  1989                     routerfile.close()
  2009                     routerfile.close()
  1990 
  2010 
  1991         _logger.debug('Command: ' + command)
  2011         _logger.debug('Command: ' + command)
  1992         (result, status) = _execute(command)
  2012         (result, status) = execute(command)
  1993         if database != None:
  2013         if database != None:
  1994             lock.unlock()
  2014             lock.unlock()
  1995         if (status != 0):
  2015         if (status != 0):
  1996             raise CCMException("Ccm status execution returned an error.")
  2016             raise CCMException("Ccm status execution returned an error. " + command + " " + result)
  1997         _logger.debug('ccm status result: ' + result)
  2017         _logger.debug('ccm status result: ' + result)
  1998         for match in re.finditer(r'Command Interface\s+@\s+(?P<ccmaddr>\w+:\d+:\d+.\d+.\d+.\d+(:\d+.\d+.\d+.\d+)*)(?P<current_session>\s+\(current\s+session\))?\s+Database:\s*(?P<dbpath>\S+)', result, re.M):
  2018         for match in re.finditer(r'Command Interface\s+@\s+(?P<ccmaddr>\w+:\d+:\d+.\d+.\d+.\d+(:\d+.\d+.\d+.\d+)*)(?P<current_session>\s+\(current\s+session\))?\s+Database:\s*(?P<dbpath>\S+)', result, re.M):
  1999             data = match.groupdict()
  2019             data = match.groupdict()
  2000             _logger.debug(data['ccmaddr'])
  2020             _logger.debug(data['ccmaddr'])
  2001             _logger.debug(socket.gethostname())
  2021             _logger.debug(socket.gethostname())
  2006                 existing_session = Session(None, None, data['dbpath'], data['ccmaddr'], close_on_exit=False)
  2026                 existing_session = Session(None, None, data['dbpath'], data['ccmaddr'], close_on_exit=False)
  2007                 _logger.debug('Existing session found: %s' % existing_session)
  2027                 _logger.debug('Existing session found: %s' % existing_session)
  2008                 output.append(existing_session)
  2028                 output.append(existing_session)
  2009     finally:
  2029     finally:
  2010         if database != None:
  2030         if database != None:
       
  2031             _logger.info("Unlocking " + CCM_SESSION_LOCK)
  2011             lock.unlock()
  2032             lock.unlock()
  2012     return  output
  2033     return  output
  2013 
  2034 
  2014 def session_exists(sessionid, database=None):
  2035 def session_exists(sessionid, database=None):
  2015     """determine if session exists"""
  2036     """determine if session exists"""