def checkForRemoval(self, userService: UserService) -> None: """ This method is used by UserService when a request for setInUse(False) is made This checks that the service can continue existing or not """ osManager = userService.deployed_service.osmanager # If os manager says "machine is persistent", do not try to delete "previous version" assigned machines doPublicationCleanup = True if not osManager else not osManager.getInstance( ).isPersistent() if doPublicationCleanup: remove = False with transaction.atomic(): userService = UserService.objects.select_for_update().get( id=userService.id) activePublication = userService.deployed_service.activePublication( ) if userService.publication and activePublication and userService.publication.id != activePublication.id: logger.debug( 'Old revision of user service, marking as removable: %s', userService) remove = True if remove: userService.remove()
def notifyPreconnect(self, userService: UserService, userName: str, protocol: str) -> None: ''' Notifies a preconnect to an user service ''' proxy = userService.deployed_service.proxy url = userService.getCommsUrl() ip, hostname = userService.getConnectionSource() if not url: logger.debug('No notification is made because agent does not supports notifications') return url += '/preConnect' try: data = {'user': userName, 'protocol': protocol, 'ip': ip, 'hostname': hostname} if proxy is not None: r = proxy.doProxyRequest(url=url, data=data, timeout=2) else: r = requests.post( url, data=json.dumps(data), headers={'content-type': 'application/json'}, verify=False, timeout=2 ) r = json.loads(r.content) logger.debug('Sent pre-connection to client using %s: %s', url, r) # In fact we ignore result right now except Exception as e: logger.info('preConnection failed: %s. Check connection on destination machine: %s', e, url)
def removeOrCancel(self, userService: UserService): if userService.isUsable() or State.isRemovable(userService.state): return self.remove(userService) if userService.isPreparing(): return self.cancel(userService) raise OperationException(_('Can\'t remove nor cancel {} cause its state don\'t allow it').format(userService.name))
def reset(self, userService: UserService) -> None: userService.refresh_from_db() if not userService.deployed_service.service.getType().canReset: return logger.debug('Reseting %s', userService) userServiceInstance = userService.getInstance() try: userServiceInstance.reset() except Exception: logger.exception('Reseting service')
def remove(self, userService: UserService) -> UserService: """ Removes a uService element """ with transaction.atomic(): userService = UserService.objects.select_for_update().get( id=userService.id) logger.debug('Removing userService %a', userService) if userService.isUsable() is False and State.isRemovable( userService.state) is False: raise OperationException( _('Can\'t remove a non active element')) userService.setState(State.REMOVING) logger.debug("***** The state now is %s *****", State.toString(userService.state)) userService.setInUse( False ) # For accounting, ensure that it is not in use right now userService.save() userServiceInstance = userService.getInstance() state = userServiceInstance.destroy() # Data will be serialized on makeUnique process UserServiceOpChecker.makeUnique(userService, userServiceInstance, state) return userService
def cancel(self, userService: UserService) -> UserService: """ Cancels an user service creation @return: the Uservice canceling """ userService.refresh_from_db() logger.debug('Canceling userService %s creation', userService) if userService.isPreparing() is False: logger.info( 'Cancel requested for a non running operation, performing removal instead' ) return self.remove(userService) userServiceInstance = userService.getInstance() if not userServiceInstance.supportsCancel( ): # Does not supports cancel, but destroy, so mark it for "later" destroy # State is kept, just mark it for destroy after finished preparing userService.setProperty('destroy_after', 'y') else: userService.setState(State.CANCELING) # We simply notify service that it should cancel operation state = userServiceInstance.cancel() # Data will be serialized on makeUnique process # If cancel is not supported, base cancel always returns "FINISHED", and # opchecker will set state to "removable" UserServiceOpChecker.makeUnique(userService, userServiceInstance, state) return userService
def process_logout(userService: UserService, username: str) -> None: """ This method is static so can be invoked from elsewhere """ osManager: typing.Optional[ osmanagers.OSManager] = userService.getOsManagerInstance() if userService.in_use: # If already logged out, do not add a second logout (windows does this i.e.) osmanagers.OSManager.loggedOut(userService, username) if osManager: if osManager.isRemovableOnLogout(userService): logger.debug('Removable on logout: %s', osManager) userService.remove() else: userService.remove()
def checkAndUpdateState(userService: UserService, userServiceInstance: UserDeployment, state: str): """ Checks the value returned from invocation to publish or checkPublishingState, updating the servicePoolPub database object Return True if it has to continue checking, False if finished """ try: # Fills up basic data userService.unique_id = userServiceInstance.getUniqueId( ) # Updates uniqueId userService.friendly_name = userServiceInstance.getName( ) # And name, both methods can modify serviceInstance, so we save it later userService.save(update_fields=['unique_id', 'friendly_name']) updater = { State.PREPARING: UpdateFromPreparing, State.REMOVING: UpdateFromRemoving, State.CANCELING: UpdateFromCanceling }.get(userService.state, UpdateFromOther) logger.debug('Updating %s from %s with updater %s and state %s', userService.friendly_name, State.toString(userService.state), updater, state) updater(userService, userServiceInstance).run(state) except Exception as e: logger.exception('Checking service state') log.doLog(userService, log.ERROR, 'Exception: {}'.format(e), log.INTERNAL) userService.setState(State.ERROR) userService.save(update_fields=['data'])
def requestLogoff(self, userService: UserService) -> None: """ Ask client to logoff user """ proxy = userService.deployed_service.proxy url = userService.getCommsUrl() if not url: logger.error('Can\'t connect with actor (no actor or legacy actor)') return url += '/logoff' try: data: typing.Dict = {} if proxy: r = proxy.doProxyRequest(url=url, data=data, timeout=5) else: r = requests.post( url, data=json.dumps(data), headers={'content-type': 'application/json'}, verify=False, timeout=4 ) r = json.loads(r.content) logger.debug('Sent logoff to client using %s: %s', url, r) # In fact we ignore result right now except Exception: # logger.info('Logoff requested but service was not listening: %s', e, url) pass
def sendScript(self, userService: UserService, script: str, forUser: bool = False) -> None: """ If allowed, send script to user service """ proxy = userService.deployed_service.proxy # logger.debug('Senging script: {}'.format(script)) url = userService.getCommsUrl() if not url: logger.error('Can\'t connect with actor (no actor or legacy actor)') return url += '/script' try: data = {'script': script} if forUser: data['user'] = '******' # Just must exists "user" parameter, don't mind value if proxy: r = proxy.doProxyRequest(url=url, data=data, timeout=5) else: r = requests.post( url, data=json.dumps(data), headers={'content-type': 'application/json'}, verify=False, timeout=5 ) r = json.loads(r.content) logger.debug('Sent script to client using %s: %s', url, r) # In fact we ignore result right now except Exception as e: logger.error('Exception caught sending script: %s. Check connection on destination machine: %s', e, url)
def process_login(userService: UserService, username: str) -> typing.Optional[osmanagers.OSManager]: osManager: typing.Optional[ osmanagers.OSManager] = userService.getOsManagerInstance() if not userService.in_use: # If already logged in, do not add a second login (windows does this i.e.) osmanagers.OSManager.loggedIn(userService, username) return osManager
def itemToDict(item: UserService) -> typing.Dict[str, typing.Any]: """ Converts an assigned/cached service db item to a dictionary for REST response :param item: item to convert :param is_cache: If item is from cache or not """ props = item.getProperties() if item.user is None: owner = '' owner_info = {'auth_id': '', 'user_id': ''} else: owner = item.user.pretty_name owner_info = { 'auth_id': item.user.manager.uuid, 'user_id': item.user.uuid } return { 'id': item.uuid, 'state_date': item.state_date, 'creation_date': item.creation_date, 'unique_id': item.unique_id, 'friendly_name': item.friendly_name, 'owner': owner, 'owner_info': owner_info, 'service': item.deployed_service.service.name, 'service_id': item.deployed_service.service.uuid, 'pool': item.deployed_service.name, 'pool_id': item.deployed_service.uuid, 'ip': props.get('ip', _('unknown')), 'source_host': item.src_hostname, 'source_ip': item.src_ip, 'in_use': item.in_use }
def notifyReadyFromOsManager(self, uService, data): try: ui = uService.getInstance() logger.debug('Notifying user service ready state') state = ui.notifyReadyFromOsManager(data) logger.debug('State: {0}'.format(state)) uService.updateData(ui) if state == State.FINISHED: logger.debug('Service is now ready') uService.save() elif uService.state in (State.USABLE, State.PREPARING): # We don't want to get active deleting or deleted machines... uService.setState(State.PREPARING) UserServiceOpChecker.makeUnique(uService, ui, state) except Exception as e: logger.exception('Unhandled exception on notyfyReady: {}'.format(e)) UserService.setState(State.ERROR) return
def itemToDict(item: models.UserService, is_cache: bool = False) -> typing.Dict[str, typing.Any]: """ Converts an assigned/cached service db item to a dictionary for REST response :param item: item to convert :param is_cache: If item is from cache or not """ props = item.getProperties() val = { 'id': item.uuid, 'id_deployed_service': item.deployed_service.uuid, 'unique_id': item.unique_id, 'friendly_name': item.friendly_name, 'state': item.state if not (props.get('destroy_after') and item.state == State.PREPARING) else State.CANCELING, 'os_state': item.os_state, 'state_date': item.state_date, 'creation_date': item.creation_date, 'revision': item.publication and item.publication.revision or '', 'ip': props.get('ip', _('unknown')), 'actor_version': props.get('actor_version', _('unknown')), } if is_cache: val['cache_level'] = item.cache_level else: if item.user is None: owner = '' owner_info = {'auth_id': '', 'user_id': ''} else: owner = item.user.pretty_name owner_info = { 'auth_id': item.user.manager.uuid, 'user_id': item.user.uuid } val.update({ 'owner': owner, 'owner_info': owner_info, 'in_use': item.in_use, 'in_use_date': item.in_use_date, 'source_host': item.src_hostname, 'source_ip': item.src_ip }) return val
def isReady(self, userService: UserService) -> bool: userService.refresh_from_db() logger.debug('Checking ready of %s', userService) if userService.state != State.USABLE or userService.os_state != State.USABLE: logger.debug('State is not usable for %s', userService.name) return False logger.debug('Service %s is usable, checking it via setReady', userService) userServiceInstance = userService.getInstance() try: state = userServiceInstance.setReady() except Exception as e: logger.warn('Could not check readyness of %s: %s', userService, e) return False logger.debug('State: %s', state) if state == State.FINISHED: userService.updateData(userServiceInstance) return True userService.setState(State.PREPARING) UserServiceOpChecker.makeUnique(userService, userServiceInstance, state) return False
def serviceList(self): # We look for services for this authenticator groups. User is logged in in just 1 authenticator, so his groups must coincide with those assigned to ds groups = list(self._user.getGroups()) availServices = DeployedService.getDeployedServicesForGroups(groups) availUserServices = UserService.getUserAssignedServices(self._user) # Extract required data to show to user services = [] # Select assigned user services for svr in availUserServices: # Skip maintenance services... trans = [] for t in svr.transports.all().order_by('priority'): if t.validForIp(self._request.ip) and t.getType( ).providesConnetionInfo(): trans.append({'id': t.uuid, 'name': t.name}) services.append({ 'id': 'A' + svr.uuid, 'name': svr['name'], 'transports': trans, 'maintenance': svr.isInMaintenance(), 'in_use': svr.in_use }) logger.debug(services) # Now generic user service for svr in availServices: trans = [] for t in svr.transports.all().order_by('priority'): if t.validForIp(self._request.ip) and t.getType( ).providesConnetionInfo(): trans.append({'id': t.uuid, 'name': t.name}) # Locate if user service has any already assigned user service for this ads = UserServiceManager.manager().getExistingAssignationForUser( svr, self._user) if ads is None: in_use = False else: in_use = ads.in_use services.append({ 'id': 'F' + svr.uuid, 'name': svr.name, 'transports': trans, 'maintenance': svr.isInMaintenance(), 'in_use': in_use }) logger.debug('Services: {0}'.format(services)) services = sorted(services, key=lambda s: s['name'].upper()) return Connection.result(result=services)
def notifyReadyFromOsManager(self, uService, data): try: ui = uService.getInstance() logger.debug('Notifying user service ready state') state = ui.notifyReadyFromOsManager(data) logger.debug('State: {0}'.format(state)) uService.updateData(ui) if state == State.FINISHED: logger.debug('Service is now ready') uService.save() elif uService.state in ( State.USABLE, State.PREPARING ): # We don't want to get active deleting or deleted machines... uService.setState(State.PREPARING) UserServiceOpChecker.makeUnique(uService, ui, state) except Exception as e: logger.exception( 'Unhandled exception on notyfyReady: {}'.format(e)) UserService.setState(State.ERROR) return
def checkUuid(self, userService: UserService) -> bool: ''' Checks if the uuid of the service is the same of our known uuid on DB ''' proxy = userService.deployed_service.proxy url = userService.getCommsUrl() if not url: logger.debug('No uuid to retrieve because agent does not supports notifications') return True # UUid is valid because it is not supported checking it version = userService.getProperty('actor_version') or '' # Just for 2.0 or newer, previous actors will not support this method. # Also externally supported agents will not support this method (as OpenGnsys) if '-' in version or version < '2.0.0': return True url += '/uuid' try: if proxy: r = proxy.doProxyRequest(url=url, timeout=5) else: r = requests.get(url, verify=False, timeout=5) if version >= '3.0.0': # New type of response: {'result': uuid} uuid = r.json()['result'] else: uuid = r.json() if uuid != userService.uuid: logger.info('The requested machine has uuid %s and the expected was %s', uuid, userService.uuid) return False logger.debug('Got uuid from machine: %s %s %s', url, uuid, userService.uuid) # In fact we ignore result right now except Exception as e: logger.error('Get uuid failed: %s. Check connection on destination machine: %s', e, url) return True
def moveToLevel(self, cache: UserService, cacheLevel: int) -> None: """ Moves a cache element from one level to another @return: cache element """ cache.refresh_from_db() logger.debug('Moving cache %s to level %s', cache, cacheLevel) cacheInstance = cache.getInstance() state = cacheInstance.moveToCache(cacheLevel) cache.cache_level = cacheLevel cache.save(update_fields=['cache_level']) logger.debug('Service State: %a %s %s', State.toString(state), State.toString(cache.state), State.toString(cache.os_state)) if State.isRuning(state) and cache.isUsable(): cache.setState(State.PREPARING) # Data will be serialized on makeUnique process UserServiceOpChecker.makeUnique(cache, cacheInstance, state)
def notifyReadyFromOsManager(self, userService: UserService, data: typing.Any) -> None: try: userServiceInstance = userService.getInstance() logger.debug('Notifying user service ready state') state = userServiceInstance.notifyReadyFromOsManager(data) logger.debug('State: %s', state) if state == State.FINISHED: userService.updateData(userServiceInstance) logger.debug('Service is now ready') elif userService.state in (State.USABLE, State.PREPARING): # We don't want to get active deleting or deleted machines... userService.setState(State.PREPARING) UserServiceOpChecker.makeUnique(userService, userServiceInstance, state) userService.save(update_fields=['os_state']) except Exception as e: logger.exception('Unhandled exception on notyfyReady: %s', e) userService.setState(State.ERROR) return
def serviceList(self): # We look for services for this authenticator groups. User is logged in in just 1 authenticator, so his groups must coincide with those assigned to ds groups = list(self._user.getGroups()) availServices = DeployedService.getDeployedServicesForGroups(groups) availUserServices = UserService.getUserAssignedServices(self._user) # Extract required data to show to user services = [] # Select assigned user services for svr in availUserServices: # Skip maintenance services... trans = [] for t in svr.transports.all().order_by('priority'): typeTrans = t.getType() if t.validForIp(self._request.ip) and t.getType().providesConnetionInfo(): trans.append({'id': t.uuid, 'name': t.name, 'needsJava': t.getType().needsJava}) services.append({'id': 'A' + svr.uuid, 'name': svr['name'], 'transports': trans, 'maintenance': svr.deployed_service.service.provider.maintenance_mode, 'in_use': svr.in_use}) logger.debug(services) # Now generic user service for svr in availServices: trans = [] for t in svr.transports.all().order_by('priority'): if t.validForIp(self._request.ip) and t.getType().providesConnetionInfo(): typeTrans = t.getType() trans.append({'id': t.uuid, 'name': t.name, 'needsJava': typeTrans.needsJava}) # Locate if user service has any already assigned user service for this ads = UserServiceManager.manager().getExistingAssignationForUser(svr, self._user) if ads is None: in_use = False else: in_use = ads.in_use services.append({'id': 'F' + svr.uuid, 'name': svr.name, 'transports': trans, 'maintenance': svr.service.provider.maintenance_mode, 'in_use': in_use}) logger.debug('Services: {0}'.format(services)) services = sorted(services, key=lambda s: s['name'].upper()) return Connection.result(result=services)
def index(request): """ Renders the main page. :param request: http request """ if request.session.get('ticket') == '1': return webLogout(request) # Session data os = request.os # We look for services for this authenticator groups. User is logged in in just 1 authenticator, so his groups must coincide with those assigned to ds groups = list(request.user.getGroups()) availServices = DeployedService.getDeployedServicesForGroups(groups) availUserServices = UserService.getUserAssignedServices(request.user) # Information for administrators nets = '' validTrans = '' logger.debug('OS: {0}'.format(os['OS'])) if request.user.isStaff(): nets = ','.join([n.name for n in Network.networksFor(request.ip)]) tt = [] for t in Transport.objects.all(): if t.validForIp(request.ip): tt.append(t.name) validTrans = ','.join(tt) # Extract required data to show to user services = [] # Select assigned user services (manually assigned) for svr in availUserServices: trans = [] for t in svr.transports.all().order_by('priority'): typeTrans = t.getType() if t.validForIp(request.ip) and typeTrans.supportsOs( os['OS']) and t.validForOs(os['OS']): if typeTrans.ownLink is True: link = reverse('TransportOwnLink', args=('A' + svr.uuid, t.uuid)) else: link = html.udsAccessLink(request, 'A' + svr.uuid, t.uuid) trans.append({'id': t.uuid, 'name': t.name, 'link': link}) servicePool = svr.deployed_service if servicePool.image is not None: imageId = servicePool.image.uuid else: imageId = 'x' # Invalid # Extract app group group = servicePool.servicesPoolGroup if servicePool.servicesPoolGroup is not None else ServicesPoolGroup.default( ).as_dict services.append({ 'id': 'A' + svr.uuid, 'name': servicePool.name, 'visual_name': servicePool.visual_name, 'description': servicePool.comments, 'group': group, 'transports': trans, 'imageId': imageId, 'show_transports': servicePool.show_transports, 'allow_users_remove': servicePool.allow_users_remove, 'allow_users_reset': servicePool.allow_users_reset, 'maintenance': servicePool.isInMaintenance(), 'not_accesible': not servicePool.isAccessAllowed(), 'in_use': svr.in_use, 'to_be_replaced': False, # Manually assigned will not be autoremoved never 'comments': servicePool.comments, }) logger.debug(services) # Now generic user service for svr in availServices: trans = [] for t in svr.transports.all().order_by('priority'): typeTrans = t.getType() if typeTrans is None: # This may happen if we "remove" a transport type but we have a transport of that kind on DB continue if t.validForIp(request.ip) and typeTrans.supportsOs( os['OS']) and t.validForOs(os['OS']): if typeTrans.ownLink is True: link = reverse('TransportOwnLink', args=('F' + svr.uuid, t.uuid)) else: link = html.udsAccessLink(request, 'F' + svr.uuid, t.uuid) trans.append({'id': t.uuid, 'name': t.name, 'link': link}) if svr.image is not None: imageId = svr.image.uuid else: imageId = 'x' # Locate if user service has any already assigned user service for this ads = UserServiceManager.manager().getExistingAssignationForUser( svr, request.user) if ads is None: in_use = False else: in_use = ads.in_use group = svr.servicesPoolGroup.as_dict if svr.servicesPoolGroup is not None else ServicesPoolGroup.default( ).as_dict tbr = svr.toBeReplaced() if tbr is not None: tbr = formats.date_format(tbr, "SHORT_DATETIME_FORMAT") tbrt = ugettext( 'This service is about to be replaced by a new version. Please, close the session before {} and save all your work to avoid loosing it.' ).format(tbr) else: tbrt = '' services.append({ 'id': 'F' + svr.uuid, 'name': svr.name, 'visual_name': svr.visual_name, 'description': svr.comments, 'group': group, 'transports': trans, 'imageId': imageId, 'show_transports': svr.show_transports, 'allow_users_remove': svr.allow_users_remove, 'allow_users_reset': svr.allow_users_reset, 'maintenance': svr.isInMaintenance(), 'not_accesible': not svr.isAccessAllowed(), 'in_use': in_use, 'to_be_replaced': tbr, 'to_be_replaced_text': tbrt, 'comments': svr.comments, }) logger.debug('Services: {0}'.format(services)) services = sorted(services, key=lambda s: s['name'].upper()) autorun = False if len(services) == 1 and GlobalConfig.AUTORUN_SERVICE.getBool( True) and len(services[0]['transports']) > 0: if request.session.get('autorunDone', '0') == '0': request.session['autorunDone'] = '1' autorun = True # return redirect('uds.web.views.service', idService=services[0]['id'], idTransport=services[0]['transports'][0]['id']) # List of services groups allGroups = [ v for v in sorted([ser['group'] for ser in services], key=lambda s: s['priority']) ] # Now remove duplicates groups = [] already = [] for g in allGroups: if g['name'] not in already: already.append(g['name']) groups.append(g) logger.debug('Groups: {}'.format(groups)) response = render( request, theme.template('index.html'), { 'groups': groups, 'services': services, 'ip': request.ip, 'nets': nets, 'transports': validTrans, 'autorun': autorun }) return response
def index(request): ''' Renders the main page. :param request: http request ''' # Session data os = request.os # We look for services for this authenticator groups. User is logged in in just 1 authenticator, so his groups must coincide with those assigned to ds groups = list(request.user.getGroups()) availServices = DeployedService.getDeployedServicesForGroups(groups) availUserServices = UserService.getUserAssignedServices(request.user) # Information for administrators nets = '' validTrans = '' logger.debug('OS: {0}'.format(os['OS'])) if request.user.isStaff(): nets = ','.join([n.name for n in Network.networksFor(request.ip)]) tt = [] for t in Transport.objects.all(): if t.validForIp(request.ip): tt.append(t.name) validTrans = ','.join(tt) # Extract required data to show to user services = [] # Select assigned user services for svr in availUserServices: trans = [] for t in svr.transports.all().order_by('priority'): typeTrans = t.getType() if t.validForIp(request.ip) and typeTrans.supportsOs(os['OS']): if typeTrans.ownLink is True: link = reverse('TransportOwnLink', args=('A' + svr.uuid, t.uuid)) else: link = html.udsAccessLink(request, 'A' + svr.uuid, t.uuid) trans.append({'id': t.uuid, 'name': t.name, 'link': link}) if svr.deployed_service.image is not None: imageId = svr.deployed_service.image.uuid else: imageId = 'x' # Invalid services.append({ 'id': 'A' + svr.uuid, 'name': svr['name'], 'transports': trans, 'imageId': imageId, 'show_transports': svr.deployed_service.show_transports, 'maintenance': svr.deployed_service.service.provider.maintenance_mode, 'in_use': svr.in_use, }) logger.debug(services) # Now generic user service for svr in availServices: # Generate ticket trans = [] for t in svr.transports.all().order_by('priority'): typeTrans = t.getType() if t.validForIp(request.ip) and typeTrans.supportsOs(os['OS']): if typeTrans.ownLink is True: link = reverse('TransportOwnLink', args=('F' + svr.uuid, t.uuid)) else: link = html.udsAccessLink(request, 'F' + svr.uuid, t.uuid) trans.append({'id': t.uuid, 'name': t.name, 'link': link}) if svr.image is not None: imageId = svr.image.uuid else: imageId = 'x' # Locate if user service has any already assigned user service for this ads = UserServiceManager.manager().getExistingAssignationForUser( svr, request.user) if ads is None: in_use = False else: in_use = ads.in_use services.append({ 'id': 'F' + svr.uuid, 'name': svr.name, 'transports': trans, 'imageId': imageId, 'show_transports': svr.show_transports, 'maintenance': svr.service.provider.maintenance_mode, 'in_use': in_use, }) logger.debug('Services: {0}'.format(services)) services = sorted(services, key=lambda s: s['name'].upper()) if len(services) == 1 and GlobalConfig.AUTORUN_SERVICE.get( True) == '1' and len(services[0]['transports']) > 0: if request.session.get('autorunDone', '0') == '0': request.session['autorunDone'] = '1' # TODO: Make this to redirect to uds link directly return redirect('uds.web.views.service', idService=services[0]['id'], idTransport=services[0]['transports'][0]['id']) response = render_to_response(theme.template('index.html'), { 'services': services, 'ip': request.ip, 'nets': nets, 'transports': validTrans, }, context_instance=RequestContext(request)) return response
def serviceList(self): # We look for services for this authenticator groups. User is logged in in just 1 authenticator, so his groups must coincide with those assigned to ds groups = list(self._user.getGroups()) availServices = DeployedService.getDeployedServicesForGroups(groups) availUserServices = UserService.getUserAssignedServices(self._user) # Extract required data to show to user services = [] # Select assigned user services for svr in availUserServices: # Skip maintenance services... trans = [] for t in svr.transports.all().order_by('priority'): if t.validForIp(self._request.ip) and t.getType().providesConnetionInfo(): trans.append({'id': t.uuid, 'name': t.name}) servicePool = svr.deployed_service services.append({'id': 'A' + svr.uuid, 'name': servicePool.name, 'description': servicePool.comments, 'visual_name': servicePool.visual_name, 'group': servicePool.servicesPoolGroup if servicePool.servicesPoolGroup is not None else ServicesPoolGroup.default().as_dict, 'thumb': servicePool.image.thumb64 if servicePool.image is not None else DEFAULT_THUMB_BASE64, 'show_transports': servicePool.show_transports, 'allow_users_remove': servicePool.allow_users_remove, 'maintenance': servicePool.isInMaintenance(), 'not_accesible': not servicePool.isAccessAllowed(), 'to_be_replaced': False, # Manually assigned will not be autoremoved never 'transports': trans, 'maintenance': servicePool.isInMaintenance(), 'in_use': servicePool.in_use}) logger.debug(services) # Now generic user service for servicePool in availServices: trans = [] for t in servicePool.transports.all().order_by('priority'): if t.validForIp(self._request.ip) and t.getType().providesConnetionInfo(): trans.append({'id': t.uuid, 'name': t.name}) # Locate if user service has any already assigned user service for this ads = userServiceManager().getExistingAssignationForUser(servicePool, self._user) if ads is None: in_use = False else: in_use = ads.in_use services.append({'id': 'F' + servicePool.uuid, 'name': servicePool.name, 'description': servicePool.comments, 'visual_name': servicePool.visual_name, 'group': servicePool.servicesPoolGroup if servicePool.servicesPoolGroup is not None else ServicesPoolGroup.default().as_dict, 'thumb': servicePool.image.thumb64 if servicePool.image is not None else DEFAULT_THUMB_BASE64, 'show_transports': servicePool.show_transports, 'allow_users_remove': servicePool.allow_users_remove, 'maintenance': servicePool.isInMaintenance(), 'not_accesible': not servicePool.isAccessAllowed(), 'to_be_replaced': servicePool.toBeReplaced(), 'transports': trans, 'maintenance': servicePool.isInMaintenance(), 'in_use': in_use}) logger.debug('Services: {0}'.format(services)) services = sorted(services, key=lambda s: s['name'].upper()) return Connection.result(result=services)
def index(request): """ Renders the main page. :param request: http request """ if request.session.get('ticket') == '1': return webLogout(request) # Session data os = request.os # We look for services for this authenticator groups. User is logged in in just 1 authenticator, so his groups must coincide with those assigned to ds groups = list(request.user.getGroups()) availServices = DeployedService.getDeployedServicesForGroups(groups) availUserServices = UserService.getUserAssignedServices(request.user) # Information for administrators nets = '' validTrans = '' logger.debug('OS: {0}'.format(os['OS'])) if request.user.isStaff(): nets = ','.join([n.name for n in Network.networksFor(request.ip)]) tt = [] for t in Transport.objects.all(): if t.validForIp(request.ip): tt.append(t.name) validTrans = ','.join(tt) # Extract required data to show to user services = [] # Select assigned user services (manually assigned) for svr in availUserServices: trans = [] for t in svr.transports.all().order_by('priority'): typeTrans = t.getType() if t.validForIp(request.ip) and typeTrans.supportsOs(os['OS']) and t.validForOs(os['OS']): if typeTrans.ownLink is True: link = reverse('TransportOwnLink', args=('A' + svr.uuid, t.uuid)) else: link = html.udsAccessLink(request, 'A' + svr.uuid, t.uuid) trans.append( { 'id': t.uuid, 'name': t.name, 'link': link } ) servicePool = svr.deployed_service if servicePool.image is not None: imageId = servicePool.image.uuid else: imageId = 'x' # Invalid # Extract app group group = servicePool.servicesPoolGroup if servicePool.servicesPoolGroup is not None else ServicesPoolGroup.default().as_dict services.append({ 'id': 'A' + svr.uuid, 'name': servicePool.name, 'visual_name': servicePool.visual_name, 'description': servicePool.comments, 'group': group, 'transports': trans, 'imageId': imageId, 'show_transports': servicePool.show_transports, 'allow_users_remove': servicePool.allow_users_remove, 'maintenance': servicePool.isInMaintenance(), 'not_accesible': not servicePool.isAccessAllowed(), 'in_use': svr.in_use, 'to_be_replaced': False, # Manually assigned will not be autoremoved never 'comments': servicePool.comments, }) logger.debug(services) # Now generic user service for svr in availServices: trans = [] for t in svr.transports.all().order_by('priority'): typeTrans = t.getType() if typeTrans is None: # This may happen if we "remove" a transport type but we have a transport of that kind on DB continue if t.validForIp(request.ip) and typeTrans.supportsOs(os['OS']) and t.validForOs(os['OS']): if typeTrans.ownLink is True: link = reverse('TransportOwnLink', args=('F' + svr.uuid, t.uuid)) else: link = html.udsAccessLink(request, 'F' + svr.uuid, t.uuid) trans.append( { 'id': t.uuid, 'name': t.name, 'link': link } ) if svr.image is not None: imageId = svr.image.uuid else: imageId = 'x' # Locate if user service has any already assigned user service for this ads = UserServiceManager.manager().getExistingAssignationForUser(svr, request.user) if ads is None: in_use = False else: in_use = ads.in_use group = svr.servicesPoolGroup.as_dict if svr.servicesPoolGroup is not None else ServicesPoolGroup.default().as_dict tbr = svr.toBeReplaced() if tbr is not None: tbr = formats.date_format(tbr, "SHORT_DATETIME_FORMAT") tbrt = ugettext('This service is about to be replaced by a new version. Please, close the session before {} and save all your work to avoid loosing it.').format(tbr) else: tbrt = '' services.append({ 'id': 'F' + svr.uuid, 'name': svr.name, 'visual_name': svr.visual_name, 'description': svr.comments, 'group': group, 'transports': trans, 'imageId': imageId, 'show_transports': svr.show_transports, 'allow_users_remove': svr.allow_users_remove, 'maintenance': svr.isInMaintenance(), 'not_accesible': not svr.isAccessAllowed(), 'in_use': in_use, 'to_be_replaced': tbr, 'to_be_replaced_text': tbrt, 'comments': svr.comments, }) logger.debug('Services: {0}'.format(services)) services = sorted(services, key=lambda s: s['name'].upper()) autorun = False if len(services) == 1 and GlobalConfig.AUTORUN_SERVICE.getBool(True) and len(services[0]['transports']) > 0: if request.session.get('autorunDone', '0') == '0': request.session['autorunDone'] = '1' autorun = True # return redirect('uds.web.views.service', idService=services[0]['id'], idTransport=services[0]['transports'][0]['id']) # List of services groups allGroups = [v for v in sorted([ser['group'] for ser in services], key=lambda s: s['priority'])] # Now remove duplicates groups = [] already = [] for g in allGroups: if g['name'] not in already: already.append(g['name']) groups.append(g) logger.debug('Groups: {}'.format(groups)) response = render( request, theme.template('index.html'), { 'groups': groups, 'services': services, 'ip': request.ip, 'nets': nets, 'transports': validTrans, 'autorun': autorun } ) return response
def __init__(self, userService: UserService, userServiceInstance: typing.Optional[UserDeployment] = None): self.userService = userService self.userServiceInstance = userServiceInstance if userServiceInstance is not None else userService.getInstance( )
def index(request): ''' Renders the main page. :param request: http request ''' # Session data os = request.os # We look for services for this authenticator groups. User is logged in in just 1 authenticator, so his groups must coincide with those assigned to ds groups = list(request.user.getGroups()) availServices = DeployedService.getDeployedServicesForGroups(groups) availUserServices = UserService.getUserAssignedServices(request.user) # Information for administrators nets = '' validTrans = '' logger.debug('OS: {0}'.format(os['OS'])) if request.user.isStaff(): nets = ','.join([n.name for n in Network.networksFor(request.ip)]) tt = [] for t in Transport.objects.all(): if t.validForIp(request.ip): tt.append(t.name) validTrans = ','.join(tt) # Extract required data to show to user services = [] # Select assigned user services for svr in availUserServices: trans = [] for t in svr.transports.all().order_by('priority'): typeTrans = t.getType() if t.validForIp(request.ip) and typeTrans.supportsOs(os['OS']): if typeTrans.ownLink is True: link = reverse('TransportOwnLink', args=('A' + svr.uuid, t.uuid)) else: link = html.udsAccessLink(request, 'A' + svr.uuid, t.uuid) trans.append( { 'id': t.uuid, 'name': t.name, 'link': link } ) if svr.deployed_service.image is not None: imageId = svr.deployed_service.image.uuid else: imageId = 'x' # Invalid services.append({ 'id': 'A' + svr.uuid, 'name': svr['name'], 'transports': trans, 'imageId': imageId, 'show_transports': svr.deployed_service.show_transports, 'maintenance': svr.deployed_service.service.provider.maintenance_mode, 'in_use': svr.in_use, }) logger.debug(services) # Now generic user service for svr in availServices: # Generate ticket trans = [] for t in svr.transports.all().order_by('priority'): typeTrans = t.getType() if t.validForIp(request.ip) and typeTrans.supportsOs(os['OS']): if typeTrans.ownLink is True: link = reverse('TransportOwnLink', args=('F' + svr.uuid, t.uuid)) else: link = html.udsAccessLink(request, 'F' + svr.uuid, t.uuid) trans.append( { 'id': t.uuid, 'name': t.name, 'link': link } ) if svr.image is not None: imageId = svr.image.uuid else: imageId = 'x' # Locate if user service has any already assigned user service for this ads = UserServiceManager.manager().getExistingAssignationForUser(svr, request.user) if ads is None: in_use = False else: in_use = ads.in_use services.append({ 'id': 'F' + svr.uuid, 'name': svr.name, 'transports': trans, 'imageId': imageId, 'show_transports': svr.show_transports, 'maintenance': svr.service.provider.maintenance_mode, 'in_use': in_use, }) logger.debug('Services: {0}'.format(services)) services = sorted(services, key=lambda s: s['name'].upper()) if len(services) == 1 and GlobalConfig.AUTORUN_SERVICE.get(True) == '1' and len(services[0]['transports']) > 0: if request.session.get('autorunDone', '0') == '0': request.session['autorunDone'] = '1' # TODO: Make this to redirect to uds link directly return redirect('uds.web.views.service', idService=services[0]['id'], idTransport=services[0]['transports'][0]['id']) response = render_to_response( theme.template('index.html'), { 'services': services, 'ip': request.ip, 'nets': nets, 'transports': validTrans, }, context_instance=RequestContext(request) ) return response
def serviceList(self): # We look for services for this authenticator groups. User is logged in in just 1 authenticator, so his groups must coincide with those assigned to ds groups = list(self._user.getGroups()) availServices = DeployedService.getDeployedServicesForGroups(groups) availUserServices = UserService.getUserAssignedServices(self._user) # Extract required data to show to user services = [] # Select assigned user services for svr in availUserServices: # Skip maintenance services... trans = [] for t in svr.transports.all().order_by('priority'): if t.validForIp(self._request.ip) and t.getType().providesConnetionInfo(): trans.append({'id': t.uuid, 'name': t.name}) servicePool = svr.deployed_service services.append({'id': 'A' + svr.uuid, 'name': servicePool.name, 'description': servicePool.comments, 'visual_name': servicePool.visual_name, 'group': servicePool.servicesPoolGroup if servicePool.servicesPoolGroup is not None else ServicesPoolGroup.default().as_dict, 'thumb': servicePool.image.thumb64 if servicePool.image is not None else DEFAULT_THUMB_BASE64, 'show_transports': servicePool.show_transports, 'allow_users_remove': servicePool.allow_users_remove, 'maintenance': servicePool.isInMaintenance(), 'not_accesible': not servicePool.isAccessAllowed(), 'to_be_replaced': False, # Manually assigned will not be autoremoved never 'transports': trans, 'in_use': svr.in_use}) logger.debug(services) # Now generic user service for servicePool in availServices: trans = [] for t in servicePool.transports.all().order_by('priority'): if t.validForIp(self._request.ip) and t.getType().providesConnetionInfo(): trans.append({'id': t.uuid, 'name': t.name}) # Locate if user service has any already assigned user service for this ads = userServiceManager().getExistingAssignationForUser(servicePool, self._user) if ads is None: in_use = False else: in_use = ads.in_use services.append({'id': 'F' + servicePool.uuid, 'name': servicePool.name, 'description': servicePool.comments, 'visual_name': servicePool.visual_name, 'group': servicePool.servicesPoolGroup if servicePool.servicesPoolGroup is not None else ServicesPoolGroup.default().as_dict, 'thumb': servicePool.image.thumb64 if servicePool.image is not None else DEFAULT_THUMB_BASE64, 'show_transports': servicePool.show_transports, 'allow_users_remove': servicePool.allow_users_remove, 'maintenance': servicePool.isInMaintenance(), 'not_accesible': not servicePool.isAccessAllowed(), 'to_be_replaced': servicePool.toBeReplaced(), 'transports': trans, 'in_use': in_use}) logger.debug('Services: {0}'.format(services)) services = sorted(services, key=lambda s: s['name'].upper()) return Connection.result(result=services)
def setCommsUrl(userService: UserService, ip: str, port: int, secret: str): userService.setCommsUrl('https://{}:{}/actor/{}'.format( ip, port, secret))