def __up_policies(): global message try: LOG.log( TRACE, "[usermgnt.modules.policies] [__up_policies] Checking policies ..." ) # get current profile user_profile = data_adapter.get_current_user_profile() if user_profile is None: LOG.error( '[usermgnt.modules.policies] [__up_policies] user_profile not found / error' ) elif user_profile == -1: LOG.warning( '[usermgnt.modules.policies] [__up_policies] user_profile not found' ) else: LOG.log( TRACE, '[usermgnt.modules.policies] [__up_policies] user_profile found. checking values ...' ) if user_profile['resource_contributor']: message = message + "ALLOWED: resource_contributor is set to TRUE; " return True message = message + "NOT ALLOWED: resource_contributor is set to FALSE; " except: LOG.exception('[usermgnt.modules.policies] [__up_policies] Exception') return False
def gen_response_ko(message, key, value, key2=None, value2=None): dict = {'error': True, 'message': message} dict[key] = value if not (key2 is None) and not (value2 is None): dict[key2] = value2 LOG.log(TRACE, "Generate response KO; dict=" + str(dict)) return dict
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 get_user_info(user_id): user_id = user_id.replace('user/', '') LOG.log( TRACE, "[usermgnt.data.mF2C.data] [get_user_info] Getting info from user " + user_id + " ...") return cimi.get_resource_by_id("user/" + user_id)
def __thr_create_user_profile(data): time.sleep(70) try: LOG.info("[usermgnt.init_config] [__thr_create_user_profile] << User Profile Creation Thread >> Creating USER-PROFILE [" + str(data) + "] in current device ...") created = False while not created: LOG.log(TRACE, '[usermgnt.init_config] [__thr_create_user_profile] << User Profile Creation Thread >> executing ...') # get device_id device_id = data_adapter.get_current_device_id() if device_id == -1: LOG.log(TRACE, '[usermgnt.init_config] [__thr_create_user_profile] << User Profile Creation Thread >> trying again in 45s ...') time.sleep(45) else: # create user-profile data['device_id'] = device_id up = um_profiling.create_user_profile(data) if up is not None: LOG.info('[usermgnt.init_config] [__thr_create_user_profile] << User Profile Creation Thread >> user-profile created! ...') created = True else: LOG.error('[usermgnt.init_config] [__thr_create_user_profile] << User Profile Creation Thread >> user-profile not created! Trying again in 60s ...') time.sleep(30) LOG.info('[usermgnt.init_config] [__thr_create_user_profile] << User Profile Creation Thread >> thread finishes') except: LOG.exception('[usermgnt.init_config] [__thr_create_user_profile] << User Profile Creation Thread >> Exception: Error while initializing application')
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 get_user_profile(device_id): try: device_id = device_id.replace('device/', '') res = requests.get(config.dic['CIMI_URL'] + "/user-profile?$filter=device_id=\"device/" + device_id + "\"", headers=CIMI_HEADER, verify=False) LOG.log( TRACE, "[usermgnt.data.mF2C.cimi] [get_user_profile] response: " + str(res) + ", " + str(res.json())) if res.status_code == 200 and len(res.json()['userProfiles']) > 0: return res.json()['userProfiles'][0] else: LOG.warning( "[usermgnt.data.mF2C.cimi] [get_user_profile] User's profile not found [device_id=" + device_id + "]; Returning -1 ...") return -1 except: LOG.exception( "[usermgnt.data.mF2C.cimi] [get_user_profile] Exception; Returning None ..." ) return None
def get_agent_info(): try: res = requests.get(config.dic['CIMI_URL'] + "/agent", headers=CIMI_HEADER, verify=False) LOG.log( TRACE, "[usermgnt.data.mF2C.cimi] [get_agent_info] response: " + str(res) + ", " + str(res.json())) if res.status_code == 200 and res.json()['count'] == 0: LOG.warning( "[usermgnt.data.mF2C.cimi] [get_agent_info] 'agent' not found") return -1 elif res.status_code == 200: return res.json()['agents'][0] LOG.warning( "[usermgnt.data.mF2C.cimi] [get_agent_info] 'agent' not found; Returning -1 ..." ) return -1 except: LOG.error( "[usermgnt.data.mF2C.cimi] [get_agent_info] Exception; Returning None ..." ) 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 get_power(): device_id = get_current_device_id() # get 'my' device_id LOG.log( TRACE, "[usermgnt.data.mF2C.data] [get_power] Getting power status from device [" + device_id + "] ...") return cimi.get_power(device_id)
def __thr_create_sharing_model(data): time.sleep(65) try: LOG.info("[usermgnt.init_config] [__thr_create_sharing_model] << Sharing Model Creation Thread >> Creating SHARING-MODEL [" + str(data) + "] in current device ...") created = False while not created: LOG.log(TRACE, '[usermgnt.init_config] [__thr_create_sharing_model] << Sharing Model Creation Thread >> executing ...') # get device_id device_id = data_adapter.get_current_device_id() if device_id == -1: LOG.log(TRACE, '[usermgnt.init_config] [__thr_create_sharing_model] << Sharing Model Creation Thread >> trying again in 45s ...') time.sleep(45) else: # create sharing-model data['device_id'] = device_id up = um_sharing_model.init_sharing_model(data) if up is not None: LOG.info('[usermgnt.init_config] [__thr_create_sharing_model] << Sharing Model Creation Thread >> sharing-model created! ...') created = True else: LOG.error('[usermgnt.init_config] [__thr_create_sharing_model] << Sharing Model Creation Thread >> sharing-model not created! Trying again in 60s ...') time.sleep(30) LOG.info('[usermgnt.init_config] [__thr_create_sharing_model] << Sharing Model Creation Thread >> thread finishes') except: LOG.exception('[usermgnt.init_config] [__thr_create_sharing_model] << Sharing Model Creation Thread >> Exception: Error while initializing application')
def get_power(device_id): try: device_id = device_id.replace('device/', '') res = requests.get(config.dic['CIMI_URL'] + "/device-dynamic?$filter=device/href='device/" + device_id + "'", headers=CIMI_HEADER, verify=False) LOG.log( TRACE, "[usermgnt.data.mF2C.cimi] [get_power] response: " + str(res) + ", " + str(res.json())) if res.status_code == 200 and res.json()['count'] > 0: power_value = res.json( )['deviceDynamics'][0]['powerRemainingStatus'] if str(power_value).lower() == "unlimited": return 100 elif __is_number(power_value): return int(float(power_value)) else: return int(power_value) else: LOG.warning( "[usermgnt.data.mF2C.cimi] [get_power] 'device-dynamic' not found [device_id=" + device_id + "]; Returning -1 ...") return -1 except: LOG.exception( "[usermgnt.data.mF2C.cimi] [get_power] Exception; Returning 100 ..." ) return 100
def read_user_id(): LOG.log(TRACE, "[usermgnt.data.app.volume] [read_user_id] Reading user_id value from local VOLUME [" + config.dic['UM_WORKING_DIR_VOLUME'] + "] ...") try: with open(config.dic['UM_WORKING_DIR_VOLUME'] + "user_id.txt", "r") as file: return file.readline() except: LOG.error("[usermgnt.data.app.volume] [read_user_id] UM could not save 'user_id' value in " + config.dic['UM_WORKING_DIR_VOLUME'] + "user_id.txt. Returning None ...") return None
def save_user_id(user_id): try: LOG.log(TRACE, "[usermgnt.app.volume] [save_user_id] Storing user_id [" + user_id + "] value in local VOLUME [" + config.dic['UM_WORKING_DIR_VOLUME'] + "] ...") with open(config.dic['UM_WORKING_DIR_VOLUME'] + "user_id.txt", "w") as file: file.write(user_id) except: LOG.error("[usermgnt.data.app.volume] [save_user_id] UM could not save 'user_id' value in " + config.dic['UM_WORKING_DIR_VOLUME'] + "user_id.txt. Returning None ...") return None
def gen_response(status, message, key, value, key2=None, value2=None): dict = {'error': True, 'message': message} dict[key] = value if not (key2 is None) and not (value2 is None): dict[key2] = value2 LOG.log(TRACE, 'Generate response ' + str(status) + "; dict=" + str(dict)) return Response(json.dumps(dict), status=status, content_type='application/json')
def update_sharing_model_by_id(sharing_model_id, data): sharing_model_id = sharing_model_id.replace('sharing-model/', '') LOG.log( TRACE, "[usermgnt.data.mF2C.data] [update_sharing_model_by_id] " + sharing_model_id + ", " + str(data)) resp = cimi.get_resource_by_id("sharing-model/" + sharing_model_id) if resp and resp == -1: return -1 elif resp: resp = cimi.update_resource(resp['id'], data) return resp return None
def delete_sharing_model_by_id(sharing_model_id): sharing_model_id = sharing_model_id.replace('sharing-model/', '') LOG.log( TRACE, "[usermgnt.data.mF2C.data] [delete_sharing_model_by_id] " + sharing_model_id) resp = cimi.get_resource_by_id("sharing-model/" + sharing_model_id) if resp and resp == -1: return -1 elif resp: resp = cimi.delete_resource(resp['id']) return resp return None
def delete_user_profile_by_id(profile_id): profile_id = profile_id.replace('user-profile/', '') LOG.log( TRACE, "[usermgnt.data.mF2C.data] [delete_user_profile_by_id] Delete Profile [" + profile_id + "]") resp = cimi.get_resource_by_id("user-profile/" + profile_id) if resp and resp == -1: return None elif resp: resp = cimi.delete_resource(resp['id']) return resp return None
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 gen_response_ok(message, key, value, key2=None, value2=None, key3=None, value3=None): dict = {'error': False, 'message': message} dict[key] = value if not (key2 is None) and not (value2 is None): dict[key2] = value2 if not (key3 is None) and not (value3 is None): dict[key3] = value3 LOG.log(TRACE, "Generate response OK; dict=" + str(dict)) return dict
def update_user_profile_by_id(profile_id, data): profile_id = profile_id.replace('user-profile/', '') LOG.log( TRACE, "[usermgnt.data.mF2C.data] [update_user_profile_by_id] " + profile_id + ", " + str(data)) resp = cimi.get_resource_by_id("user-profile/" + profile_id) if resp and resp == -1: return -1 elif resp: #resp['service_consumer'] = data['service_consumer'] #resp['resource_contributor'] = data['resource_contributor'] #now = datetime.datetime.now() #resp['updated'] = now.strftime('%Y-%m-%dT%H:%M:%S.%fZ') #resp = cimi.update_resource(resp['id'], resp) resp = cimi.update_resource(resp['id'], data) return resp return None
def create_user_profile(): if config.dic['UM_MODE'] == "MF2C": try: LOG.log(TRACE, '[usermgnt.init_config] [create_user_profile] Creating USER-PROFILE [MF2C] in current device ...') data = { "service_consumer": config.dic['SERVICE_CONSUMER'], "resource_contributor": config.dic['RESOURCE_CONTRIBUTOR'], "device_id": "" } d = threading.Thread(target=__thr_create_user_profile, args=(data,)) d.setDaemon(True) d.start() except: LOG.exception('[usermgnt.init_config] [create_user_profile] Exception: Error while initializing application') else: LOG.info('[usermgnt.init_config] [create_user_profile] Creating USER-PROFILE [STANDALONE] in current device ...') db.save_to_SHARING_MODEL(config.dic['DEVICE_USER'], "localhost", 5, 50)
def delete_resource(resource_id): try: res = requests.delete(config.dic['CIMI_URL'] + '/' + resource_id, headers=CIMI_HEADER, verify=False) LOG.log( TRACE, "[usermgnt.data.mF2C.cimi] [delete_resource] response: " + str(res) + ", " + str(res.json())) if res.status_code == 200: return res.json() except: LOG.exception( "[usermgnt.data.mF2C.cimi] [delete_resource] Exception; Returning None ..." ) LOG.warning( "[usermgnt.data.mF2C.cimi] [delete_resource] Returning None ...") return None
def get_current_user_profile(): LOG.log( TRACE, "[usermgnt.data.mF2C.data] [get_current_user_profile] Getting information about current user and device ..." ) device_id = get_current_device_id( ) # get 'my' device_id from 'agent' resource LOG.log( TRACE, "[usermgnt.data.mF2C.data] [get_current_user_profile] device_id=" + str(device_id)) if device_id == -1: LOG.warning( "[usermgnt.data.mF2C.data] [get_current_user_profile] No device found; Returning None ..." ) return None else: return cimi.get_user_profile(device_id)
def get_resource_by_id(resource_id): try: res = requests.get(config.dic['CIMI_URL'] + "/" + resource_id, headers=CIMI_HEADER, verify=False) LOG.log( TRACE, "[usermgnt.data.mF2C.cimi] [get_resource_by_id] response: " + str(res) + ", " + str(res.json())) if res.status_code == 200 and 'id' in res.json(): return res.json() LOG.error( "[usermgnt.data.mF2C.cimi] [get_resource_by_id] Request failed: " + res.status_code + "; Returning None ...") except: LOG.exception( "[usermgnt.data.mF2C.cimi] [get_resource_by_id] Exception; Returning None ..." ) return None
def __sm_policies(): global message try: LOG.log( TRACE, "[usermgnt.modules.policies] [__sm_policies] Checking policies ..." ) # get current sharing model sharing_model = data_adapter.get_current_sharing_model() if sharing_model is None: LOG.error( '[usermgnt.modules.policies] [__sm_policies] sharing_model not found / error' ) elif sharing_model == -1: LOG.warning( '[usermgnt.modules.policies] [__sm_policies] sharing_model not found' ) else: LOG.log( TRACE, '[usermgnt.modules.policies] [__sm_policies] sharing_model found. checking values ...' ) # 1. battery_level battery_level = data_adapter.get_power() LOG.log( TRACE, "[usermgnt.modules.policies] [__sm_policies] 1. [battery_level=" + str(battery_level) + "] ... [sharing_model('battery_limit')=" + str(sharing_model['battery_limit']) + "]") if battery_level is None or battery_level == -1 or battery_level > sharing_model[ 'battery_limit']: # 2. total services running apps_running = data_adapter.get_total_services_running() LOG.log( TRACE, "[usermgnt.modules.policies] [__sm_policies] 2. [apps_running=" + str(apps_running) + "] ... [sharing_model('max_apps')=" + str(sharing_model['max_apps']) + "]") if apps_running >= sharing_model['max_apps']: message = message + "NOT ALLOWED: apps_running >= max_apps; " return False return True else: message = message + "NOT ALLOWED: battery_level < battery_limit; " return False except: LOG.exception('[usermgnt.modules.policies] [__sm_policies] Exception') return False
def create_sharing_model(): if config.dic['UM_MODE'] == "MF2C": try: LOG.log(TRACE, '[usermgnt.init_config] [create_sharing_model] Creating SHARING-MODEL in current device ...') data = { "gps_allowed": config.dic['GPS_ALLOWED'], "max_cpu_usage": config.dic['MAX_CPU_USAGE'], "max_memory_usage": config.dic['MAX_MEM_USAGE'], "max_storage_usage": config.dic['MAX_STO_USAGE'], "max_bandwidth_usage": config.dic['MAX_BANDWITH_USAGE'], "battery_limit": config.dic['BATTERY_LIMIT'], "max_apps": config.dic['MAX_APPS'], "device_id": "" } d = threading.Thread(target=__thr_create_sharing_model, args=(data,)) d.setDaemon(True) d.start() except: LOG.exception('[usermgnt.init_config] [create_sharing_model] Exception: Error while initializing application') else: LOG.info('[usermgnt.init_config] [create_sharing_model] Creating USER-PROFILE [STANDALONE] in current device ...') db.save_to_USER_PROFILE(config.dic['DEVICE_USER'], "localhost", True, True)
def get_id_from_device(deviceID): try: res = requests.get(config.dic['CIMI_URL'] + "/device?$filter=deviceID=\"" + deviceID + "\"", headers=CIMI_HEADER, verify=False) LOG.log(TRACE, "[usermgnt.data.mF2C.cimi] [get_id_from_device] response: " + str(res)) # + ", " + str(res.json())) if res.status_code == 200 and len(res.json()['devices']) > 0: return res.json()['devices'][0]['id'] else: LOG.warning( "[usermgnt.data.mF2C.cimi] [get_id_from_device] No device found; Returning -1 ..." ) return -1 except: LOG.exception( "[usermgnt.data.mF2C.cimi] [get_id_from_device] Exception; Returning None ..." ) return None
def __check_resources_used(user_profile, sharing_model, battery_level, total_services): try: LOG.log( TRACE, "[usermgnt.modules.assessment] [__check_resources_used] << Assessment Process >> [battery_level=" + str(battery_level) + "], " "[total_services=" + str(total_services) + "]") result = {} if battery_level <= sharing_model['battery_limit']: result['battery_limit_violation'] = True if not user_profile['resource_contributor'] and total_services > 0: result['resource_contributor_violation'] = True if total_services > sharing_model['max_apps']: result['max_apps_violation'] = True except: LOG.exception( '[usermgnt.modules.assessment] [__check_resources_used] << Assessment Process >> check_resources_used >> Exception' ) return result # TODO check if empty
def get_current_device_id(): LOG.log( TRACE, "[usermgnt.data.mF2C.data] [get_current_device_id] Getting 'my' device ID from 'agent' resource ..." ) # 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.log( TRACE, "[usermgnt.data.mF2C.data] [get_current_device_id] (LOCAL VOLUME) device_id = " + device_id) return device_id # get from AGENT resource else: agent = cimi.get_agent_info() LOG.log( TRACE, "[usermgnt.data.mF2C.data] [get_current_device_id] agent=" + str(agent)) if not agent is None and agent != -1: LOG.log( TRACE, "[usermgnt.data.mF2C.data] [get_current_device_id] Getting device 'id' by 'deviceID'=" + agent['device_id']) id = cimi.get_id_from_device(agent['device_id']) if not id is None and id != -1: LOG.info( "[usermgnt.data.mF2C.data] [get_current_device_id] Returning 'my' device ID = " + id) return id else: LOG.warning( "[usermgnt.data.mF2C.data] [get_current_device_id] Device information not found. Returning -1 ..." ) return -1 else: LOG.warning( "[usermgnt.data.mF2C.data] [get_current_device_id] Agent information not found. Returning -1 ..." ) return -1