def patch(cls, **kwargs): data = cls.parser_patch.parse_args() point: BACnetPointModel = copy.deepcopy(cls.get_point(**kwargs)) if point is None: raise NotFoundException(f"Does not exist with {kwargs}") use_next_available_address: bool = data.get( 'use_next_available_address') address: str = data.get('address') if use_next_available_address is not None or address is not None: if use_next_available_address is None: use_next_available_address = point.use_next_available_address if use_next_available_address and address: raise BadDataException( "address needs to be null when use_next_available_address is true" ) elif not use_next_available_address and not address: raise BadDataException( "address cannot be null when use_next_available_address is false" ) priority_array_write = data.pop('priority_array_write') non_none_data = {} for key in data.keys(): if data[key] is not None: non_none_data[key] = data[key] if priority_array_write: PriorityArrayModel.filter_by_point_uuid( point.uuid).update(priority_array_write) BACnetPointModel.filter_by_uuid(point.uuid).update(non_none_data) BACServer().remove_point(point) point_return = BACnetPointModel.find_by_uuid(point.uuid) BACServer().add_point(point_return) return point_return
def add_point(cls, data, uuid): priority_array_write: dict = data.pop('priority_array_write') or {} point = BACnetPointModel(uuid=uuid, **data) if point.use_next_available_address and point.address: raise BadDataException( "address needs to be null when use_next_available_address is true" ) elif not point.use_next_available_address and not point.address: raise BadDataException( "address cannot be null when use_next_available_address is false" ) point.save_to_db(priority_array_write) if BACServer().status(): BACServer().add_point(point) return point
def get(cls, service): if service == OPEN_VPN_CLIENT: return ["v0.0.0"] token: str = get_github_token() headers = {} if token: headers['Authorization'] = f'Bearer {token}' app = get_app_from_service(service) resp = requests.get(app.get_releases_link(), headers=headers) data = json.loads(resp.content) releases = [] try: all_releases: bool = False if 'all' in request.args: all_releases = bool(strtobool(request.args['all'])) except Exception: raise BadDataException('Invalid query string') for row in data: if isinstance(row, str): raise PreConditionException(data) if all_releases: releases.append(row.get('tag_name')) elif version.parse(app.min_support_version) <= version.parse(row.get('tag_name')): releases.append(row.get('tag_name')) if not releases: raise NotFoundException(f'No version found, check your repo with version >= {app.min_support_version}') return releases
def post(cls): args = request.get_json() if not validate_args(args, delete_data_attributes): raise BadDataException('Invalid request') delete_data_res = [] for arg in args: service: str = arg['service'].upper() app: InstallableApp = get_app_from_service(service) try: res = { 'service': service, 'deletion': False, 'backup_data': False, 'stop': False, 'error': '' } stop: bool = app.stop() backup_data: bool = app.backup_data() deletion: bool = delete_existing_folder(app.get_data_dir()) res = { **res, 'deletion': deletion, 'backup_data': backup_data, 'stop': stop } except Exception as e: res = {'error': str(e)} delete_data_res.append(res) return delete_data_res
def update_user(cls, username, password): if not re.match("^([A-Za-z0-9_-])+$", username): raise BadDataException( "username should be alphanumeric and can contain '_', '-'") app_setting = current_app.config[AppSetting.FLASK_KEY] hashed_password = generate_password_hash(password, method='sha256') default_user = f'{username}:{hashed_password}' write_file(app_setting.users_file, default_user)
def put(cls): args = request.get_json() if args is None: raise BadDataException("Invalid request") service = args.get('service', '').upper() data = args.get('data', None) app: InstallableApp = get_app_from_service(service) update = app.update_config_file(data) app_details = get_installed_app_details(app) or {} return {'service': service, 'update': update, **app_details}
def patch(cls, **kwargs): data = cls.patch_parser.parse_args() point: PointModel = cls.get_point(**kwargs) if not point: raise NotFoundException('Point does not exist') if not point.writable: raise BadDataException('Point is not writable') point.update_point_store(value=data.get('value'), priority=data.get('priority'), priority_array_write=data.get('priority_array_write')) return {}
def get(cls): service: str = request.args.get('service') if not service: raise BadDataException("Include ?service as an argument") app: InstallableApp = get_app_from_service(service) filename = 'logging.conf' directory = os.path.join(app.get_global_dir(), 'config') file = os.path.join(directory, filename) if not os.path.exists(file): raise NotFoundException( f'Service {service} does not have {filename}') return {"data": read_file(file)}
def post(cls): args = request.get_json() if not validate_args(args, download_attributes): raise BadDataException('Invalid request') download_state: str = get_download_state().get('state') if download_state == DownloadState.DOWNLOADING.name: raise PreConditionException('Download is in progress') elif download_state == DownloadState.DOWNLOADED.name: raise PreConditionException('Download state is not cleared') update_download_state(DownloadState.DOWNLOADING) gevent.spawn(download_async, current_app._get_current_object().app_context, args) return {"message": "Download started"}
def model_marshaller_with_children(data: any, args: dict, base_fields: dict, children_fields: dict): with_children = False if 'with_children' in args: try: with_children = bool(strtobool(args['with_children'])) except Exception: raise BadDataException('Invalid query string') if with_children: return marshal(data, children_fields) else: return marshal(data, base_fields)
def get(cls): service: str = request.args.get('service') if not service: raise BadDataException("Include ?service as an argument") app: InstallableApp = get_app_from_service(service) if not is_dir_exist(app.get_data_dir()): raise NotFoundException(f'Service {service} does not have any data to download') file = app.download_data() if request.args.get('bridge'): raise NotImplementedException("We don't have the application/zip download support yet!") return send_file(file, mimetype='application/zip', attachment_filename=f'{service}_DATA_{datetime.now().strftime("%Y%m%d%H%M%S")}.zip', as_attachment=True)
def get(cls): service: str = request.args.get('service') if not service: raise BadDataException("Include ?service as an argument") app: InstallableApp = get_app_from_service(service) if app.app_type == Types.APT_APP.value: return {"data": read_file(app.app_setting.config_file)} else: filename = 'config.json' directory = os.path.join(app.get_global_dir(), 'config') file = os.path.join(directory, filename) if not os.path.exists(file): raise NotFoundException( f'Service {service} does not have {filename}') return {"data": json.loads(read_file(file))}
def delete(cls): args = request.get_json() if not validate_args(args, restart_job_delete_attributes): raise BadDataException('Invalid request') restart_res = [] for arg in args: service: str = arg['service'].upper() res = {'service': service, 'error': ''} try: cls.validate_service(service) delete_service_restart_job(service) except Exception as e: res = {**res, 'error': str(e)} restart_res.append(res) return restart_res
def post(cls): parser = reqparse.RequestParser() parser.add_argument('global_uuid', type=str) args = parser.parse_args() global_uuid = args['global_uuid'] device: Dict = {**RemoteDeviceRegistry().devices[global_uuid]} # new dict del device['count'] if global_uuid not in RemoteDeviceRegistry().devices and device: raise NotFoundException(f"global_uuid = {global_uuid} does not exist on discovered devices list") slaves, slaves_file = cls.get_slaves() if global_uuid in slaves: raise BadDataException(f"global_uuid = {global_uuid} is already inserted") slaves[global_uuid] = device write_file(slaves_file, json.dumps(slaves)) return slaves
def post(cls): args = request.get_json() if not validate_args(args, install_attributes): raise BadDataException('Invalid request') download_state: str = get_download_state().get('state') if download_state == DownloadState.DOWNLOADING.name: raise PreConditionException('Download is in progress') install_res = [] rubix_plat = args.pop(next((i for i, item in enumerate(args) if item["service"].upper() == "RUBIX_PLAT"), -1)) processes = [] for arg in args: processes.append(gevent.spawn(install_app_async, current_app._get_current_object().app_context, arg)) gevent.joinall(processes) for process in processes: install_res.append(process.value) if rubix_plat: install_res.append(install_app(rubix_plat)) return install_res
def post(cls): args = request.get_json() if not validate_args(args, control_attributes): raise BadDataException('Invalid request') control_res = [] for arg in args: service: str = arg['service'] action: str = arg['action'] res = {'service': service, 'action': action, 'error': ''} try: _action: str = validate_and_create_action(arg['action']) service_cmd: str = cls.validate_and_create_service_cmd( _action, arg['service']) execute_command_with_exception(service_cmd) except Exception as e: res = {**res, 'error': str(e)} control_res.append(res) return control_res
def post(cls): parser = reqparse.RequestParser() parser.add_argument('username', type=str, required=True, store_missing=False) parser.add_argument('password', type=str, required=True, store_missing=False) args = parser.parse_args() user = UserModel.find_by_username(args['username']) if user is None: raise NotFoundException('User does not exist') if not check_password_hash(user.password, args['password']): raise BadDataException( 'username and password combination is incorrect') return encode_jwt_token(user.uuid, user.username)
def post(cls): parser = reqparse.RequestParser() parser.add_argument('service', type=str, required=True) parser.add_argument('version', type=str, required=True) parser.add_argument('file', type=FileStorage, location='files', required=True) args = parser.parse_args() service = args['service'].upper() version = args['version'] file = args['file'] match: bool = Version._regex.search(version) if not match: raise BadDataException( f'Invalid version, version needs to be like v1.0.0, v1.1.0') app: InstallableApp = get_app_from_service(service, version) return app.upload(file)
def post(cls): parser = reqparse.RequestParser() parser.add_argument('interface', type=str, help='example `eth0`', required=True) parser.add_argument('ip_address', type=str, help='example `192.168.15.1`', required=True) parser.add_argument('routers', type=str, help='example `192.168.15.1`', required=True) parser.add_argument('domain_name_server', type=str, help='example `8.8.8.8`', required=True) parser.add_argument('netmask', type=str, help='example `255.255.255.0`', required=True) parser.add_argument('network_reset', type=bool, help='Will reset networking`', required=True) args = parser.parse_args() interface = args['interface'] if not is_interface_up(interface): raise BadDataException("interface is not valid") ip_address = args['ip_address'] if not is_valid_ip(ip_address): raise BadDataException("ip address is not valid") routers = args['routers'] if not is_valid_ip(routers): raise BadDataException("routers address is not valid") if not is_valid_ip(routers): raise BadDataException("routers address is not valid") domain_name_server = args['domain_name_server'] if not is_valid_ip(domain_name_server): raise BadDataException("domain_name_server address is not valid") netmask = args['netmask'] if not is_valid_ip(netmask): raise BadDataException("netmask address is not valid") reset = args['network_reset'] ip = dhcpcdManager() ip.set_static_info(interface, ip_address, routers, domain_name_server, netmask) if reset: ip.restart_interface(interface) return True
def post(cls, service): service = service.upper() args = request.get_json() if not validate_args(args, install_plugin_attributes): raise BadDataException('Invalid request') uninstall_res = [] try: app: InstallableApp = get_app_from_service(service) for arg in args: plugin: str = arg["plugin"].lower() installation = app.uninstall_plugin(plugin) uninstall_res.append({ 'plugin': plugin, 'uninstall': installation, 'error': '' }) except (Exception, NotFoundException) as e: raise NotFoundException(str(e)) return uninstall_res
def model_network_marshaller(data: any, args: dict, base_fields: dict, children_without_point_fields: dict, children_fields: dict): with_children = False points = False try: if 'with_children' in args: with_children = bool(strtobool(args['with_children'])) if 'points' in args: points = bool(strtobool(args['points'])) except Exception: raise BadDataException('Invalid query string') if with_children: if points: return marshal(data, children_fields) else: return marshal(data, children_without_point_fields) else: return marshal(data, base_fields)
def post(cls): parser = reqparse.RequestParser() parser.add_argument('interface', type=str, help='example `192.168.15`', required=True) parser.add_argument('network_reset', type=bool, help='Will reset networking`', required=True) args = parser.parse_args() interface = args['interface'] reset = args['network_reset'] if not is_interface_up(interface): raise BadDataException("interface is not valid") ip = dhcpcdManager() ip.remove_static_info(interface) if reset: ip.restart_interface(interface) return True
def post(cls, service): service = service.upper() args = request.get_json() if not validate_args(args, download_plugin_attributes): raise BadDataException('Invalid request') download_state: str = get_plugin_download_state(service).get('state') if download_state == DownloadState.DOWNLOADING.name: raise PreConditionException('Download is in progress') elif download_state == DownloadState.DOWNLOADED.name: raise PreConditionException('Download state is not cleared') app: InstallableApp = get_app_from_service(service) _version: str = app.get_installed_version() if not _version: return {"message": f"Please install service {service} first"} app.set_version(_version) update_plugin_download_state(DownloadState.DOWNLOADING, service, _version) gevent.spawn(download_plugins_async, current_app._get_current_object().app_context, app, args) return {"message": "Download started"}
def post(cls, service): service = service.upper() args = request.get_json() if not validate_args(args, install_plugin_attributes): raise BadDataException('Invalid request') install_res = [] try: app: InstallableApp = get_app_from_service(service) _version: str = app.get_installed_version() if not _version: return {"message": f"Please install service {service} first"} for arg in args: plugin: str = arg["plugin"].lower() installation = app.install_plugin(plugin) install_res.append({ 'plugin': plugin, 'installation': installation, 'error': '' }) except (Exception, NotFoundException) as e: raise NotFoundException(str(e)) return install_res
def post(cls): args = request.get_json() if not validate_args(args, restart_job_attributes): raise BadDataException('Invalid request') restart_res = [] for arg in args: service: str = arg['service'].upper() timer: int = arg['timer'] res = {'service': service, 'timer': timer, 'error': ''} try: cmd: str = cls.validate_and_create_restart_service_cmd(arg['service'].upper()) restart_job: dict = { service: { "timer": timer, "cmd": cmd, "prev_time": str(datetime.now()), "next_time": str(datetime.now() + timedelta(minutes=timer)) } } create_service_restart_job(restart_job) except Exception as e: res = {**res, 'error': str(e)} restart_res.append(res) return restart_res
def abort_if_bacnet_is_not_running(cls): if not BACServer().status(): raise BadDataException('BACnet server is not running')