def get_pwd_expire(request, adict): pwdcycle = int( GetDictionary(DataDictionary.DICT_TYPE_PWD_CYCLE, "pwdcycle", '0')) if pwdcycle == 0: adict['exp_days'] = '永不过期' return None pwdexpriy = GetDictionary(DataDictionary.DICT_TYPE_PWD_EXPIRY, request.user.id, 'none') if pwdexpriy == 'none': adict['exp_days'] = '请重新登录' return None else: t = (datetime.datetime.strptime(str(pwdexpriy), "%Y-%m-%d %H:%M:%S") - timezone.now()).days adict['exp_days'] = str(t + 1) + '天' return None
def kvm_remote_procedure_call(self, params): from xdashboard.common.dict import GetDictionary from xdashboard.models import DataDictionary params_obj = json.loads(params) if params_obj.get('info'): params_obj['info']['aio_server_ip'] = '{}'.format('{}{}'.format( GetDictionary(DataDictionary.DICT_TYPE_TAKEOVER_SEGMENT, 'SEGMENT', '172.29'), '.16.2')) return self.getLogicPrx().kvmRpc( json.dumps(params_obj, ensure_ascii=False))
def is_database_full(): from xdashboard.models import DataDictionary from xdashboard.common.dict import GetDictionary database_used_bytes = get_database_size() database_can_use_size = GetDictionary( DataDictionary.DICT_TYPE_DATABASE_CAN_USE_SIZE, 'dbmaxsize', str(1024)) database_can_use_size = int(database_can_use_size) if database_can_use_size * 1024 * 1024 * 0.95 <= database_used_bytes: return True, database_can_use_size, database_used_bytes return False, database_can_use_size, database_used_bytes
def getUrl(request): jsonstr = { "r": 0, "e": "操作成功", "url": GetDictionary(DataDictionary.DICT_TYPE_UPDATE_URL, 'url', "update.clerware.com") } return HttpResponse(json.dumps(jsonstr, ensure_ascii=False))
def _create_aio_tap(self, tap_name): cmd = r'ip tuntap add {tap_name} mode tap'.format(tap_name=tap_name) self._excute_cmd_and_return_code(cmd, False) cmd = r'ip link set {tap_name} master takeoverbr0'.format( tap_name=tap_name) self._excute_cmd_and_return_code(cmd, False) cmd = r'ifconfig {tap_name} {ip} up'.format( tap_name=tap_name, ip='{}{}'.format( GetDictionary(DataDictionary.DICT_TYPE_TAKEOVER_SEGMENT, 'SEGMENT', '172.29'), '.16.1')) self._excute_cmd_and_return_code(cmd, False)
def _create_br(self): name = 'takeoverbr0' if not self._is_adpter_name_exist(name): cmd = r'ip link add takeoverbr0 type bridge' self._excute_cmd_and_return_code(cmd, True) # cmd = r'ifconfig takeoverbr0 0.0.0.0 promisc up' # self._excute_cmd_and_return_code(cmd, True) cmd = r'ifconfig takeoverbr0 {} up'.format('{}{}'.format( GetDictionary(DataDictionary.DICT_TYPE_TAKEOVER_SEGMENT, 'SEGMENT', '172.29'), '.16.2')) self._excute_cmd_and_return_code(cmd, True) tap_name = 'aiotap0' if not self._is_adpter_name_exist(tap_name): self._create_aio_tap(tap_name) time.sleep(5) self._net_restart_service()
def isSessionTimeout(request): try: if request.user.is_authenticated(): if 'lastRequest' in request.session: elapsedTime = time.time() - request.session['lastRequest'] if 'myexpiry' in request.session: Minute = int(request.session['myexpiry']) else: request.session['myexpiry'] = int( GetDictionary(DataDictionary.DICT_TYPE_EXPIRY, 'expiry', 120)) Minute = int(request.session['myexpiry']) if Minute != 0 and elapsedTime > Minute * 60: del request.session['lastRequest'] return True request.session['lastRequest'] = time.time() except Exception as e: _logger.info(str(e)) return False
def _add_private_adpter(self, kvm_adpter, exist_kvm_adpter=None): for adpter in kvm_adpter: if adpter['name'] in ('my_private_aio', ): return kvm_adpter bfind = False if exist_kvm_adpter: for adpter in exist_kvm_adpter: if adpter['name'] in ('my_private_aio', ): kvm_adpter.append(adpter) bfind = True break if not bfind: private_ip = list() kvm_private_ip = self._get_kvm_private_ip() for ip in kvm_private_ip: if 'ip' in ip: private_ip.append(ip['ip']) for i in range(3, 255): ip = '{seg}.16.{i}'.format(seg=GetDictionary( DataDictionary.DICT_TYPE_TAKEOVER_SEGMENT, 'SEGMENT', '172.29'), i=i) if ip not in private_ip: adpter = { "name": "my_private_aio", "nic_name": "Clerware Network Adapter", "ips": [{ "ip": ip, "mask": "255.255.0.0" }], "macvtap": "", "mac": self._get_unused_mac() } kvm_adpter.append(adpter) break return kvm_adpter
def _get_agent_service_configure(self, ext_info): try: user = User.objects.get(username=ext_info["UserIdent"]) user_id = user.id agent_user_info = '{}|*{}'.format( user_id, user.userprofile.user_fingerprint) except User.DoesNotExist: agent_user_info = '0|None' aio_ip = '{}{}'.format( GetDictionary(DataDictionary.DICT_TYPE_TAKEOVER_SEGMENT, 'SEGMENT', '172.29'), '.16.1') tunnel_ip = -1 tunnel_port = -1 routers = {"is_save": 0, "router_list": []} return { "user_info": agent_user_info, "aio_ip": aio_ip, "routers": routers, 'tunnel_ip': tunnel_ip, 'tunnel_port': tunnel_port }
def execute(self, **kwargs): self.task_content = { 'error': '', 'stime': timezone.now().strftime(xdatetime.FORMAT_WITH_USER_SECOND), } try: self.log_info('CreateVerifyKvm execute task_id={}'.format( self.task_id)) auto_verify_task_obj = AutoVerifyTask.objects.get(id=self.task_id) pointid = auto_verify_task_obj.point_id _hardware_recommend = get_takeover_hardware_recommend( pointid, True) self.task_content['logic'] = _hardware_recommend['logic'] params = pointid.split('|') if params[0] == xdata.SNAPSHOT_TYPE_NORMAL: snapshot_time = params[2] else: # CDP时间 snapshot_time = params[3] kvm_cpu_sockets = 1 kvm_cpu_cores = 2 private_ip = list() kvm_private_ip = self._get_kvm_private_ip() for ip in kvm_private_ip: if 'ip' in ip: private_ip.append(ip['ip']) kvm_ip = None kvm_mac = None for i in range(1, 255): ip = '{seg}.130.{i}'.format(seg=GetDictionary( DataDictionary.DICT_TYPE_TAKEOVER_SEGMENT, 'SEGMENT', '172.29'), i=i) if ip not in private_ip: kvm_mac = self._get_mac_address(ip) kvm_ip = ip break assert kvm_ip assert kvm_mac schedule_ext_config_obj = json.loads( auto_verify_task_obj.schedule_ext_config) api_request = { "name": 'auto_verify_{}'.format(self.task_id), "pointid": pointid, "snapshot_time": snapshot_time, "kvm_cpu_count": int('{}{}'.format(kvm_cpu_sockets, kvm_cpu_cores)), "kvm_memory_size": schedule_ext_config_obj.get('kvm_memory_size', 1024), "kvm_memory_unit": schedule_ext_config_obj.get('kvm_memory_unit', 'MB').upper(), "kvm_storagedevice": auto_verify_task_obj.storage_node_ident, "kvm_adpter": [{ "name": "private_aio", "nic_name": None, "mac": kvm_mac, "ips": [] }], "kvm_route": [], "kvm_gateway": [""], "kvm_dns": [], "kvm_type": 'verify_kvm', 'kvm_pwd': ''.join(random.sample('0123456789', 6)), 'hddctl': _hardware_recommend['hddctl'], 'vga': _hardware_recommend['vga'], 'net': _hardware_recommend['net'], 'cpu': 'core2duo', 'boot_firmware': None, } api_response = TakeOverKVMCreate().post(request=None, api_request=api_request) if not status.is_success(api_response.status_code): self.task_content['error'] = get_response_error_string( api_response) self.log_error( 'CreateVerifyKvm TakeOverKVMCreate Failed.e={}'.format( self.task_content['error'])) takeover_id = int(api_response.data['id']) schedule_ext_config_obj['takeover_id'] = takeover_id schedule_ext_config_obj['stime'] = time.time() AutoVerifyTask.objects.filter(id=self.task_id).update( schedule_ext_config=json.dumps(schedule_ext_config_obj, ensure_ascii=False)) self.task_content['takeover_id'] = takeover_id api_request = {"id": takeover_id, "debug": 0} takeover_kvm_obj = TakeOverKVM.objects.get(id=takeover_id) flag_file = takeover_kvm_obj.kvm_flag_file self._save_kvm_run_info(flag_file, 'msg', '已发送开机命令') api_response = TakeOverKVMExecute().post(request=None, api_request=api_request) if not status.is_success(api_response.status_code): self.task_content['error'] = get_response_error_string( api_response) self.log_error( 'CreateVerifyKvm TakeOverKVMCreate Failed.e={}'.format( self.task_content['error'])) self.task_content['ip'] = kvm_ip self.log_info('CreateVerifyKvm kvm_ip={}'.format(kvm_ip)) except Exception as e: self.task_content['error'] = e self.log_error('CreateVerifyKvm execute failed.e={}'.format(e)) return self.task_content
def execute(self, task_content, **kwargs): if TakeoverKVMEntrance.has_error(task_content): return task_content TakeOverKVMobj = TakeOverKVM.objects.get(id=self._id) if TakeOverKVMobj.kvm_type == 'verify_kvm': return task_content ext_info = json.loads(TakeOverKVMobj.ext_info) floppy_path = ext_info.get('floppy_path', None) if floppy_path and os.path.isfile(floppy_path): return task_content flp_path = TakeOverKVMobj.kvm_flag_file + '{}.flp'.format(self._id) if ext_info['logic'] == 'linux': if TakeOverKVMobj.kvm_type == 'forever_kvm': ext_info['floppy_path'] = flp_path TakeOverKVM.objects.filter(id=self._id).update( ext_info=json.dumps(ext_info, ensure_ascii=False)) return task_content else: info = dict() info['aio_ip'] = '{}{}'.format( GetDictionary(DataDictionary.DICT_TYPE_TAKEOVER_SEGMENT, 'SEGMENT', '172.29'), '.16.1') info['tunnel_ip'] = -1 info['tunnel_port'] = -1 info['SetIpInfo'] = list() info['aio_ini'] = self._get_ini_content(ext_info) info['SetRoute'] = ext_info['kvm_route'] kvm_adpters = ext_info['kvm_adpter'] for kvm_adpter in kvm_adpters: mtu = int( GetDictionary(DataDictionary.DICT_TYPE_AIO_NETWORK, 'aio_mtu', -1)) one_info = { "ip_mask_list": [], "gate_way": "", "mac": "", "name": "", "dns_list": [], 'mtu': mtu } if len(kvm_adpter['ips']) == 0: continue for ip in kvm_adpter['ips']: one_info['ip_mask_list'].append({ "ip": ip['ip'], "mask": ip["mask"], "ip_type": xdata.HTB_IP_TYPE_CONTROL }) for kvm_gateway in ext_info['kvm_gateway']: one_info['gate_way'] = kvm_gateway one_info['mac'] = kvm_adpter['mac'] one_info['name'] = kvm_adpter['name'] one_info['nic_name'] = kvm_adpter.get('nic_name', None) for dns in ext_info['kvm_dns']: one_info['dns_list'].append(dns) info['SetIpInfo'].append(one_info) adpterinfo_str = json.dumps(info, ensure_ascii=False) flag_string = r'7294847cc045474882a93ec99090797b' flag_raw_content = [ord(letter) for letter in flag_string] with open(flp_path, 'wb') as file_object: file_bytes = 1024 * 1024 * 20 # 20MB file_object.truncate(file_bytes) file_object.seek(1024 * 1024 * 10) file_object.write(bytearray(flag_raw_content)) file_object.write(bytearray(adpterinfo_str, 'utf-8')) ext_info['floppy_path'] = flp_path TakeOverKVM.objects.filter(id=self._id).update( ext_info=json.dumps(ext_info, ensure_ascii=False)) return task_content
def _open_kvm_params(self, mdisk_snapshots, flag_file_path): """ 获取起kvm的参数 :param host_snapshot: 主机快照 :return: """ params_file_name = '{}_takeover.json'.format(uuid.uuid4().hex) params = { "logic": 'linux', "system_type": 64, "vnc": None, "shutdown": False, 'tmp_qcow': '{}_tmp.qcow2'.format(flag_file_path), "cmd_list": [{ "cmd": r"/home/python3.6/bin/python3.6 /home/patch/linux_iso/scripts/add_share_restore_takeover.py " r"--kvmparams /home/{}".format(params_file_name), "work_dir": '/home/patch/linux_iso', "timeouts": None, "post_result_url": None, "post_result_params": None }], "write_new": { "src_path": "/dev/shm/{}".format(params_file_name), "dest_path": "/home/{}".format(params_file_name) } } disk_devices = list() for disk in mdisk_snapshots: if disk == 'boot_devices': disk_devices.append({ "disk_ident": mdisk_snapshots[disk][0]['disk_ident'], "boot_device": True, "device_profile": { "nbd": dict() } }) else: for data_device in mdisk_snapshots[disk]: disk_devices.append({ "disk_ident": data_device['disk_ident'], "boot_device": False, "device_profile": { "nbd": dict() } }) params['disk_devices'] = disk_devices params['aio_server_ip'] = '{}'.format('{}{}'.format( GetDictionary(DataDictionary.DICT_TYPE_TAKEOVER_SEGMENT, 'SEGMENT', '172.29'), '.16.2')) return params
def _get_ipconfigs(self, kvm_adpter, kvm_dns, kvm_gateway): ''' [{'hardwareConfig': '[{"LocationInformation": "@system32\\\\drivers\\\\pci.sys,#65536;PCI \\u603b\\u7ebf %1\\u3001\\u8bbe\\u5907 %2\\u3001\\u529f\\u80fd %3;(3,0,0)", "Address": 0, "ContainerID": "", "HardwareID": ["PCI\\\\VEN_15AD&DEV_07B0&SUBSYS_07B015AD&REV_01", "PCI\\\\VEN_15AD&DEV_07B0&SUBSYS_07B015AD", "PCI\\\\VEN_15AD&DEV_07B0&CC_020000", "PCI\\\\VEN_15AD&DEV_07B0&CC_0200"], "NameGUID": "{848F537B-D3A3-4FD7-9360-3F7098E5EDE5}", "UINumber": 160, "Service": "VMXNET3NDIS6", "Mac": "0050569508BB"}, {"LocationInformation": "@system32\\\\drivers\\\\pci.sys,#65536;PCI bus %1, device %2, function %3;(0,21,0)", "Address": 1376256, "ContainerID": "", "HardwareID": ["PCI\\\\VEN_15AD&DEV_07A0&SUBSYS_07A015AD&REV_01", "PCI\\\\VEN_15AD&DEV_07A0&SUBSYS_07A015AD", "PCI\\\\VEN_15AD&DEV_07A0&CC_060400", "PCI\\\\VEN_15AD&DEV_07A0&CC_0604"], "NameGUID": null, "UINumber": -1, "Service": "PCI", "Mac": "0050569508BB"}]', 'subnetMask': '255.255.0.0', 'nameServer': '172.16.1.1', 'multiInfos': '{"is_set": true, "is_to_self": false, "network_name": "", "ip_mask_pair": [{"Ip": "172.16.6.193", "Mask": "255.255.0.0"}, {"Ip": "172.16.6.194", "Mask": "255.255.0.0"}], "src_instance_id": "", "gate_way": "172.16.1.1", "dns_list": ["172.16.1.1", "172.16.1.2"], "target_nic": {"isConnected": true, "szDescription": "vmxnet3 Ethernet Adapter", "szNetType": "MIB_IF_TYPE_ETHERNET", "szDeviceInstanceID": "PCI\\\\VEN_15AD&DEV_07B0&SUBSYS_07B015AD&REV_01\\\\FF565000BB0895FE00", "szMacAddress": "0050569508BB", "szGuid": "{848F537B-D3A3-4FD7-9360-3F7098E5EDE5}"}}', 'gateway': '172.16.1.1', 'ipAddress': '172.16.6.193'}] ''' isConnected = True gateway = '' for gw in kvm_gateway: gateway = gw ipconfigs = list() for adpter in kvm_adpter: ip_mask_pair = list() ips = adpter['ips'] if len(ips) == 0: continue i = -1 for ip in ips: i = i + 1 if i == 0: ipAddress = ip['ip'] subnetMask = ip['mask'] ip_mask_pair.append({"Ip": ip['ip'], "Mask": ip['mask']}) nameServer = '' for dns in kvm_dns: nameServer = dns nic_name = adpter.get('nic_name', None) mtu = int( GetDictionary(DataDictionary.DICT_TYPE_AIO_NETWORK, 'aio_mtu', -1)) if adpter['name'] == 'my_private_aio': nic_name = 'ClerwareNetwork' ipconfig = { 'ipAddress': ipAddress, 'subnetMask': subnetMask, "gateway": gateway, 'nameServer': nameServer, 'hardwareConfig': json.dumps([{ 'Mac': xdata.standardize_mac_addr(adpter['mac']) }], ensure_ascii=False), 'multiInfos': json.dumps( { 'ip_mask_pair': ip_mask_pair, "target_nic": { "isConnected": isConnected }, "dns_list": kvm_dns, "gate_way": gateway, "name": nic_name, 'mtu': mtu }, ensure_ascii=False) } ipconfigs.append(ipconfig) isConnected = False return ipconfigs
def _get_running_max_count(): return int( GetDictionary(DataDictionary.DICT_TYPE_TASK_QUEUE_NUM, 'queue_num', xdata.DICT_TYPE_TASK_QUEUE_NUM_DEFAULT))