def save_to_USER_PROFILE(user_id, device_id, service_consumer, resource_contributor): LOG.debug( '[usermgnt.data.standalone.db] [save_to_USER_PROFILE] Saving record ...' ) # 1. there is only one record [user-profile] per device: delete all del_all_from_USER_PROFILE() # 2. add record try: record = get_from_USER_PROFILE(user_id, device_id) if record is None: id = user_id + "_" + str(uuid.uuid4()) DB_USER_PROFILE.insert(id=id, user_id=user_id, device_id=device_id, service_consumer=service_consumer, resource_contributor=resource_contributor) DB_USER_PROFILE.commit() # save changes on disk # debug DB __print_records(DB_USER_PROFILE) return "saved" else: LOG.warning( '[usermgnt.data.standalone.db] [save_to_USER_PROFILE] User-Profile already added to DB' ) return None except: LOG.exception( '[usermgnt.data.standalone.db] [save_to_USER_PROFILE] Exception') return None
def __print_records(db): LOG.debug( '[usermgnt.data.standalone.db] [__print_records] Retrieving records from db...' ) records = db() for r in records: LOG.debug("db> " + str(r))
def update_SHARING_MODEL(id, max_apps, battery_limit): LOG.debug( '[usermgnt.data.standalone.db] [update_SHARING_MODEL] Updating record ...' ) try: record = get_from_SHARING_MODEL_by_id(id) if record is not None: # 'id', 'user_id', 'device_id', 'max_apps', 'battery_limit' DB_SHARING_MODEL.update(record, max_apps=max_apps, battery_limit=battery_limit) DB_SHARING_MODEL.commit() # save changes on disk # debug DB __print_records(DB_SHARING_MODEL) return "updated" else: LOG.warning( '[usermgnt.data.standalone.db] [update_SHARING_MODEL] Sharing-Model not found' ) return None except: LOG.exception( '[usermgnt.data.standalone.db] [update_SHARING_MODEL] Exception') return None
def add_resource(resource_name, content): try: LOG.debug( "[usermgnt.data.mF2C.cimi] [add_resource] Adding new resource to [" + resource_name + "] with content [" + str(content) + "] ... ") # complete map and update resource content.update(common_new_map_fields()) #content.pop("user_id", None) res = requests.post(config.dic['CIMI_URL'] + '/' + resource_name, headers=CIMI_HEADER, verify=False, json=content) LOG.log( TRACE, "[usermgnt.data.mF2C.cimi] [add_resource] response: " + str(res) + ", " + str(res.json())) if res.status_code == 201: return get_resource_by_id(res.json()['resource-id']) LOG.error("[usermgnt.data.mF2C.cimi] [add_resource] Request failed: " + str(res.status_code) + "; Returning None ...") except: LOG.exception( "[usermgnt.data.mF2C.cimi] [add_resource] Exception; Returning None ..." ) return None
def update_resource(resource_id, content): try: LOG.log( TRACE, "[usermgnt.data.mF2C.cimi] [update_resource] (1) Updating resource [" + resource_id + "] with content [" + str(content) + "] ... ") # complete map and update resource content.update(common_update_map_fields()) LOG.debug( "[usermgnt.data.mF2C.cimi] [update_resource] (2) Updating resource [" + resource_id + "] with content [" + str(content) + "] ... ") res = requests.put(config.dic['CIMI_URL'] + '/' + resource_id, headers=CIMI_HEADER, verify=False, json=content) LOG.log( TRACE, "[usermgnt.data.mF2C.cimi] [update_resource] response: " + str(res) + ", " + str(res.json())) if res.status_code == 200: return get_resource_by_id(resource_id) LOG.error( "[usermgnt.data.mF2C.cimi] [update_resource] Request failed: " + str(res.status_code) + "; Returning None ...") except: LOG.exception( "[usermgnt.data.mF2C.cimi] [update_resource] Exception; Returning None ..." ) return None
def delete_resource_by_owner(resource, resources, owner_id): try: res = requests.get(config.dic['CIMI_URL'] + "/" + resource + "?$filter=acl/owner/principal='" + owner_id + "'", headers=CIMI_HEADER, verify=False) LOG.log( TRACE, "[usermgnt.data.mF2C.cimi] [delete_resource_by_owner] response: " + str(res)) # + ", " + str(res.json())) if res.status_code == 200 and len(res.json()[resources]) > 0: for r in res.json()[resources]: res2 = requests.delete(config.dic['CIMI_URL'] + "/" + r["id"], headers=CIMI_HEADER, verify=False) LOG.debug( "[usermgnt.data.mF2C.cimi] [delete_resource_by_owner] response: " + str(res2) + ", " + str(res2.json())) if res2.status_code == 200: LOG.debug( "[usermgnt.data.mF2C.cimi] [delete_resource_by_owner] Resource " + r["id"] + " deleted!") else: LOG.warning( "[usermgnt.data.mF2C.cimi] [delete_resource_by_owner] No " + resources + " found.") except: LOG.exception( "[usermgnt.data.mF2C.cimi] [delete_resource_by_owner] Exception.")
def save_to_SHARING_MODEL(user_id, device_id, max_apps, battery_limit): LOG.debug( '[usermgnt.data.standalone.db] [save_to_SHARING_MODEL] Saving record ...' ) # 1. there is only one record [sharing-model] per device: delete all del_all_from_SHARING_MODEL() # 2. add record try: record = get_from_SHARING_MODEL(user_id, device_id) if record is None: id = user_id + "_" + str(uuid.uuid4()) # 'id', 'user_id', 'device_id', 'max_apps', 'battery_limit' DB_SHARING_MODEL.insert(id=id, user_id=user_id, device_id=device_id, max_apps=max_apps, battery_limit=battery_limit) DB_SHARING_MODEL.commit() # save changes on disk # debug DB __print_records(DB_SHARING_MODEL) return "saved" else: LOG.warning( '[usermgnt.data.standalone.db] [save_to_SHARING_MODEL] Sharing-Model already added to DB' ) return None except: LOG.exception( '[usermgnt.data.standalone.db] [save_to_SHARING_MODEL] Exception') return None
def register_user(data): LOG.debug( "[usermgnt.data.standalone.data] [register_user] Creating new Profile for user [data=" + str(data) + "] ...") return db.save_to_USER_PROFILE(config.dic['DEVICE_USER'], config.dic['HOST_IP'], data['service_consumer'], data['resource_contributor'])
def get_agent_info(): LOG.log( TRACE, "[usermgnt.data.mF2C.data] [get_agent_info] Getting 'agent' resource ..." ) # get from AGENT resource agent = cimi.get_agent_info() LOG.debug("[usermgnt.data.mF2C.data] [get_agent_info] agent = " + str(agent)) if not agent is None and agent != -1: return agent else: return -1
def get_user(user_id): LOG.debug("[usermgnt.modules.um_user] [get_user] user_id=" + str(user_id)) user = data_adapter.get_user_info(user_id) if user is None: return common.gen_response(500, 'Error or User not found', 'user_id', user_id, 'user', {}) elif user == -1: return common.gen_response( 403, "Warning: User " + user_id + " has no permissions on this device", 'user_id', user_id, 'user', {}) else: return common.gen_response_ok('User found', 'user_id', user_id, 'user', user)
def get_user_profile_by_id(profile_id): LOG.debug( "[usermgnt.modules.um_profiling] [get_user_profile_by_id] profile_id=" + profile_id) user_profile = data_adapter.get_user_profile_by_id(profile_id) if user_profile is None: return common.gen_response(500, 'Error', 'profile_id', profile_id, 'profile', {}) elif user_profile == -1: return common.gen_response_ko('Warning: User profile not found', 'profile_id', profile_id, 'profile', {}) else: return common.gen_response_ok('User found', 'profile_id', profile_id, 'profile', user_profile)
def get_current_device_id(): LOG.info( "[usermgnt.data.standalone.data] [get_current_device_id] Getting 'my' device ID ..." ) # get from local volume device_id = vol.read_device_id() if device_id is not None and not device_id == "" and len(device_id) > 0: LOG.debug( "[usermgnt.data.standalone.data] [get_current_device_id] (LOCAL VOLUME) device_id = " + device_id) return device_id # get from config.dic['HOST_IP'] else: return config.dic['HOST_IP']
def update_user_profile_by_id(profile_id, data): LOG.debug( "[usermgnt.modules.um_profiling] [update_user_profile_by_id] profile_id=" + profile_id + ", data=" + str(data)) # update user user_profile = data_adapter.update_user_profile_by_id(profile_id, data) if user_profile is None: return common.gen_response(500, 'Error', 'profile_id', profile_id, 'profile', {}) elif user_profile == -1: return common.gen_response_ko('Warning: User profile not found', 'profile_id', profile_id, 'profile', {}) else: return common.gen_response_ok('User updated', 'profile_id', profile_id, 'profile', user_profile)
def get_status(): global execute global d LOG.debug( "[usermgnt.modules.assessment] [get_status] << Assessment Process >> Getting assessment process status [execute=" + str(execute) + "]") if d is None: return "Not initialized" elif execute and d.isAlive() == True: return "Running" elif execute: return "???" else: return "Stopped"
def get_current_SHARING_MODEL(): try: records = DB_SHARING_MODEL() LOG.debug( "[usermgnt.data.standalone.db] [get_current_SHARING_MODEL] records: " + str(records)) if len(records) >= 1: return list(records)[0] else: LOG.warning( '[usermgnt.data.standalone.db] [get_current_SHARING_MODEL] No records found' ) except: LOG.exception( '[usermgnt.data.standalone.db] [get_current_SHARING_MODEL] Exception' ) return None
def del_from_SHARING_MODEL(user_id, device_id): try: record = get_from_SHARING_MODEL(user_id, device_id) if record is not None: LOG.debug( "[usermgnt.data.standalone.db] [del_from_SHARING_MODEL] deleted records: " + str(DB_SHARING_MODEL.delete(record))) DB_SHARING_MODEL.commit() # save changes on disk return "deleted" else: LOG.warning( '[usermgnt.data.standalone.db] [del_from_SHARING_MODEL] Sharing-Model not found' ) return None except: LOG.exception( '[usermgnt.data.standalone.db] [del_from_SHARING_MODEL] Exception') return None
def del_from_USER_PROFILE(user_id, device_id): try: record = get_from_USER_PROFILE(user_id, device_id) if record is not None: LOG.debug( "[usermgnt.data.standalone.db] [del_from_USER_PROFILE] deleted records: " + str(DB_USER_PROFILE.delete(record))) DB_USER_PROFILE.commit() # save changes on disk return "deleted" else: LOG.warning( '[usermgnt.data.standalone.db] [del_from_USER_PROFILE] User-Profile not found' ) return None except: LOG.exception( '[usermgnt.data.standalone.db] [del_from_USER_PROFILE] Exception') return None
def get_from_SHARING_MODEL_by_id(id): try: # print_records(DB_DOCKER_PORTS) # debug DB records = [r for r in DB_SHARING_MODEL if r['id'] == id] LOG.debug( "[usermgnt.data.standalone.db] [get_from_SHARING_MODEL_by_id] records: " + str(records)) if len(records) >= 1: return list(records)[0] else: LOG.warning( '[usermgnt.data.standalone.db] [get_from_SHARING_MODEL_by_id] No records found' ) except: LOG.exception( '[usermgnt.data.standalone.db] [get_from_SHARING_MODEL_by_id] Exception' ) return None
def get_from_USER_PROFILE_by_device_id(device_id): try: # print_records(DB_DOCKER_PORTS) # debug DB records = [r for r in DB_USER_PROFILE if r['device_id'] == device_id] LOG.debug( "[usermgnt.data.standalone.db] [get_from_USER_PROFILE_by_device_id] records: " + str(records)) if len(records) >= 1: return list(records)[0] else: LOG.warning( '[usermgnt.data.standalone.db] [get_from_USER_PROFILE_by_device_id] No records found' ) except: LOG.exception( '[usermgnt.data.standalone.db] [get_from_USER_PROFILE_by_device_id] Exception' ) return None
def stop(): global execute global d LOG.debug( "[usermgnt.modules.assessment] [stop] << Assessment Process >> Stopping assessment process [execute=" + str(execute) + "]") if d is None: LOG.warning( '[usermgnt.modules.assessment] [stop] << Assessment Process >> [execute: ' + str(execute) + '; d.isAlive(): None]') return "???" else: LOG.debug( '[usermgnt.modules.assessment] [stop] << Assessment Process >> [d.join()]' ) execute = False d.join() d = None return "Stopped"
def get_from_SHARING_MODEL(user_id, device_id): try: # print_records(DB_SHARING_MODEL) # debug DB records = [ r for r in DB_SHARING_MODEL if r['user_id'] == user_id and r['device_id'] == device_id ] LOG.debug( "[usermgnt.data.standalone.db] [get_from_SHARING_MODEL] records: " + str(records)) if len(records) >= 1: return list(records)[0] else: LOG.warning( '[usermgnt.data.standalone.db] [get_from_SHARING_MODEL] No records found' ) except: LOG.exception( '[usermgnt.data.standalone.db] [get_from_SHARING_MODEL] Exception') return None
def delete_user(data): if 'user_id' not in data: LOG.warning( '[usermgnt.modules.um_user] [delete_user] parameter not found: user_id' ) return common.gen_response(405, 'parameter not found: user_id', 'data', str(data)) user_id = data['user_id'] LOG.debug("[usermgnt.modules.um_user] [delete_user] user_id=" + str(user_id)) user = data_adapter.delete_user(user_id) if user is None: return common.gen_response(500, 'Error or User not found', 'user_id', user_id, 'user', {}) elif user == -1: return common.gen_response( 403, "Warning: User " + user_id + " has no permissions on this device", 'user_id', user_id, 'user', {}) else: return common.gen_response_ok('User deleted', 'user_id', user_id)
def start(): global execute global d LOG.debug( "[usermgnt.modules.assessment] [start] << Assessment Process >> Starting assessment process [execute=" + str(execute) + "]") if d is None: LOG.debug( "[usermgnt.modules.assessment] [start] << Assessment Process >> [d is None]" ) d = threading.Thread(target=__daemon) #(name='daemon', target=daemon) d.setDaemon(True) execute = True d.start() return "started" else: LOG.warning( "[usermgnt.modules.assessment] [start] << Assessment Process >> [execute: " + str(execute) + "; d.isAlive(): " + str(d.isAlive()) + "]") return "???"
def update_USER_PROFILE(id, service_consumer, resource_contributor): LOG.debug( '[usermgnt.data.standalone.db] [update_USER_PROFILE] Updating record ...' ) try: record = get_from_USER_PROFILE_by_id(id) if record is not None: DB_USER_PROFILE.update(record, service_consumer=service_consumer, resource_contributor=resource_contributor) DB_USER_PROFILE.commit() # save changes on disk # debug DB __print_records(DB_USER_PROFILE) return "updated" else: LOG.warning( '[usermgnt.data.standalone.db] [update_USER_PROFILE] User-Profile not found' ) return None except: LOG.exception( '[usermgnt.data.standalone.db] [update_USER_PROFILE] Exception') return None
def __daemon(): global execute try: while execute: LOG.debug( '[usermgnt.modules.assessment] [__daemon] << Assessment Process Thread >> executing ...' ) device_id = None user_id = None # 1. get current profile user_profile = data_adapter.get_current_user_profile() if user_profile is None: LOG.error( '[usermgnt.modules.assessment] [__daemon] << Assessment Process Thread >> user_profile not found / error' ) elif user_profile == -1: LOG.warning( '[usermgnt.modules.assessment] [__daemon] << Assessment Process Thread >> user_profile not found' ) else: user_id = user_profile['user_id'] device_id = user_profile['device_id'] LOG.log( TRACE, '[usermgnt.modules.assessment] [__daemon] << Assessment Process Thread >> user_profile found' ) # 2. get current sharing model sharing_model = data_adapter.get_current_sharing_model() if sharing_model is None: LOG.error( '[usermgnt.modules.assessment] [__daemon] << Assessment Process Thread >> sharing_model not found / error' ) elif sharing_model == -1: LOG.warning( '[usermgnt.modules.assessment] [__daemon] << Assessment Process Thread >> sharing_model not found' ) else: user_id = sharing_model['user_id'] device_id = sharing_model['device_id'] LOG.log( TRACE, '[usermgnt.modules.assessment] [__daemon] << Assessment Process Thread >> sharing_model found' ) if not user_id is None and not device_id is None: LOG.log( TRACE, '[usermgnt.modules.assessment] [__daemon] << Assessment Process Thread >> checking values ...' ) # 3. Get information: # - battery battery_level = data_adapter.get_power() # battery_level = 50 # TODO # - total services running total_services = data_adapter.get_total_services_running() # 4. check information and send warning to Lifecycle if needed result = __check_resources_used(user_profile, sharing_model, battery_level, total_services) if not result: LOG.debug( "[usermgnt.modules.assessment] [__daemon] << Assessment Process Thread >> no violations: result: " + str(result)) else: LOG.debug( "[usermgnt.modules.assessment] [__daemon] << Assessment Process Thread >> violations found: result: " + str(result)) LOG.log( TRACE, '[usermgnt.modules.assessment] [__daemon] << Assessment Process Thread >> generating warning / sending notification ...' ) mf2c.send_warning(user_id, device_id, user_profile, sharing_model, result) else: LOG.warning( '[usermgnt.modules.assessment] [__daemon] << Assessment Process Thread >> cannot check values' ) # wait 300 seconds LOG.debug( '[usermgnt.modules.assessment] [__daemon] << Assessment Process Thread >> Waiting 5m (300s) for next execution ...' ) time.sleep(300) except: LOG.exception( '[usermgnt.modules.assessment] [__daemon] << Assessment Process Thread >> Exception' )
def get_current_user_profile(): LOG.debug( "[usermgnt.data.standalone.data] [get_current_user_profile] Getting information about current user and device ..." ) return db.get_current_USER_PROFILE()
def get_total_services_running(): LOG.debug( "[usermgnt.data.standalone.data] [get_total_services_running] Total of services running in device = " + str(config.APPS_RUNNING)) return config.APPS_RUNNING
def get_sharing_model_by_id(sharing_model_id): LOG.debug("[usermgnt.data.standalone.data] [get_sharing_model_by_id] " + sharing_model_id) return db.get_from_SHARING_MODEL_by_id(sharing_model_id)
def init(): try: # get CIMI from environment values: LOG.info('[usermgnt.init_config] [init] Reading values from ENVIRONMENT...') # UM_MODE common.set_value_env('UM_MODE') common.set_value_env('HOST_IP') common.set_value_env('DEVICE_USER') common.set_value_env('UM_WORKING_DIR_VOLUME') # UM_WORKING_DIR_VOLUME from environment values: common.set_value_env('CIMI_URL') LOG.info('[usermgnt.init_config] [init] Reading User-Profile and Sharing-Model values from ENVIRONMENT...') common.set_value_env_bool('SERVICE_CONSUMER', config.dic['SERVICE_CONSUMER']) common.set_value_env_bool('RESOURCE_CONTRIBUTOR', config.dic['RESOURCE_CONTRIBUTOR']) common.set_value_env_int('MAX_APPS', config.dic['MAX_APPS']) common.set_value_env_int('BATTERY_LIMIT', config.dic['BATTERY_LIMIT']) common.set_value_env_bool('GPS_ALLOWED', config.dic['GPS_ALLOWED']) common.set_value_env_int('MAX_CPU_USAGE', config.dic['MAX_CPU_USAGE']) common.set_value_env_int('MAX_MEM_USAGE', config.dic['MAX_MEM_USAGE']) common.set_value_env_int('MAX_STO_USAGE', config.dic['MAX_STO_USAGE']) common.set_value_env_int('MAX_BANDWITH_USAGE', config.dic['MAX_BANDWITH_USAGE']) LOG.info('[usermgnt.init_config] [init] Checking configuration...') LOG.info('[usermgnt.init_config] [init] [UM_MODE=' + config.dic['UM_MODE'] + ']') # CIMI URL if "/api" not in config.dic['CIMI_URL'] and not config.dic['CIMI_URL'].endswith("/api"): LOG.debug("[usermgnt.init_config] [init] Adding '/api' to CIMI_URL ...") if config.dic['CIMI_URL'].endswith("/"): config.dic['CIMI_URL'] = config.dic['CIMI_URL'] + "api" else: config.dic['CIMI_URL'] = config.dic['CIMI_URL'] + "/api" LOG.debug('[usermgnt.init_config] [init] [CIMI_URL=' + config.dic['CIMI_URL'] + ']') else: LOG.debug("[usermgnt.init_config] [init] CIMI_URL ... " + config.dic['CIMI_URL']) LOG.info('[usermgnt.init_config] [init] [CIMI_URL=' + config.dic['CIMI_URL'] + ']') LOG.info('[usermgnt.init_config] [init] [DEVICE_USER='******'DEVICE_USER'] + ']') LOG.info('[usermgnt.init_config] [init] [UM_WORKING_DIR_VOLUME=' + config.dic['UM_WORKING_DIR_VOLUME'] + ']') LOG.info('[usermgnt.init_config] [init] [DB_SHARING_MODEL=' + config.dic['DB_SHARING_MODEL'] + ']') LOG.info('[usermgnt.init_config] [init] [DB_USER_PROFILE=' + config.dic['DB_USER_PROFILE'] + ']') LOG.info('[usermgnt.init_config] [init] [SERVER_PORT=' + str(config.dic['SERVER_PORT']) + ']') LOG.info('[usermgnt.init_config] [init] [API_DOC_URL=' + config.dic['API_DOC_URL'] + ']') LOG.info('[usermgnt.init_config] [init] [HOST_IP=' + config.dic['HOST_IP'] + ']') LOG.info('[usermgnt.init_config] [init] User-Profile and Sharing-Model configuration...') LOG.info('[usermgnt.init_config] [init] [SERVICE_CONSUMER=' + str(config.dic['SERVICE_CONSUMER']) + ']') LOG.info('[usermgnt.init_config] [init] [RESOURCE_CONTRIBUTOR=' + str(config.dic['RESOURCE_CONTRIBUTOR']) + ']') LOG.info('[usermgnt.init_config] [init] [MAX_APPS=' + str(config.dic['MAX_APPS']) + ']') LOG.info('[usermgnt.init_config] [init] [BATTERY_LIMIT=' + str(config.dic['BATTERY_LIMIT']) + ']') LOG.info('[usermgnt.init_config] [init] [GPS_ALLOWED=' + str(config.dic['GPS_ALLOWED']) + ']') LOG.info('[usermgnt.init_config] [init] [MAX_CPU_USAGE=' + str(config.dic['MAX_CPU_USAGE']) + ']') LOG.info('[usermgnt.init_config] [init] [MAX_MEM_USAGE=' + str(config.dic['MAX_MEM_USAGE']) + ']') LOG.info('[usermgnt.init_config] [init] [MAX_STO_USAGE=' + str(config.dic['MAX_STO_USAGE']) + ']') LOG.info('[usermgnt.init_config] [init] [MAX_BANDWITH_USAGE=' + str(config.dic['MAX_BANDWITH_USAGE']) + ']') LOG.info('[usermgnt.init_config] [init] Checking volume files ...') if os.path.exists(config.dic['UM_WORKING_DIR_VOLUME'] + "device_id.txt"): os.remove(config.dic['UM_WORKING_DIR_VOLUME'] + "device_id.txt") LOG.info("[usermgnt.init_config] [init] File deleted: " + config.dic['UM_WORKING_DIR_VOLUME'] + "device_id.txt") else: LOG.info("[usermgnt.init_config] [init] The file does not exist: " + config.dic['UM_WORKING_DIR_VOLUME'] + "device_id.txt. Creating new path ...") os.makedirs(config.dic['UM_WORKING_DIR_VOLUME'], exist_ok = True) if os.path.exists(config.dic['UM_WORKING_DIR_VOLUME'] + "user_id.txt"): os.remove(config.dic['UM_WORKING_DIR_VOLUME'] + "user_id.txt") LOG.info("[usermgnt.init_config] [init] File deleted: " + config.dic['UM_WORKING_DIR_VOLUME'] + "user_id.txt") else: LOG.info("[usermgnt.init_config] [init] The file does not exist: " + config.dic['UM_WORKING_DIR_VOLUME'] + "user_id.txt. Creating new path ...") os.makedirs(config.dic['UM_WORKING_DIR_VOLUME'], exist_ok = True) data_adapter.init(config.dic['UM_MODE']) except: LOG.exception('[usermgnt.init_config] [init] Exception: Error while initializing application')
def get_current_sharing_model(): LOG.debug( "[usermgnt.data.standalone.data] [get_current_sharing_model] Getting information about current user and device ..." ) return db.get_current_SHARING_MODEL()