def guest_state_report_engine(self): """ Guest 状态上报引擎 """ guest_state_mapping = dict() while True: if Utils.exit_flag: msg = 'Thread guest_state_report_engine say bye-bye' print msg logger.info(msg=msg) return try: # 3 秒钟更新一次 time.sleep(config['engine_cycle_interval'] * 3) threads_status['guest_state_report_engine'] = { 'timestamp': ji.Common.ts() } self.refresh_dom_mapping() for uuid, dom in self.dom_mapping_by_uuid.items(): state = Guest.get_state(dom=dom) if uuid in guest_state_mapping and guest_state_mapping[ uuid] == state: continue guest_state_mapping[uuid] = state Guest.guest_state_report(dom=dom) except: log_emit.warn(traceback.format_exc())
def post(self): self.response.headers['Content-Type'] = 'text/html' first_name = cgi.escape(self.request.get('first-name')) last_name = cgi.escape(self.request.get('last-name')) email = cgi.escape(self.request.get('email')) guests = cgi.escape(self.request.get('guests')) country = cgi.escape(self.request.get('country')) message = cgi.escape(self.request.get('message')) template_values = { 'greetings': 'Hey' } g = db.GqlQuery("SELECT * FROM Guest WHERE email = :1", email) if g is not None: g = Guest(first_name=first_name, last_name=last_name, email = email, guests = guests, country = country, message = message) g.put() template_path = 'tmp/confirm.html' if 'es' in self.request.url: template_path = 'tmp/confirm-es.html' path = os.path.join(os.path.dirname(__file__), template_path) self.response.write(template.render(path, template_values))
def main(conn=None): parser = getParser() options = parser.parse_args() conn = libvirt.open(options.connect) if conn is None: print "There is some error opening connection to libvirt" sys.exit(1); # check if existing machine of same name exists vm = None try: vm = conn.lookupByName(options.name) except libvirt.libvirtError: pass if vm is not None: print "VM of same name exists already, destroying and recreating it again" if vm.ID() != -1: vm.destroy() vm.undefine() guest = Guest(conn, options) xml = guest.guestGetXML(options.boot, options.cdrom).replace('\n','') dom = conn.createXML(xml, 0) dom = conn.defineXML(xml) if not dom: print "Cannot create/define domain" sys.exit(1) return 0
def post(self): self.response.headers['Content-Type'] = 'text/html' first_name = cgi.escape(self.request.get('first-name')) last_name = cgi.escape(self.request.get('last-name')) email = cgi.escape(self.request.get('email')) guests = cgi.escape(self.request.get('guests')) country = cgi.escape(self.request.get('country')) message = cgi.escape(self.request.get('message')) template_values = {'greetings': 'Hey'} g = db.GqlQuery("SELECT * FROM Guest WHERE email = :1", email) if g is not None: g = Guest(first_name=first_name, last_name=last_name, email=email, guests=guests, country=country, message=message) g.put() template_path = 'tmp/confirm.html' if 'es' in self.request.url: template_path = 'tmp/confirm-es.html' path = os.path.join(os.path.dirname(__file__), template_path) self.response.write(template.render(path, template_values))
def test_guest_class_methods(self): # import pdb; pdb.set_trace() self.assertItemsEqual(Guest.all(), [guest_1, guest_2, guest_3]) self.assertItemsEqual([guest.name for guest in Guest.all()], [guest_1.name, guest_2.name, guest_3.name]) self.assertEqual(Guest.most_popular(), guest_1) self.assertEqual(Guest.toughest_critic(), guest_1) self.assertEqual(Guest.most_active_critic(), guest_1)
def refresh_guest_state(self): try: self.refresh_dom_mapping() for dom in self.dom_mapping_by_uuid.values(): Guest.guest_state_report(dom=dom) except: log_emit.warn(traceback.format_exc())
def refresh_guest_state(self): try: self.init_conn() self.refresh_guest_mapping() for guest in self.guest_mapping_by_uuid.values(): Guest.guest_state_report(guest) except: logger.error(traceback.format_exc()) log_emit.error(traceback.format_exc())
def test_balance_checker(): # BALANCE_ERROR : If user's balance is insufficient for room cost room = Room(1, 50, 1, None, None) new_guest = Guest('C', False, 1, 0, 10, date(2020, 9, 27), date(2020, 9, 28)) assert Room.is_available_for_customer(room, new_guest) == error.BALANCE_ERROR room = Room(1, 50, 1, None, None) new_guest = Guest('C', False, 1, 2, 70, date(2020, 9, 27), date(2020, 9, 28)) assert Room.is_available_for_customer(room, new_guest) == error.BALANCE_ERROR
def test_find_available_room_for_customer_func(): rooms = generate_rooms([1, 1, 1, 1, 1, 1]) new_guest = Guest('F', True, 3, 2, 1000, date(2020, 9, 27), date(2020, 9, 28)) assert find_available_room_for_customer(rooms, new_guest) == True assert new_guest.room_number == 2 new_guest1 = Guest('G', True, 3, 2, 1000, date(2020, 9, 27), date(2020, 9, 28)) assert find_available_room_for_customer(rooms, new_guest1) == error.HANDICAP_ERROR # After checkout, the third room should be empty checkout_guest(rooms, new_guest) assert rooms[2].checkin_date == None
def test_bed_checker(): # BED_ERROR : If the room doesn't have proper number of beds room = Room(1, 50, 1, date(2020, 9, 27), date(2020, 9, 28)) new_guest = Guest('E', False, 2, 2, 90, date(2020, 9, 29), date(2020, 9, 30)) assert Room.is_available_for_customer(room, new_guest) == error.BED_COUNT_ERROR
def test_occupation_checker(): # OCCUPATION_ERROR : If the room is already booked room = Room(1, 50, 1, date(2020, 9, 27), date(2020, 9, 28)) new_guest = Guest('D', False, 1, 2, 90, date(2020, 9, 28), date(2020, 9, 30)) assert Room.is_available_for_customer(room, new_guest) == error.OCCUPATION_ERROR
def test_handicap_checker(): # HANDICAP_ERROR : If level is 2 and guest is disabled room = Room(2, 50, 1, None, None) new_guest = Guest('B', True, 1, 2, 60, date(2020, 9, 27), date(2020, 9, 28)) assert Room.is_available_for_customer(room, new_guest) == error.HANDICAP_ERROR
def test_pay_checker(): # PET_CHECK : If the number of pets is more than 2 room = Room(1, 50, 1, None, None) new_guest = Guest('A', False, 1, 5, 60, date(2020, 9, 27), date(2020, 9, 28)) assert Room.is_available_for_customer(room, new_guest) == error.PET_CHECK_ERROR
def run_server(): """ Setting up server. Wait for connection from new clients, starts server_input thread and communication thread. Socket with context manager is used to close socket automatically when it finish it's job :return: None """ with soc.socket(soc.AF_INET, soc.SOCK_STREAM) as s: s.bind((HOST, PORT)) # set up server print("...server started...\n") Thread(target=server_input).start() # starting thread to get input from user to the server s.listen(10) # open server to listen for connections while True: try: conn, addr = s.accept() # wait for any for connections print("...new user connected...") conn.send("Please provide your name: ".encode()) # server to provide name for identification name = conn.recv(1024).decode() # first message received is always the persons name when_joined = strftime('%Y-%m-%d %H:%M:%S', gmtime()) """creates a new guest object and adds it to the list of guest """ list_of_guests.append(Guest(conn, addr, when_joined)) list_of_guests[-1].set_name(name) # sets the name for a new guest object """sending welcome message to every user on the server but the one that joined""" welcome = f"{list_of_guests[-1].get_name()} just joined! Time: {when_joined}\n" say_to_all(welcome, list_of_guests[-1].get_connection()) print(f"connection from: {addr[0]}, port: {addr[1]}. Hello {list_of_guests[-1].get_name()}" f". Time: {strftime('%Y-%m-%d %H:%M:%S', gmtime())}\n") Thread(target=communication, args=(list_of_guests[-1],)).start() # starts communication thread except Exception as e: print("Exception in server - run server: ", e)
def test_user_can_signup(self): guest = Guest() member = Member() librairian = Librarian() self.assertEqual(guest.id, 0) self.assertIsNotNone(member.id) self.assertIsNotNone(librairian.id)
def recognize_user(rfid_reader): print("start scanning") guests = Guest.get_guests() while True: uuid = rfid_reader.get_rfid_value() print("received uuid: ", uuid) for guest in guests: if uuid[0:11] == guest.get_uuid(): return guest
def main(): num_channel = int(raw_input("Quantidade de canais: ")) num_guests = int(raw_input("Quantidade de hospedes: ")) min_watch_time = int(raw_input("Tempo minimo para assistir: ")) max_watch_time = int(raw_input("Tempo maximo para assistir: ")) min_rest_time = int(raw_input("Tempo minimo de descanso: ")) max_rest_time = int(raw_input("Tempo maximo de descanso: ")) for i in range(num_guests): t = Guest(randint(1, num_channel), randint(min_watch_time, max_watch_time), randint(min_rest_time, max_rest_time)) t.start() Guest().start() print "Favorite channel: %s" %t.favorite_channel print "Rest time: %s" %t.rest_time print "Watch time: %s" %t.watch_time take_control = threading.Lock() mutex = threading.Lock() watching = 0 def watch_channel(): while True: mutex.acquire(True) watching += 1 if watching == 1: take_control.release(True) mutex.release() #seta_canal() watching -= 1 if watching == 0: take_control.release(True) mutex.release(True) #assiste_tv() def set_channel(): while True: take_control.acquire(True) #seta_canal() take_control.release(True)
def result(username): guests.update() registered = guests.is_exist(username) if registered: user = guests.get_guest(username) else: user = Guest(username, '') return render_template('result.html', registered=registered, user=user)
def post(self): ime = self.request.get("ime") priimek = self.request.get("priimek") email = self.request.get("email") sporocilo = self.request.get("sporocilo") if not ime: ime = "Neznanec" if not "<script>" in sporocilo: guest = Guest(ime=ime, priimek=priimek, email=email, sporocilo=sporocilo) guest.put() return self.redirect_to("main") else: sprocilo = "" return self.redirect_to("main")
def main(): # Create object of Hotel class obj_hotel = Hotel('MARRIOTT', '1 Amiryan Street, Yerevan 0010 Armenia', '+374-10-599000', 'www.marriott.com') # Create objects of Guest class obj_guest1 = Guest('Armen', 'Hakobian', '*****@*****.**', '091-333-402') obj_guest2 = Guest('Ani', 'Hakobian', '*****@*****.**', '077-587-578') # Create objects of Room class obj_room1 = Room(1, 'Yes', 'Yes', 'No') obj_room2 = Room(2, 'No', 'Yes', 'Yes') obj_room3 = Room(3, 'No', 'Yes', 'No') # Add rooms in Hotel obj_hotel.add_room(obj_room1) obj_hotel.add_room(obj_room2) obj_hotel.add_room(obj_room3) # Book rooms obj_hotel.book_room(obj_guest1) obj_hotel.book_room(obj_guest2) # Print hotel info obj_hotel.print_hotel_info() # Print all rooms info obj_hotel.print_all_rooms() # Print room info with a given number (ex. 2) obj_hotel.print_room_info(2) # Print guest info obj_guest1.get_info() # Print all booked rooms info obj_hotel.print_book_info() # or # Print a booked room info by room number obj_hotel.print_book_info(2)
def login(self): usr_input = self.ids.usr_input psw_input = self.ids.psw_input msg = Guest.login(usr_input.text, psw_input.text) if msg: MessagePopup(message=msg).open() usr_input.focus = True else: usr_input.text = '' psw_input.text = '' root = App.get_running_app().root # main screen manager root.transition = CardTransition(direction="up", mode="pop") root.current = "menu"
def show_guests(): """ Show guests that have RSVP'd. Add guests to RSVP list if method is POST. """ if request.method == "GET": return render_template("guests.html", guests=guest_list) elif request.method == "POST": name = request.form.get("name") email = request.form.get("email") plus_one = request.form.get("plus-one") phone = request.form.get("phone") guest_list.append(Guest(name, email, plus_one, phone)) return render_template("guests.html", guests=guest_list)
def get_booking_info(type): from database import Database from guest import Guest from reservations import Reservation from worker import Worker from hotel import Hotel try: if type == "Guest": return Guest() elif type == "Worker": return Worker() elif type == "Reservation": return Reservation() elif type == "Database": return Database() elif type == "Hotel": return Hotel() raise AssertionError("Part not found") except AssertionError as _e: print(_e)
def get_guest_menu(): print("LOGGED AS GUEST") print() guest_obj = Guest() print("1. View products") print("2. Register") print("3. Exit") opt = int(input("Enter the corresponding number : ")) while opt != 3: if opt == 1: view_products(guest_obj) elif opt == 2: get_register_menu() break elif opt != 3: print("Invalid option! Try again") print("LOGGED AS GUEST") print() print("1. View products") print("2. Register") print("3. Exit") opt = int(input("Enter the corresponding number : "))
class TestHasManyThroughMiniProj(unittest.TestCase): global guest_1 guest_1 = Guest("Dwight Schrute") global guest_2 guest_2 = Guest("Michael Scott") global guest_3 guest_3 = Guest("Pam Beasley") global dinner_party_1 dinner_party_1 = DinnerParty("Office Christmas Party") global dinner_party_2 dinner_party_2 = DinnerParty("Your parent's friend's") global dinner_party_3 dinner_party_3 = DinnerParty("Friend's House Warming") global invite_1 invite_1 = Invite(dinner_party_1, guest_1) global invite_2 invite_2 = Invite(dinner_party_1, guest_2) global invite_3 invite_3 = Invite(dinner_party_1, guest_3) global invite_4 invite_4 = Invite(dinner_party_2, guest_1) global invite_5 invite_5 = Invite(dinner_party_3, guest_1) global recipe_1 recipe_1 = Recipe("Disaster") global recipe_2 recipe_2 = Recipe("Punch") global recipe_3 recipe_3 = Recipe("Cookies") global recipe_4 recipe_4 = Recipe("Punch") global recipe_5 recipe_5 = Recipe("Cookies") global recipe_6 recipe_6 = Recipe("Punch") global course_1 course_1 = Course(dinner_party_1, recipe_1) global course_2 course_2 = Course(dinner_party_1, recipe_2) global course_3 course_3 = Course(dinner_party_1, recipe_3) global course_4 course_4 = Course(dinner_party_1, recipe_4) global course_5 course_5 = Course(dinner_party_2, recipe_5) global course_6 course_6 = Course(dinner_party_2, recipe_6) global course_7 course_7 = Course(dinner_party_2, recipe_2) global review_1 review_1 = Review(guest_1, recipe_1, 3, "the Disaster wasn't as bad as I would've liked") global review_2 review_2 = Review(guest_2, recipe_1, 5, "It was total chaos, exceeded expectations") global review_3 review_3 = Review(guest_3, recipe_1, 4, "Just disastrous, nothing more") global review_4 review_4 = Review(guest_1, recipe_2, 2, "way too much pineapple juice!") global review_5 review_5 = Review(guest_2, recipe_2, 2, "not enough pineapple juice!") global review_6 review_6 = Review( guest_3, recipe_2, 3, "right amount of pineapple juice, but wasn't anything to write home about" ) global review_7 review_7 = Review(guest_1, recipe_3, 2, "I don't like cookies, that's all.") global review_8 review_8 = Review(guest_2, recipe_1, 4, "Pretty disastrous, nothing more") global review_9 review_9 = Review(guest_3, recipe_1, 4, "Meh, I've seen more bedlam") global review_10 review_10 = Review(guest_1, recipe_4, 1, "It was more of a slap in the face") def test_guest_class_methods(self): self.assertItemsEqual(Guest.all(), [guest_1, guest_2, guest_3]) self.assertEqual(Guest.most_popular(), guest_1) self.assertEqual(Guest.toughest_critic(), guest_1) self.assertEqual(Guest.most_active_critic(), guest_1) def test_guest_instance_methods(self): self.assertEqual(guest_1.rsvp(invite_1, True), True) self.assertEqual(guest_1.number_of_invites(), 3) self.assertEqual( len( guest_1.review_recipe( recipe_1, 3, "The disaster just wasn't disastrous enough!")), 6) Review._all.pop() self.assertEqual(guest_1.favorite_recipe(), recipe_1) def test_invite_class_methods(self): self.assertItemsEqual( Invite._all, [invite_1, invite_2, invite_3, invite_4, invite_5]) self.assertItemsEqual( Invite.all(), [invite_1, invite_2, invite_3, invite_4, invite_5]) def test_invite_instance_methods(self): self.assertEqual(guest_1.rsvp(invite_1, True), True) self.assertEqual(invite_1.accepted, True) self.assertEqual(invite_1.dinner_party, dinner_party_1) def test_dinner_party_class_methods(self): self.assertItemsEqual(DinnerParty.all(), [dinner_party_1, dinner_party_2, dinner_party_3]) def test_dinner_party_instance_methods(self): self.assertItemsEqual(dinner_party_1.reviews(), [ review_1, review_2, review_3, review_4, review_5, review_6, review_7, review_8, review_9, review_10 ]) self.assertItemsEqual(dinner_party_1.recipes(), [recipe_1, recipe_2, recipe_3, recipe_4]) self.assertEqual(dinner_party_1.recipe_count(), 4) self.assertEqual(dinner_party_1.highest_rated_recipe(), recipe_1) invite_1.accepted = True invite_2.accepted = True invite_3.accepted = True self.assertEqual(dinner_party_1.number_of_attendees(), 3) def test_review_class_methods(self): self.assertItemsEqual(Review._all, [ review_1, review_2, review_3, review_4, review_5, review_6, review_7, review_8, review_9, review_10 ]) self.assertItemsEqual(Review.all(), [ review_1, review_2, review_3, review_4, review_5, review_6, review_7, review_8, review_9, review_10 ]) def test_review_instance_methods(self): self.assertEqual(review_1.rating, 3) self.assertEqual(review_1.reviewer, guest_1) self.assertEqual(review_1.recipe, recipe_1) self.assertEqual(review_1.comment, "the Disaster wasn't as bad as I would've liked") def test_recipe_class_methods(self): self.assertItemsEqual( Recipe.all(), [recipe_1, recipe_2, recipe_3, recipe_4, recipe_5, recipe_6]) self.assertItemsEqual(Recipe.top_three(), [recipe_1, recipe_2, recipe_3]) self.assertItemsEqual(Recipe.bottom_three(), [recipe_4, recipe_2, recipe_3]) def test_recipe_instance_methods(self): self.assertItemsEqual( recipe_1.top_five_reviews(), [review_1, review_2, review_8, review_3, review_9])
from room import Room from guest import Guest room_1 = Room(25) customer = Guest("Cher", 70, "Believe") room_1.check_in(customer) print(room_1.check_total_tab())
def guest_booting2running_report_engine(self): """ Guest 启动到运行状态上报 """ self.init_conn() list_booting_guest = list() def is_running(_guest): running = False try: exec_ret = libvirt_qemu.qemuAgentCommand(_guest, json.dumps({ 'execute': 'guest-ping', 'arguments': { } }), 3, libvirt_qemu.VIR_DOMAIN_QEMU_AGENT_COMMAND_NOWAIT) running = True except: logger.error(traceback.format_exc()) return running while True: if Utils.exit_flag: msg = 'Thread guest_booting2running_report_engine say bye-bye' print msg logger.info(msg=msg) return # noinspection PyBroadException try: try: payload = q_booting_guest.get(timeout=config['engine_cycle_interval']) list_booting_guest.append(payload) q_booting_guest.task_done() except Queue.Empty as e: time.sleep(config['engine_cycle_interval']) threads_status['guest_booting2running_report_engine'] = dict() threads_status['guest_booting2running_report_engine']['timestamp'] = ji.Common.ts() for i, uuid in enumerate(list_booting_guest): guest = self.conn.lookupByUUIDString(uuidstr=uuid) log = u' '.join([u'域', guest.name(), u', UUID', uuid, u'的状态改变为']) if guest is not None and guest.isActive() and is_running(_guest=guest): log += u' Running。' guest_event_emit.running(uuid=uuid) logger.info(log) log_emit.info(log) else: time.sleep(config['engine_cycle_interval']) Guest.guest_state_report(guest=guest) del list_booting_guest[i] except: logger.error(traceback.format_exc()) log_emit.error(traceback.format_exc())
def guest_creating_progress_report_engine(): """ Guest 创建进度上报引擎 """ list_creating_guest = list() template_size = dict() while True: if Utils.exit_flag: msg = 'Thread guest_creating_progress_report_engine say bye-bye' print msg logger.info(msg=msg) return # noinspection PyBroadException try: try: payload = q_creating_guest.get(timeout=config['engine_cycle_interval']) list_creating_guest.append(payload) q_creating_guest.task_done() except Queue.Empty as e: pass threads_status['guest_creating_progress_report_engine'] = dict() threads_status['guest_creating_progress_report_engine']['timestamp'] = ji.Common.ts() # 当有 Guest 被创建时,略微等待一下,避免复制模板的动作还没开始,就开始计算进度。这样会产生找不到镜像路径的异常。 time.sleep(1) for i, guest in enumerate(list_creating_guest): template_path = guest['template_path'] progress = 0 if guest['storage_mode'] in [StorageMode.ceph.value, StorageMode.glusterfs.value]: if guest['storage_mode'] == StorageMode.glusterfs.value: if template_path not in template_size: Guest.dfs_volume = guest['dfs_volume'] Guest.init_gfapi() template_size[template_path] = float(Guest.gf.getsize(template_path)) system_image_size = Guest.gf.getsize(guest['system_image_path']) progress = system_image_size / template_size[template_path] elif guest['storage_mode'] in [StorageMode.local.value, StorageMode.shared_mount.value]: if template_path not in template_size: template_size[template_path] = float(os.path.getsize(template_path)) system_image_size = os.path.getsize(guest['system_image_path']) progress = system_image_size / template_size[template_path] else: del list_creating_guest[i] log = u' '.join([u'UUID: ', guest['uuid'], u'未支持的存储模式: ', str(guest['storage_mode'])]) logger.error(log) log_emit.error(log) guest_event_emit.creating(uuid=guest['uuid'], progress=int(progress * 90)) if progress >= 1: del list_creating_guest[i] except: logger.error(traceback.format_exc()) log_emit.error(traceback.format_exc())
def instruction_process_engine(self): self.init_conn() ps = r.pubsub(ignore_subscribe_messages=False) ps.subscribe(config['instruction_channel']) while True: if Utils.exit_flag: msg = 'Thread instruction_process_engine say bye-bye' print msg logger.info(msg=msg) return threads_status['instruction_process_engine'] = dict() threads_status['instruction_process_engine']['timestamp'] = ji.Common.ts() # noinspection PyBroadException try: msg = ps.get_message(timeout=config['engine_cycle_interval']) if msg is None or 'data' not in msg or not isinstance(msg['data'], basestring): continue try: msg = json.loads(msg['data']) if msg['action'] == 'pong': continue if msg['action'] == 'ping': # 通过 ping pong 来刷存在感。因为经过实际测试发现,当订阅频道长时间没有数据来往,那么订阅者会被自动退出。 r.publish(config['instruction_channel'], message=json.dumps({'action': 'pong'})) continue except ValueError as e: logger.error(e.message) log_emit.error(e.message) continue if 'node_id' in msg and int(msg['node_id']) != self.node_id: continue # 下列语句繁琐写法如 <code>if 'action' not in msg or 'uuid' not in msg:</code> if not all([key in msg for key in ['_object', 'action']]): continue extend_data = dict() if msg['_object'] == 'guest': self.refresh_guest_mapping() if msg['action'] not in ['create']: if msg['uuid'] not in self.guest_mapping_by_uuid: if config['DEBUG']: _log = u' '.join([u'uuid', msg['uuid'], u'在计算节点', self.hostname, u'中未找到.']) logger.debug(_log) log_emit.debug(_log) raise RuntimeError('The uuid ' + msg['uuid'] + ' not found in current domains list.') self.guest = self.guest_mapping_by_uuid[msg['uuid']] if not isinstance(self.guest, libvirt.virDomain): raise RuntimeError('Guest ' + msg['uuid'] + ' is not a domain.') if msg['action'] == 'create': t = threading.Thread(target=Guest.create, args=(self.conn, msg)) t.setDaemon(False) t.start() continue elif msg['action'] == 'reboot': if self.guest.reboot() != 0: raise RuntimeError('Guest reboot failure.') elif msg['action'] == 'force_reboot': self.guest.destroy() self.guest.create() Guest.quota(guest=self.guest, msg=msg) elif msg['action'] == 'shutdown': if self.guest.shutdown() != 0: raise RuntimeError('Guest shutdown failure.') elif msg['action'] == 'force_shutdown': if self.guest.destroy() != 0: raise RuntimeError('Guest force shutdown failure.') elif msg['action'] == 'boot': if not self.guest.isActive(): if self.guest.create() != 0: raise RuntimeError('Guest boot failure.') Guest.quota(guest=self.guest, msg=msg) elif msg['action'] == 'suspend': if self.guest.suspend() != 0: raise RuntimeError('Guest suspend failure.') elif msg['action'] == 'resume': if self.guest.resume() != 0: raise RuntimeError('Guest resume failure.') elif msg['action'] == 'delete': root = ET.fromstring(self.guest.XMLDesc()) if self.guest.isActive(): self.guest.destroy() self.guest.undefine() system_disk = None for _disk in root.findall('devices/disk'): if 'vda' == _disk.find('target').get('dev'): system_disk = _disk if msg['storage_mode'] in [StorageMode.ceph.value, StorageMode.glusterfs.value]: # 签出系统镜像路径 path_list = system_disk.find('source').attrib['name'].split('/') if msg['storage_mode'] == StorageMode.glusterfs.value: Guest.dfs_volume = path_list[0] Guest.init_gfapi() try: Guest.gf.remove('/'.join(path_list[1:])) except OSError: pass elif msg['storage_mode'] in [StorageMode.local.value, StorageMode.shared_mount.value]: file_path = system_disk.find('source').attrib['file'] try: os.remove(file_path) except OSError: pass elif msg['action'] == 'reset_password': if self.guest.setUserPassword(msg['user'], msg['password']) != 0: raise RuntimeError('Guest reset password failure.') elif msg['action'] == 'attach_disk': if 'xml' not in msg: _log = u'添加磁盘缺少 xml 参数' raise KeyError(_log) flags = libvirt.VIR_DOMAIN_AFFECT_CONFIG if self.guest.isActive(): flags |= libvirt.VIR_DOMAIN_AFFECT_LIVE # 添加磁盘成功返回时,ret值为0。可参考 Linux 命令返回值规范? if self.guest.attachDeviceFlags(xml=msg['xml'], flags=flags) != 0: raise RuntimeError('Attack disk failure.') Guest.quota(guest=self.guest, msg=msg) elif msg['action'] == 'detach_disk': if 'xml' not in msg: _log = u'分离磁盘缺少 xml 参数' raise KeyError(_log) flags = libvirt.VIR_DOMAIN_AFFECT_CONFIG if self.guest.isActive(): flags |= libvirt.VIR_DOMAIN_AFFECT_LIVE if self.guest.detachDeviceFlags(xml=msg['xml'], flags=flags) != 0: raise RuntimeError('Detach disk failure.') elif msg['action'] == 'update_ssh_key': if not self.guest.isActive(): _log = u'欲更新 SSH-KEY 的目标虚拟机未处于活动状态。' logger.warning(_log) log_emit.warn(_log) continue ret = Guest.update_ssh_key(guest=self.guest, msg=msg) logger.info(json.dumps(ret, ensure_ascii=False)) elif msg['action'] == 'allocate_bandwidth': t = threading.Thread(target=Guest.allocate_bandwidth, args=(self.guest, msg)) t.setDaemon(False) t.start() continue elif msg['action'] == 'adjust_ability': t = threading.Thread(target=Guest.adjust_ability, args=(self.conn, self.guest, msg)) t.setDaemon(False) t.start() continue elif msg['action'] == 'migrate': # duri like qemu+ssh://destination_host/system if 'duri' not in msg: _log = u'迁移操作缺少 duri 参数' raise KeyError(_log) # https://rk4n.github.io/2016/08/10/qemu-post-copy-and-auto-converge-features/ flags = libvirt.VIR_MIGRATE_PERSIST_DEST | \ libvirt.VIR_MIGRATE_UNDEFINE_SOURCE | \ libvirt.VIR_MIGRATE_COMPRESSED | \ libvirt.VIR_MIGRATE_PEER2PEER | \ libvirt.VIR_MIGRATE_AUTO_CONVERGE root = ET.fromstring(self.guest.XMLDesc()) if msg['storage_mode'] == StorageMode.local.value: # 需要把磁盘存放路径加入到两边宿主机的存储池中 # 不然将会报 no storage pool with matching target path '/opt/Images' 错误 flags |= libvirt.VIR_MIGRATE_NON_SHARED_DISK flags |= libvirt.VIR_MIGRATE_LIVE if not self.guest.isActive(): _log = u'非共享存储不支持离线迁移。' logger.error(_log) log_emit.error(_log) raise RuntimeError('Nonsupport online migrate with storage of non sharing mode.') if self.init_ssh_client(hostname=msg['duri'].split('/')[2], user='******'): for _disk in root.findall('devices/disk'): _file_path = _disk.find('source').get('file') disk_info = Disk.disk_info_by_local(image_path=_file_path) disk_size = disk_info['virtual-size'] stdin, stdout, stderr = self.ssh_client.exec_command( ' '.join(['qemu-img', 'create', '-f', 'qcow2', _file_path, str(disk_size)])) for line in stdout: logger.info(line) log_emit.info(line) for line in stderr: logger.error(line) log_emit.error(line) elif msg['storage_mode'] in [StorageMode.shared_mount.value, StorageMode.ceph.value, StorageMode.glusterfs.value]: if self.guest.isActive(): flags |= libvirt.VIR_MIGRATE_LIVE flags |= libvirt.VIR_MIGRATE_TUNNELLED else: flags |= libvirt.VIR_MIGRATE_OFFLINE if self.guest.migrateToURI(duri=msg['duri'], flags=flags) == 0: if msg['storage_mode'] == StorageMode.local.value: for _disk in root.findall('devices/disk'): _file_path = _disk.find('source').get('file') if _file_path is not None: os.remove(_file_path) else: raise RuntimeError('Unknown storage mode.') elif msg['_object'] == 'disk': if msg['action'] == 'create': if msg['storage_mode'] == StorageMode.glusterfs.value: Guest.dfs_volume = msg['dfs_volume'] Guest.init_gfapi() if not Disk.make_qemu_image_by_glusterfs(gf=Guest.gf, dfs_volume=msg['dfs_volume'], image_path=msg['image_path'], size=msg['size']): raise RuntimeError('Create disk failure with glusterfs.') elif msg['storage_mode'] in [StorageMode.local.value, StorageMode.shared_mount.value]: if not Disk.make_qemu_image_by_local(image_path=msg['image_path'], size=msg['size']): raise RuntimeError('Create disk failure with local storage mode.') elif msg['action'] == 'delete': if msg['storage_mode'] == StorageMode.glusterfs.value: Guest.dfs_volume = msg['dfs_volume'] Guest.init_gfapi() if Disk.delete_qemu_image_by_glusterfs(gf=Guest.gf, image_path=msg['image_path']) \ is not None: raise RuntimeError('Delete disk failure with glusterfs.') elif msg['storage_mode'] in [StorageMode.local.value, StorageMode.shared_mount.value]: if Disk.delete_qemu_image_by_local(image_path=msg['image_path']) is not None: raise RuntimeError('Delete disk failure with local storage mode.') elif msg['action'] == 'resize': if 'size' not in msg: _log = u'添加磁盘缺少 disk 或 disk["size"] 参数' raise KeyError(_log) used = False if msg['guest_uuid'].__len__() == 36: used = True if used: self.refresh_guest_mapping() if msg['guest_uuid'] not in self.guest_mapping_by_uuid: if config['DEBUG']: _log = u' '.join([u'uuid', msg['uuid'], u'在计算节点', self.hostname, u'中未找到.']) logger.debug(_log) log_emit.debug(_log) raise RuntimeError('Resize disk failure, because the uuid ' + msg['guest_uuid'] + ' not found in current domains.') self.guest = self.guest_mapping_by_uuid[msg['guest_uuid']] if not isinstance(self.guest, libvirt.virDomain): raise RuntimeError('Resize disk failure, because the guest is not a domain.') # 在线磁盘扩容 if used and self.guest.isActive(): if 'device_node' not in msg: _log = u'添加磁盘缺少 disk 或 disk["device_node|size"] 参数' raise KeyError(_log) # 磁盘大小默认单位为KB,乘以两个 1024,使其单位达到GB msg['size'] = int(msg['size']) * 1024 * 1024 if self.guest.blockResize(disk=msg['device_node'], size=msg['size']) != 0: raise RuntimeError('Online resize disk failure in blockResize method.') Guest.quota(guest=self.guest, msg=msg) # 离线磁盘扩容 else: if not all([key in msg for key in ['storage_mode', 'dfs_volume', 'image_path']]): _log = u'添加磁盘缺少 disk 或 disk["storage_mode|dfs_volume|image_path|size"] 参数' raise KeyError(_log) if msg['storage_mode'] == StorageMode.glusterfs.value: if not Disk.resize_qemu_image_by_glusterfs(dfs_volume=msg['dfs_volume'], image_path=msg['image_path'], size=msg['size']): raise RuntimeError('Offline resize disk failure with glusterfs.') elif msg['storage_mode'] in [StorageMode.local.value, StorageMode.shared_mount.value]: if not Disk.resize_qemu_image_by_local(image_path=msg['image_path'], size=msg['size']): raise RuntimeError('Offline resize disk failure with local storage mode.') elif msg['action'] == 'quota': self.refresh_guest_mapping() if msg['guest_uuid'] not in self.guest_mapping_by_uuid: if config['DEBUG']: _log = u' '.join([u'uuid', msg['guest_uuid'], u'在计算节点', self.hostname, u'中未找到.']) logger.debug(_log) log_emit.debug(_log) raise RuntimeError('Disk quota failure, because the uuid ' + msg['guest_uuid'] + ' not found in current domains.') self.guest = self.guest_mapping_by_uuid[msg['guest_uuid']] if not isinstance(self.guest, libvirt.virDomain): raise RuntimeError('Disk quota failure, because the guest is not a domain.') if not self.guest.isActive(): _log = u'磁盘 ' + msg['uuid'] + u' 所属虚拟机未处于活动状态。' logger.warning(_log) log_emit.warn(_log) continue Guest.quota(guest=self.guest, msg=msg) elif msg['_object'] == 'snapshot': self.refresh_guest_mapping() if msg['uuid'] not in self.guest_mapping_by_uuid: if config['DEBUG']: _log = u' '.join([u'uuid', msg['uuid'], u'在计算节点', self.hostname, u'中未找到.']) logger.debug(_log) log_emit.debug(_log) raise RuntimeError('Snapshot ' + msg['action'] + ' failure, because the uuid ' + msg['uuid'] + ' not found in current domains.') self.guest = self.guest_mapping_by_uuid[msg['uuid']] if not isinstance(self.guest, libvirt.virDomain): raise RuntimeError('Snapshot ' + msg['action'] + ' failure, because the guest is not a domain.') if msg['action'] == 'create': t = threading.Thread(target=Guest.create_snapshot, args=(self.guest, msg)) t.setDaemon(False) t.start() continue elif msg['action'] == 'delete': t = threading.Thread(target=Guest.delete_snapshot, args=(self.guest, msg)) t.setDaemon(False) t.start() continue elif msg['action'] == 'revert': t = threading.Thread(target=Guest.revert_snapshot, args=(self.guest, msg)) t.setDaemon(False) t.start() continue elif msg['action'] == 'convert': t = threading.Thread(target=Guest.convert_snapshot, args=(msg,)) t.setDaemon(False) t.start() continue elif msg['_object'] == 'os_template_image': if msg['action'] == 'delete': if msg['storage_mode'] == StorageMode.glusterfs.value: Guest.dfs_volume = msg['dfs_volume'] Guest.init_gfapi() try: Guest.gf.remove(msg['template_path']) except OSError: pass elif msg['storage_mode'] in [StorageMode.local.value, StorageMode.shared_mount.value]: try: os.remove(msg['template_path']) except OSError: pass elif msg['_object'] == 'global': if msg['action'] == 'refresh_guest_state': host_use_for_refresh_guest_state = Host() t = threading.Thread(target=host_use_for_refresh_guest_state.refresh_guest_state, args=()) t.setDaemon(False) t.start() continue else: _log = u'未支持的 _object:' + msg['_object'] logger.error(_log) log_emit.error(_log) response_emit.success(_object=msg['_object'], action=msg['action'], uuid=msg['uuid'], data=extend_data, passback_parameters=msg.get('passback_parameters')) except redis.exceptions.ConnectionError as e: logger.error(traceback.format_exc()) # 防止循环线程,在redis连接断开时,混水写入日志 time.sleep(5) except: # 防止循环线程,在redis连接断开时,混水写入日志 time.sleep(5) logger.error(traceback.format_exc()) log_emit.error(traceback.format_exc()) response_emit.failure(_object=msg['_object'], action=msg.get('action'), uuid=msg.get('uuid'), passback_parameters=msg.get('passback_parameters'))
def test_guest_class_methods(self): self.assertItemsEqual(Guest.all(), [guest_1, guest_2, guest_3]) self.assertEqual(Guest.most_popular(), guest_1) self.assertEqual(Guest.toughest_critic(), guest_1) self.assertEqual(Guest.most_active_critic(), guest_1)
def get(self): seznam = Guest.query().fetch() params = {"seznam": seznam} return self.render_template("seznam-sporocil.html", params=params)
## Trying filename open / closing, IO, loops and classes ## Eric Menzie 9/8/19 ## Hotel game from guest import Guest from roomservice import RoomService filename = 'hotelguests.txt' the_guest = Guest('') call_roomservice = RoomService('') the_guest.welcome() with open(filename, 'a') as file_object: while True: a_guest = input('What is your, and your guest' 's, names? (Enter "q" if finished): ') if a_guest == 'q': break else: file_object.write(a_guest + "\n") print(f'Welcome {a_guest}!') the_guest.greet_guests() call_roomservice.offerDrinks()