def CreateServiceInstance(self, serviceName): old_block_trap = stackless.getcurrent().block_trap stackless.getcurrent().block_trap = 1 try: try: createName, createClass = self.classmapWithReplacements[ serviceName] except KeyError: self._BuildClassMap() try: createName, createClass = self.classmapWithReplacements[ serviceName] except KeyError: raise ServiceNotFound(serviceName) if createName != serviceName: print 'Replacing service %r with %r' % (serviceName, createName) replaceService = getattr(createClass, '__replaceservice__', None) if replaceService is not None and replaceService != serviceName: raise RuntimeError( 'Must not start %s directly as it replaces %s' % (serviceName, replaceService)) srv = createClass() if not isinstance(srv, service.Service): raise RuntimeError( 'Service name %r does not resolve to a service class (%r)' % (serviceName, createClass)) srv.__servicename__ = serviceName srv.session = base.GetServiceSession(serviceName) self.VerifyServiceExports(srv, serviceName) return srv finally: stackless.getcurrent().block_trap = old_block_trap
def CheckCredentials(username, password): sess = CreateSession(username, password) if macho.mode == 'client': cherrypy.session['machoSession'] = sess return auth = base.GetServiceSession('cherry').ConnectToAnyService( 'authentication') sptype = const.userConnectTypeServerPages try: sessstuff, _ = auth.Login(sess.sid, username, password, None, sptype, cherrypy.request.remote.ip) except UserError: return u'Incorrect username or password' except Exception: return u'Incorrect username or password' session = CreateSession(username, password) sessstuff['role'] |= sess.role for otherSession in base.FindSessions('userid', [sessstuff['userid']]): otherSession.LogSessionHistory( 'Usurped by user %s via HTTP using local authentication' % username) base.CloseSession(otherSession) cherrypy.session['machoSession'] = sess sess.SetAttributes(sessstuff)
def Bind(self, sess = None, call = None): """ Binds the moniker, performing the first call as well if the params are specified, using the given session. If no session is specified, a service session is used. """ localKeywords = ('machoTimeout', 'noCallThrottling') done = {} while 1: try: if self.__bindParams is None: raise RuntimeError("Thou shall not use None as a Moniker's __bindParams") if '__semaphoreB__' not in self.__dict__: self.__semaphoreB__ = uthread.Semaphore(('moniker::Bind', self.__serviceName, self.__bindParams)) self.__semaphoreB__.acquire() try: if not self.boundObject: if self.__nodeID is None: self.__ResolveImpl(0, sess) if sess is None: if session and base.IsInClientContext(): sess = session elif session and session.role == ROLE_SERVICE: sess = session.GetActualSession() else: sess = base.GetServiceSession('util.Moniker') else: sess = sess.GetActualSession() if self.__nodeID == sm.GetService('machoNet').GetNodeID(): service = sess.ConnectToService(self.__serviceName) self.boundObject = service.MachoGetObjectBoundToSession(self.__bindParams, sess) else: remotesvc = sess.ConnectToRemoteService(self.__serviceName, self.__nodeID) self.__PerformSessionCheck() if call is not None and call[2]: c2 = {k:v for k, v in call[2].iteritems() if k not in localKeywords} call = (call[0], call[1], c2) self.boundObject, retval = remotesvc.MachoBindObject(self.__bindParams, call) self.boundObject.persistantObjectID = (self.__serviceName, self.__bindParams) return retval finally: done[self.__serviceName, self.__bindParams] = 1 self.__semaphoreB__.release() if call is not None: return self.MonikeredCall(call, sess) return except UpdateMoniker as e: if (e.serviceName, e.bindParams) in done: log.LogException() raise RuntimeError('UpdateMoniker referred us to the same location twice', (e.serviceName, e.bindParams)) else: self.__bindParams = e.bindParams self.__serviceName = e.serviceName self.__nodeID = e.nodeID self.Unbind() sys.exc_clear()
def GetConfigSvc(self): if not self.servicebroker: sess = base.GetServiceSession('cfg') if 'config' in sm.services: config = sess.ConnectToService('config') self.servicebroker = sess self.server = 1 elif boot.role == 'proxy': self.servicebroker = ProxyServiceBroker() self.client = 1 else: self.servicebroker = sess.ConnectToService('connection') if not self.servicebroker.IsConnected(): if sm.GetService('machoNet').authenticating != 1: raise RuntimeError('NotConnected') self.client = 1 return self.servicebroker.ConnectToService('config')
def __ResolveImpl(self, justQuery, sess=None): if '__semaphoreR__' not in self.__dict__: self.__semaphoreR__ = uthread.Semaphore( ('moniker::Resolve', self.__serviceName, self.__bindParams)) self.__semaphoreR__.acquire() try: if self.__nodeID is not None: return self.__nodeID if macho.mode == 'client' or base.IsInClientContext(): self.__nodeID = sm.services['machoNet'].GuessNodeIDFromAddress( self.__serviceName, self.__bindParams) if self.__nodeID is not None: return self.__nodeID if not self.__nodeID: self.__nodeID = sm.services['machoNet']._addressCache.Get( self.__serviceName, self.__bindParams) if self.__nodeID is not None: return self.__nodeID if sess is None: if session and session.role == ROLE_SERVICE: sess = session.GetActualSession() else: sess = base.GetServiceSession('util.Moniker') else: sess = sess.GetActualSession() if justQuery == 2: service = sm.services.get(self.__serviceName, None) if service is None: return elif macho.mode == 'client' or base.IsInClientContext(): service = sess.ConnectToRemoteService(self.__serviceName) else: service = sess.ConnectToAnyService(self.__serviceName) self.__nodeID = service.MachoResolveObject(self.__bindParams, justQuery) if self.__nodeID is None and not justQuery: raise RuntimeError( 'Resolution failure: ResolveObject returned None') if macho.mode == 'client' or base.IsInClientContext(): sm.services['machoNet'].SetNodeOfAddress( self.__serviceName, self.__bindParams, self.__nodeID) return self.__nodeID finally: self.__semaphoreR__.release()
def _AssociateWithSession(self, packet=None, forceNodeID=None): if forceNodeID is not None: nodeID = forceNodeID serviceSession = True elif macho.mode == 'client': nodeID = 0 serviceSession = False elif not packet.command % 2: if packet.source.addressType == const.ADDRESS_TYPE_CLIENT: nodeID = packet.source.clientID serviceSession = False else: nodeID = packet.source.nodeID serviceSession = True elif packet.destination.addressType == const.ADDRESS_TYPE_CLIENT: nodeID = packet.destination.clientID serviceSession = False else: nodeID = packet.destination.nodeID serviceSession = True sess = self.sessions.get(nodeID, None) if not sess: sess = self.contextSessions.get(nodeID, None) if not sess: if macho.mode == 'client': sess = session elif serviceSession: sess = base.GetServiceSession('remote:%d' % nodeID, True) elif not packet.command % 2: if not isinstance(packet, macho.SessionInitialStateNotification): log.LogTraceback( 'Packet received before initial session notification. Packet/tasklet reordering?' ) raise SessionUnavailable( 'Unable to load session for request') sess = base.CreateSession(packet.sid, packet.sessionType) else: raise UnMachoDestination( 'Failed session association: cmd = %s, mode = %s' % (packet.command, macho.mode)) sess.__dict__['clientID'] = nodeID if sess.contextOnly: self.contextSessions[nodeID] = sess else: self.sessions[nodeID] = sess if serviceSession: role = sess.__dict__['role'] | ROLE_SERVICE | ROLE_REMOTESERVICE sess.SetAttributes({'role': role}) sess.LogSessionHistory( 'machoNet associated remote service session with clientID/nodeID %s' % nodeID) else: sess.__dict__['rwlock'] = uthread.RWLock( ('sessions', sess.sid)) packetUserID = None if packet is None else packet.userID if packetUserID is not None: sess.SetAttributes({'userid': packetUserID}) sess.LogSessionHistory( 'machoNet associated session with clientID %s and userID %s' % (nodeID, packetUserID)) sess.lastRemoteCall = blue.os.GetWallclockTime() return (nodeID, sess)
def GetSvc(self, serviceid): if not self.servicebroker: sess = base.GetServiceSession('cfg') self.servicebroker = sess self.server = 1 return self.servicebroker.ConnectToService(serviceid)
def ConnectToService(self, name): sess = base.GetServiceSession('cfg') return sess.ConnectToRemoteService(name)
def GetSession(parent, request, response, sessionsBySID, sessionsByFlatkaka): parent.LogInfo('GetSession') if request.cookie.has_key('flatkaka'): flatkaka = request.cookie['flatkaka'] if sessionsByFlatkaka.has_key(flatkaka): sess = sessionsByFlatkaka[flatkaka] if macho.mode == 'client': return sess uspa = request.Authorization() if uspa != None: u = sess.esps.contents['username'] p = sess.esps.contents['password'] if uspa[0] != u or uspa[1] != p: parent.LogWarn("User %s is trying to hijack %s's session, with sessID=%d" % (uspa[0], u, sess.sid)) else: parent.LogInfo('cookie information verified') return sess sess = None success = False if macho.mode == 'client': sess = base.CreateSession(None, const.session.SESSION_TYPE_ESP, None) sess.esps = ESPSession(parent, sess.sid) success = True else: usernameAndPassword = request.Authorization() reason = 'Access denied' statusCode = '401 Unauthorized' if usernameAndPassword != None: parent.LogInfo('GetSession uap<>n') username = usernameAndPassword[0] password = usernameAndPassword[1] for s in sessionsBySID.itervalues(): if hasattr(s, 'esps') and s.esps.contents['username'] == username: if s.userid and s.esps.contents['password'] == password: return s break if macho.mode == 'server' and ('authentication' not in sm.services or sm.services['authentication'].state != service.SERVICE_RUNNING): blue.pyos.synchro.SleepWallclock(3000) raise UserError('AutClusterStarting') try: if sm.services['http'].session.ConnectToProxyServerService('machoNet').CheckACL(request.ep.address, espCheck=True): blue.pyos.synchro.SleepWallclock(3000) raise UserError('AutClusterStarting') except UnMachoDestination: blue.pyos.synchro.SleepWallclock(3000) raise UserError('AutClusterStarting') sessionID = base.GetNewSid() sess = base.CreateSession(sessionID, const.session.SESSION_TYPE_ESP) sess.esps = ESPSession(parent, sess.sid) auth = base.GetServiceSession('httpService').ConnectToAnyService('authentication') try: try: sessstuff, _ = auth.Login(sessionID, username, password, None, const.userConnectTypeServerPages, request.ep.address) sessstuff['role'] |= sess.role except UserError as e: if e.msg != 'CharacterInDifferentRegion': raise sys.exc_clear() for each in base.FindSessions('userid', [sessstuff['userid']]): each.LogSessionHistory('Usurped by user %s via HTTP using local authentication' % username) base.CloseSession(each) sess.LogSessionHistory('Authenticating user %s via HTTP using local authentication' % username) sess.SetAttributes(sessstuff) sess.LogSessionHistory('Authenticated user %s via HTTP using local authentication' % username) success = True except UnMachoDestination: reason = 'The proxy server was unable to connect to any Sol Server Node to handle your authentication request.' statusCode = '500 No Sol Server available' sys.exc_clear() except UserError as e: if e.msg != 'LoginAuthFailed': raise sys.exc_clear() if not success: sess.LogSessionHistory('Session closed due to local authentication failure') base.CloseSession(sess) parent.LogInfo('GetSession done auth %s' % success) if success: sessID = sess.sid while sessionsBySID.has_key(sessID): parent.LogWarn('Session %d already exits, adding 1 to it' % sessID) sessID += 1 sessionsBySID[sessID] = sess sessionsByFlatkaka[sess.esps.GetFlatkaka()] = sess parent.OnSessionBegin(sessID) session = sess session.cacheList = [] session.requestCount = 0 session.esps.contents['timeoutTimer'] = None if macho.mode != 'client': session.esps.contents['username'] = username session.esps.contents['password'] = password return session else: response.Clear() response.status = statusCode response.Write(reason) response.authenticate = 1 response.Flush() return