def __init__(self): """The Constructor for UpdateCompany class""" self.postgres = PostgreSQL() self._couch_db = CouchDatabase() self.couch_query = Queries() self.log = Log() super(UpdateCompany, self).__init__()
def __init__(self): """The Constructor for DeviceOverview class""" self.postgres = PostgreSQL() self.couch_query = Queries() self.unit_conversion = UnitConversion() self.calc = calculate_alarm_trigger.CalculateAlarmTrigger() super(DeviceOverview, self).__init__()
def __init__(self): """The Constructor for EmailVesselInfo class""" self.postgres = PostgreSQL() self.couch_query = Queries() self.epoch_default = 26763 super(EmailVesselInfo, self).__init__()
def __init__(self): """The Constructor for UpdateModuleState class""" self._couch_db = CouchDatabase() self.couch_query = Queries() self.postgres = PostgreSQL() super(UpdateModuleState, self).__init__()
def __init__(self): """The Constructor for BlockageData class""" self.blocks = Blockages() self.postgres = PostgreSQL() self.couch_query = Queries() self.epoch_default = 26763 super(BlockageData, self).__init__()
def __init__(self): """The Constructor for Invite class""" # INIT CONFIG self.config = ConfigParser() # CONFIG FILE self.config.read("config/config.cfg") self._couch_db = CouchDatabase() self.couch_query = Queries() self.postgres = PostgreSQL() self.epoch_default = 26763 self.vpn_db_build = config_section_parser(self.config, "VPNDB")['build'] super(Invite, self).__init__() if self.vpn_db_build.upper() == 'TRUE': self.my_ip = config_section_parser(self.config, "IPS")['my'] self.my_protocol = config_section_parser(self.config, "IPS")['my_protocol'] self.user_vpn = config_section_parser(self.config, "IPS")['user_vpn'] self.user_protocol = config_section_parser(self.config, "IPS")['user_protocol'] self.vessel_vpn = config_section_parser(self.config, "IPS")['vessel_vpn'] self.vessel_protocol = config_section_parser( self.config, "IPS")['vessel_protocol'] self.vpn_token = '269c2c3706886d94aeefd6e7f7130ab08346590533d4c5b24ccaea9baa5211ec'
def __init__(self): """The Constructor for Device Upload class""" self.couch_query = Queries() self.postgres = PostgreSQL() self.aws3 = AwsS3() super(Upload, self).__init__()
def __init__(self): """The Constructor for ObuSummary class""" self.postgres = PostgreSQL() self.couch_query = Queries() self.unit_conversion = UnitConversion() super(ObuSummary, self).__init__()
def __init__(self): """The Constructor for DeleteVessel class""" super(DeleteVessel, self).__init__() self.couch_query = Queries() # INIT CONFIG self.config = ConfigParser() # CONFIG FILE self.config.read("config/config.cfg") self.postgres = PostgreSQL() self.vpn_db_build = config_section_parser(self.config, "VPNDB")['build'] if self.vpn_db_build.upper() == 'TRUE': self.my_ip = config_section_parser(self.config, "IPS")['my'] self.my_protocol = config_section_parser(self.config, "IPS")['my_protocol'] self.vessel_vpn = config_section_parser(self.config, "IPS")['vessel_vpn'] self.vessel_protocol = config_section_parser( self.config, "IPS")['vessel_protocol'] self.vpn_token = '269c2c3706886d94aeefd6e7f7130ab08346590533d4c5b24ccaea9baa5211ec'
def __init__(self): """The Constructor for NetworkConfiguration class""" self._couch_db = CouchDatabase() self.postgresql_query = PostgreSQL() self.couch_query = Queries() self.epoch_default = 26763 super(NetworkConfiguration, self).__init__()
def __init__(self): """The Constructor for Failover class""" self._couch_db = CouchDatabase() self.postgresql_query = PostgreSQL() self.couch_query = Queries() self.epoch_default = 26763 super(Failover, self).__init__()
def __init__(self): """The Constructor for Vessel class""" # self._my_db = MySQLDatabase() self._couch_db = CouchDatabase() self.couch_query = Queries() self.postgres = PostgreSQL() self.epoch_default = 26763 self.aws3 = AwsS3() super(Vessel, self).__init__()
def __init__(self): """The Constructor for AlarmRecord class""" self.postgres = PostgreSQL() self.log = Log() self.calc_trigger = calculate_alarm_trigger.CalculateAlarmTrigger() self.calc_value = calculate_alarm_value.CalculateAlarmValue() self.format_alarm = FormatAlarmState() self.couch_query = Queries() self.epoch_default = 26763 super(AlarmRecord, self).__init__()
def __init__(self): """The Constructor for RemoteCommand class""" # INIT CONFIG self.config = ConfigParser() # CONFIG FILE self.config.read("config/config.cfg") self._couch_db = CouchDatabase() self.couch_query = Queries() self.postgres = PostgreSQL() self.epoch_default = 26763 super(RemoteCommand, self).__init__()
def __init__(self): """The Constructor for Device class""" # INIT CONFIG self.config = ConfigParser() # CONFIG FILE self.config.read("config/config.cfg") self._couch_db = CouchDatabase() self.couch_query = Queries() self.aws3 = AwsS3() self.epoch_default = 26763 self.db_host = config_section_parser(self.config, "COUCHDB")['host'] self.db_port = config_section_parser(self.config, "COUCHDB")['port'] super(Device, self).__init__()
def __init__(self): """The Constructor for CreateSubCategory class""" self.postgresql_query = PostgreSQL() self._couch_db = CouchDatabase() self.couch_query = Queries() super(CreateSubCategory, self).__init__()
def __init__(self): """The Constructor for CreateAlarmValue class""" self.postgres = PostgreSQL() self.couch_query = Queries() self.validate_value = ValidateAlarmValue() super(CreateAlarmValue, self).__init__()
def __init__(self): """The Constructor for VesselFiles class""" self.postgres = PostgreSQL() self.couch_query = Queries() self.device_state = UpdateDeviceState() self.aws3 = AwsS3() super(VesselFiles, self).__init__()
def __init__(self): """The Constructor for Vessels class""" self._couch_db = CouchDatabase() self.couch_query = Queries() self.postgres = PostgreSQL() self.epoch_default = 26763 self.vessel_name = "" self.aws3 = AwsS3() # INIT CONFIG self.config = ConfigParser() # CONFIG FILE self.config.read("config/config.cfg") self.vpn_db_build = config_section_parser(self.config, "VPNDB")['build'] super(MapVessels, self).__init__()
def __init__(self): """The Constructor for UpdateINIFiles class""" # INIT CONFIG self.config = ConfigParser() # CONFIG FILE self.config.read("config/config.cfg") self._couch_db = CouchDatabase() self.couch_query = Queries() self.postgres = PostgreSQL() super(UpdateINIFiles, self).__init__() self.vpn_db_build = config_section_parser(self.config, "VPNDB")['build'] self.vessel_vpn = config_section_parser(self.config, "IPS")['vessel_vpn'] self.vessel_protocol = config_section_parser(self.config, "IPS")['vessel_protocol'] self.vpn_token = '269c2c3706886d94aeefd6e7f7130ab08346590533d4c5b24ccaea9baa5211ec'
class UpdateOptionState(Common): """Class for UpdateOptionState""" # INITIALIZE def __init__(self): """The Constructor for UpdateOptionState class""" self._couch_db = CouchDatabase() self.couch_query = Queries() self.postgres = PostgreSQL() super(UpdateOptionState, self).__init__() def update_option_state(self): """Update Option State""" options = self.couch_query.get_options() option_ids = [x['_id'] for x in options] # INIT SQL QUERY sql_str = "SELECT * FROM option" # FETCH ALL rows = self.postgres.query_fetch_all(sql_str) db_option_ids = [x['option_id'] for x in rows] option_ids = set(option_ids) db_option_ids = set(db_option_ids) option_ids.difference_update(db_option_ids) if option_ids: opt_ids = list(option_ids) for option in options: if option['_id'] in opt_ids: data = {} data['option_id'] = option['_id'] data['option'] = option['option'] data['vessel_id'] = option['vessel_id'] data['update_on'] = time.time() data['created_on'] = time.time() self.postgres.insert('option', data) # RETURN return rows
class UpdateModuleState(Common): """Class for UpdateModuleState""" # INITIALIZE def __init__(self): """The Constructor for UpdateModuleState class""" self._couch_db = CouchDatabase() self.couch_query = Queries() self.postgres = PostgreSQL() super(UpdateModuleState, self).__init__() def update_module_state(self): """Update Module State""" modules = self.couch_query.get_modules() module_ids = [x['_id'] for x in modules] # INIT SQL QUERY sql_str = "SELECT * FROM module" # FETCH ALL rows = self.postgres.query_fetch_all(sql_str) db_module_ids = [x['module_id'] for x in rows] module_ids = set(module_ids) db_module_ids = set(db_module_ids) module_ids.difference_update(db_module_ids) if module_ids: mdl_ids = list(module_ids) for module in modules: if module['_id'] in mdl_ids: data = {} data['module_id'] = module['_id'] data['module'] = module['module'] data['vessel_id'] = module['vessel_id'] data['update_on'] = time.time() data['created_on'] = time.time() self.postgres.insert('module', data) # RETURN return rows
def __init__(self): """The Constructor for UserProfile class""" self.postgres = PostgreSQL() self.couch_query = Queries() super(UserProfile, self).__init__()
class Failover(Common): """Class for Failover""" # INITIALIZE def __init__(self): """The Constructor for Failover class""" self._couch_db = CouchDatabase() self.postgresql_query = PostgreSQL() self.couch_query = Queries() self.epoch_default = 26763 super(Failover, self).__init__() def failover(self): """ This API is for Getting Failover --- tags: - Vessel produces: - application/json parameters: - name: token in: header description: Token required: true type: string - name: userid in: header description: User ID required: true type: string - name: vessel_id in: query description: Vessel ID required: true type: string - name: date in: query description: Epoch date required: false type: string - name: limit in: query description: Limit required: true type: integer - name: page in: query description: Page required: true type: integer - name: sort_type in: query description: Sort Type required: false type: string - name: sort_column in: query description: Sort Column required: false type: string - name: filter_column in: query description: Filter Column required: false type: string - name: filter_value in: query description: Filter Value required: false type: string responses: 500: description: Error 200: description: Vessel Failover """ data = {} # VESSEL ID vessel_id = request.args.get('vessel_id') epoch_date = request.args.get('date') limit = int(request.args.get('limit')) page = int(request.args.get('page')) sort_type = request.args.get('sort_type') sort_column = request.args.get('sort_column') filter_column = request.args.get('filter_column') filter_value = request.args.get('filter_value') # GET DATA token = request.headers.get('token') userid = request.headers.get('userid') # CHECK TOKEN token_validation = self.validate_token(token, userid) if not token_validation: data["alert"] = "Invalid Token" data['status'] = 'Failed' # RETURN ALERT return self.return_data(data) if not vessel_id: data["alert"] = "Please complete parameters!" data['status'] = 'Failed' # RETURN ALERT return self.return_data(data) filter_mod_val = "" filter_subcat = "" filter_option = "" filter_val = "" if filter_column and filter_value: i = 0 for filter_col in filter_column.split(","): if filter_col == "category": filter_mod_val = filter_value.split(",")[i] elif filter_col == "sub_category": filter_subcat = filter_value.split(",")[i] elif filter_col == "option": filter_option = filter_value.split(",")[i] elif filter_col == "value": filter_val = filter_value.split(",")[i] i += 1 data = {} data['data'] = [] total_page = 0 if epoch_date: values = self.couch_query.get_complete_values( vessel_id, "FAILOVER", str(self.epoch_default), str(epoch_date), flag='one_doc' ) else: values = self.couch_query.get_complete_values( vessel_id, "FAILOVER", flag='one_doc' ) if values: all_values = values['value'] timestamp = values['timestamp'] temp_datas, options, categories = self.values_wrapper("FAILOVER", all_values, timestamp ) convert = UnitConversion() temp_datas = convert.check_unit(temp_datas) temp_datas = self.add_device_subcategory(temp_datas) temp_datas = self.add_device_category(temp_datas) rows = self.value_filter(filter_mod_val, filter_subcat, filter_option, filter_val, temp_datas) if sort_type and sort_column: sort_column = sort_column.lower() if sort_type.lower() == "desc" and sort_column in ['category', 'sub_category', 'option', 'value']: rows = sorted(rows, key=lambda i: i[sort_column], reverse=True) if sort_type.lower() == "asc": rows = sorted(rows, key=lambda i: i[sort_column]) else: rows = [] options = [] categories = [] datas = self.limits(rows, limit, page) total_count = len(datas) total_page = int(math.ceil(int(total_count - 1) / limit)) final_data = [] temp_category = '' temp_subcat = '' for item in datas: if temp_category == item['category']: item['category'] = '' else: temp_category = item['category'] if temp_subcat == item['sub_category']: item['sub_category'] = '' else: temp_subcat = item['sub_category'] final_data.append(item) data['data'] = final_data data['total_page'] = total_page data['limit'] = int(limit) data['page'] = int(page) data['total_rows'] = total_count data['options'] = options data['categories'] = categories data['subcategories'] = self.get_device_subcategory(datas) data['status'] = 'ok' return self.return_data(data)
class Invite(Common, ShaSecurity): """Class for Invite""" # INITIALIZE def __init__(self): """The Constructor for Invite class""" # INIT CONFIG self.config = ConfigParser() # CONFIG FILE self.config.read("config/config.cfg") self._couch_db = CouchDatabase() self.couch_query = Queries() self.postgres = PostgreSQL() self.epoch_default = 26763 self.vpn_db_build = config_section_parser(self.config, "VPNDB")['build'] super(Invite, self).__init__() if self.vpn_db_build.upper() == 'TRUE': self.my_ip = config_section_parser(self.config, "IPS")['my'] self.my_protocol = config_section_parser(self.config, "IPS")['my_protocol'] self.user_vpn = config_section_parser(self.config, "IPS")['user_vpn'] self.user_protocol = config_section_parser(self.config, "IPS")['user_protocol'] self.vessel_vpn = config_section_parser(self.config, "IPS")['vessel_vpn'] self.vessel_protocol = config_section_parser( self.config, "IPS")['vessel_protocol'] self.vpn_token = '269c2c3706886d94aeefd6e7f7130ab08346590533d4c5b24ccaea9baa5211ec' # GET VESSEL FUNCTION def invitation(self): """ This API is for Sending invitation --- tags: - User produces: - application/json parameters: - name: token in: header description: Token required: true type: string - name: userid in: header description: User ID required: true type: string - name: query in: body description: Invite required: true schema: id: Invite properties: first_name: type: string last_name: type: string middle_name: type: string url: type: string email: type: string companies: types: array example: [] roles: types: array example: [] vessels: types: array example: [] responses: 500: description: Error 200: description: Sending invitaion """ # INIT DATA data = {} # GET DATA token = request.headers.get('token') userid = request.headers.get('userid') # GET JSON REQUEST query_json = request.get_json(force=True) # GET REQUEST PARAMS email = query_json["email"] url = query_json["url"] vessels = query_json['vessels'] # CHECK TOKEN token_validation = self.validate_token(token, userid) if not token_validation: data["alert"] = "Invalid Token" data['status'] = 'Failed' # RETURN ALERT return self.return_data(data) # INIT IMPORTANT KEYS important_keys = {} important_keys['companies'] = [] important_keys['roles'] = [] important_keys['email'] = "string" important_keys['url'] = "string" # CHECK IMPORTANT KEYS IN REQUEST JSON if not self.check_request_json(query_json, important_keys): data["alert"] = "Invalid query, Missing parameter!" data['status'] = 'Failed' # RETURN ALERT return self.return_data(data) # CHECK INVITATION if self.check_invitaion(email): data["alert"] = "Already invited!" data['status'] = 'Failed' # RETURN ALERT return self.return_data(data) password = self.generate_password() # INSERT INVITATION account_id = self.insert_invitation(password, query_json) if not account_id: data = {} data['message'] = "Invalid email!" data['status'] = "Failed" return self.return_data(data) if self.vpn_db_build.upper() == 'TRUE': # FOR USER VPN # JOB DATAS callback_url = self.my_protocol + "://" + self.my_ip + "/vpn/update" data_url = self.my_protocol + "://" + self.my_ip + "/vpn/data" sql_str = "SELECT * FROM account_role where account_id='{0}' ".format( account_id) sql_str += "AND role_id in (SELECT role_id FROM role " sql_str += "WHERE role_name='super admin')" super_admin = self.postgres.query_fetch_one(sql_str) vpn_type = 'VCLIENT' cvpn_type = 'CLIENT' if super_admin: vpn_type = 'VRH' cvpn_type = 'RHADMIN' # INSERT JOB job_id = self.insert_job(callback_url, data_url, self.vpn_token, account_id, self.user_vpn, cvpn_type) # INIT PARAMS FOR CREATE VPN vpn_params = {} vpn_params['callback_url'] = callback_url vpn_params['data_url'] = data_url vpn_params['job_id'] = job_id # CREATE VPN self.create_vpn(vpn_params, self.vpn_token) # FOR VESSEL VPN if vessels or super_admin: allow_access = False for vessel in vessels: if vessel['allow_access']: allow_access = True break if allow_access or super_admin: # INSERT JOB job_id = self.insert_job(callback_url, data_url, self.vpn_token, account_id, self.vessel_vpn, vpn_type) # INIT PARAMS FOR CREATE VPN vpn_params = {} vpn_params['callback_url'] = callback_url vpn_params['data_url'] = data_url vpn_params['job_id'] = job_id # CREATE VPN self.create_vpn(vpn_params, self.vpn_token, True) # SEND INVITATION self.send_invitation(email, password, url) data = {} data['message'] = "Invitation successfully sent!" data['status'] = "ok" return self.return_data(data) def check_invitaion(self, email): """Check Invitation""" sql_str = "SELECT * FROM account WHERE " sql_str += " email = '" + email + "'" res = self.postgres.query_fetch_one(sql_str) if res: return res return 0 def check_username(self, username): """Check Invitation""" sql_str = "SELECT * FROM account WHERE " sql_str += " username = '******'" res = self.postgres.query_fetch_one(sql_str) if res: return res return 0 def insert_invitation(self, password, query_json): """Insert Invitation""" token = self.generate_token() vessels = query_json['vessels'] companies = query_json['companies'] roles = query_json['roles'] data = query_json data = self.remove_key(data, "companies") data = self.remove_key(data, "roles") data = self.remove_key(data, "vessels") # username = query_json["email"].split("@")[0] username = "******".format(int(time.time())) if not self.check_username(username): username += self.random_str_generator(5) data['username'] = username data['token'] = token data['status'] = True data['state'] = False data['password'] = self.string_to_sha_plus(password) data['created_on'] = time.time() account_id = self.postgres.insert('account', data, 'id') if not account_id: return 0 for vessel in vessels: ntwconf = self.couch_query.get_complete_values( vessel['vessel_id'], "NTWCONF") # ACCOUNT VESSEL temp = {} temp['vessel_vpn_ip'] = ntwconf['NTWCONF']['tun1']['IP'] temp['account_id'] = account_id temp['vessel_id'] = vessel['vessel_id'] temp['vessel_vpn_state'] = 'pending' temp['allow_access'] = False if 'allow_access' in vessel.keys(): temp['allow_access'] = vessel['allow_access'] self.postgres.insert('account_vessel', temp) for company in companies: # ACCOUNT COMPANY temp = {} temp['account_id'] = account_id temp['company_id'] = company self.postgres.insert('account_company', temp) for role_id in roles: # ACCOUNT COMPANY temp = {} temp['account_id'] = account_id temp['role_id'] = role_id self.postgres.insert('account_role', temp) return account_id def send_invitation(self, email, password, url): """Send Invitation""" email_temp = Invitation() emailer = Email() message = email_temp.invitation_temp(password, url) subject = "Invitation" emailer.send_email(email, message, subject) return 1 def generate_password(self): """Generate Password""" char = string.ascii_uppercase char += string.ascii_lowercase char += string.digits return self.random_str_generator(8, char) def insert_job(self, callback_url, data_url, vpn_token, account_id, user_vpn, vpn_type): """Insert Job""" update_on = time.time() # INIT NEW JOB temp = {} temp['callback_url'] = callback_url temp['vnp_server_ip'] = user_vpn temp['data_url'] = data_url temp['token'] = vpn_token temp['status'] = 'pending' temp['account_id'] = account_id temp['vpn_type'] = vpn_type temp['action'] = 'CREATE' temp['account_os'] = 'WINDOWS' # LINUX temp['update_on'] = update_on temp['created_on'] = update_on # INSERT NEW JOB job_id = self.postgres.insert('job', temp, 'job_id') return job_id def create_vpn(self, data, vpn_token, flag=False): """Create VPN""" api_endpoint = self.user_protocol + "://" + self.user_vpn + "/ovpn" if flag: api_endpoint = self.vessel_protocol + "://" + self.vessel_vpn + "/ovpn" headers = {'content-type': 'application/json', 'token': vpn_token} req = requests.post(api_endpoint, data=json.dumps(data), headers=headers) res = req.json() return res
def __init__(self): """The Constructor for PortForwarding class""" self._couch_db = CouchDatabase() self.couch_query = Queries() self.epoch_default = 26763 super(PortForwarding, self).__init__()
class PortForwarding(Common): """Class for PortForwarding""" # INITIALIZE def __init__(self): """The Constructor for PortForwarding class""" self._couch_db = CouchDatabase() self.couch_query = Queries() self.epoch_default = 26763 super(PortForwarding, self).__init__() def port_forwarding(self): """ This API is for getting Port Forwarding of device --- tags: - Devices produces: - application/json parameters: - name: token in: header description: Token required: true type: string - name: userid in: header description: User ID required: true type: string - name: vessel_id in: query description: Vessel ID required: true type: string - name: device_id in: query description: Device ID required: false type: string - name: limit in: query description: Limit required: true type: integer - name: page in: query description: Page required: true type: integer responses: 500: description: Error 200: description: Vessel Device Info """ data = {} # VESSEL ID vessel_id = request.args.get('vessel_id') device_id = request.args.get('device_id') limit = int(request.args.get('limit')) page = int(request.args.get('page')) # GET DATA token = request.headers.get('token') userid = request.headers.get('userid') # CHECK TOKEN token_validation = self.validate_token(token, userid) if not token_validation: data["alert"] = "Invalid Token" data['status'] = 'Failed' # RETURN ALERT return self.return_data(data) if not vessel_id: data["alert"] = "Please complete parameters!" data['status'] = 'Failed' # RETURN ALERT return self.return_data(data) # device_list = [] device_name = "" if device_id: device_data = self.couch_query.get_by_id(device_id) dev_name = device_data['device'] # device_list.append(value) # else: # device_list = self.couch_query.get_device(vessel_id) # REMOVE DATA # data_to_remove = ['PARAMETERS', 'COREVALUES', 'FAILOVER', 'NTWCONF', 'NTWPERF1'] # device_list = self.remove_data(device_list, data_to_remove) datas = {} datas['data'] = [] final_data = [] ntwconf = self.couch_query.get_complete_values(vessel_id, "NTWCONF") parameters = self.couch_query.get_complete_values( vessel_id, "PARAMETERS") vpn_ip = ntwconf['NTWCONF']['tun1']['IP'] keys = parameters['PARAMETERS'].keys() for i in range(1, (len(keys))): temp_pf = {} port = 'PORTFORWARDING' + str(i) if port in keys: destination_ip_val = parameters['PARAMETERS'][port][ 'DESTINATIONIP'] destination_port_val = parameters['PARAMETERS'][port][ 'DESTINATIONPORT'] description_val = parameters['PARAMETERS'][port]['DESCRIPTION'] device_name = parameters['PARAMETERS'][port]['DEVICE'] link = description_val.lower() + '://' link += vpn_ip + ':' + parameters['PARAMETERS'][port][ 'SOURCEPORT'] if device_id and dev_name == device_name: temp_pf['destination_ip'] = destination_ip_val temp_pf['destination_port'] = destination_port_val temp_pf['description'] = description_val temp_pf['link'] = link temp_pf['device'] = device_name final_data.append(temp_pf) elif not device_id: temp_pf['destination_ip'] = destination_ip_val temp_pf['destination_port'] = destination_port_val temp_pf['description'] = description_val temp_pf['link'] = link temp_pf['device'] = device_name final_data.append(temp_pf) total_count = len(final_data) - 1 total_page = int(math.ceil(int(total_count) / limit)) + 1 final_data = self.limits(final_data, limit, page) datas['total_rows'] = total_count + 1 datas['total_page'] = total_page datas['limit'] = int(limit) datas['page'] = int(page) datas['data'] = final_data datas['status'] = 'ok' return self.return_data(datas)
class DeleteVessel(Common): """Class for DeleteVessel""" # INITIALIZE def __init__(self): """The Constructor for DeleteVessel class""" super(DeleteVessel, self).__init__() self.couch_query = Queries() # INIT CONFIG self.config = ConfigParser() # CONFIG FILE self.config.read("config/config.cfg") self.postgres = PostgreSQL() self.vpn_db_build = config_section_parser(self.config, "VPNDB")['build'] if self.vpn_db_build.upper() == 'TRUE': self.my_ip = config_section_parser(self.config, "IPS")['my'] self.my_protocol = config_section_parser(self.config, "IPS")['my_protocol'] self.vessel_vpn = config_section_parser(self.config, "IPS")['vessel_vpn'] self.vessel_protocol = config_section_parser( self.config, "IPS")['vessel_protocol'] self.vpn_token = '269c2c3706886d94aeefd6e7f7130ab08346590533d4c5b24ccaea9baa5211ec' def delete_vessel(self): """ This API is for Deleting Permission --- tags: - Vessel produces: - application/json parameters: - name: token in: header description: Token required: true type: string - name: userid in: header description: User ID required: true type: string - name: query in: body description: Vessel infos required: true schema: id: Delete Vessels properties: vessel_info: types: array example: [{'vessel_id': vesselid1, 'vessel_rev': vesselrev1 }] responses: 500: description: Error 200: description: Delete Vessel """ data = {} # GET JSON REQUEST query_json = request.get_json(force=True) # GET HEADER token = request.headers.get('token') userid = request.headers.get('userid') # GET QUERY vessel_info = query_json["vessel_info"] # CHECK TOKEN token_validation = self.validate_token(token, userid) if not token_validation: data["alert"] = "Invalid Token" data['status'] = 'Failed' # RETURN ALERT return self.return_data(data) for vssl in vessel_info: doc = self.couch_query.get_by_id(vssl['vessel_id']) # INIT PARAMS FOR CREATE VPN vpn_params = {} vpn_params['vessel_number'] = vssl['vessel_id'] if 'error' not in doc.keys(): vpn_params['vessel_number'] = doc['number'] if self.vpn_db_build.upper() == 'TRUE': if not self.revoke_vpn(vpn_params): data["alert"] = "Please try again after 5 minutes!" data['status'] = 'Failed' # RETURN ALERT return self.return_data(data) vessel_id = vssl['vessel_id'] vessel_rev = vssl['vessel_rev'] os.path.dirname(os.path.realpath(__file__)) subprocess.Popen([ "nohup", "python3", "delete_vessel.py", str(vessel_id), str(vessel_rev), ">", "out.log", "&" ]) data['message'] = "Vessel(s) successfully Deleted!" data['status'] = "ok" return self.return_data(data) def revoke_vpn(self, data): """Update VPN""" try: api_endpoint = self.vessel_protocol + "://" + self.vessel_vpn + "/delete/vessel/vpn" headers = { 'content-type': 'application/json', 'token': self.vpn_token } req = requests.delete(api_endpoint, data=json.dumps(data), headers=headers) res = req.json() if res['status'] == 'ok': cmd = "rm -rf /home/admin/all_vpn/VESSEL_" + str( data['vessel_number']) + ".zip" _ = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, check=True) return res except: return 0
def __init__(self): """The Constructor for Report class""" self.postgresql_query = PostgreSQL() self._couch_db = CouchDatabase() self.couch_query = Queries() super(Report, self).__init__()
class CreateCompany(Common): """Class for CreateCompany""" # INITIALIZE def __init__(self): """The Constructor for CreateCompany class""" self.postgresql_query = PostgreSQL() self._couch_db = CouchDatabase() self.couch_query = Queries() self.log = Log() super(CreateCompany, self).__init__() def create_company(self): """ This API is for Creating Company --- tags: - Company produces: - application/json parameters: - name: token in: header description: Token required: true type: string - name: userid in: header description: User ID required: true type: string - name: query in: body description: Company required: true schema: id: Company properties: company_name: type: string vessel_ids: types: array example: [] responses: 500: description: Error 200: description: Company """ data = {} # GET JSON REQUEST query_json = request.get_json(force=True) # GET HEADER token = request.headers.get('token') userid = request.headers.get('userid') # EXTRACT QUERY JSON company_name = query_json['company_name'] vessel_ids = query_json['vessel_ids'] # CHECK TOKEN token_validation = self.validate_token(token, userid) if not token_validation: data["alert"] = "Invalid Token" data['status'] = 'Failed' # RETURN ALERT return self.return_data(data) # CREATE COMPANY company_id = self.insert_company(company_name) if not company_id: data[ "alert"] = "Please check your query! | Company is Already Exist." data['status'] = 'Failed' # RETURN ALERT return self.return_data(data) # BIND COMPANY TO VESSELS alert, status = self.insert_company_vessels(company_id, vessel_ids) if status != 'ok': data["alert"] = alert data['status'] = status # RETURN ALERT return self.return_data(data) data['message'] = "Company successfully created!" data['status'] = "ok" return self.return_data(data) def insert_company(self, company_name): """Insert Company""" data = {} data['company_name'] = company_name data['created_on'] = time.time() company_id = self.postgresql_query.insert('company', data, 'company_id') return company_id or 0 def insert_company_vessels(self, company_id, vessel_ids): """Insert Company Vessels""" alert, status = '', '' if not self.check_vessel_existence(vessel_ids): alert = "Some Vessel/s doesn't exists." status = 'Failed' else: for vessel_id in vessel_ids: data = {} data['company_id'] = company_id data['vessel_id'] = vessel_id try: self.postgres.insert('company_vessels', data, 'company_id') alert = "" status = 'ok' except TypeError: alert = "ERROR inserting company vessels" status = 'Failed' return alert, status def check_vessel_existence(self, vessel_ids): """Verify if vessel exists""" for _id in vessel_ids: res = self.couch_query.get_by_id(_id) if res.get('error', False): return 0 if res.get('_id', False): pass else: return 0 return 1