def check_sub_id(self, subscription_id): azure_key = AzureKey.objects(subscription_id=subscription_id).first() if self.util.is_local(): if azure_key is not None: azure_key.verified = True azure_key.save() return ok("success") if azure_key is None: return internal_server_error( "No available azure key on the server side.") sms = CloudServiceAdapter(azure_key.subscription_id, azure_key.get_local_pem_url(), host=azure_key.management_host) if sms.ping(): azure_key.verified = True azure_key.save() else: return bad_request( "Subscription id is not valid, check whether subscription id is valid and upload the right cer file to azure" ) return ok("success")
def hackathon_online(self, hackathon): req = ok() if hackathon.status == HACK_STATUS.DRAFT or hackathon.status == HACK_STATUS.OFFLINE or hackathon.status == HACK_STATUS.APPLY_ONLINE: if self.util.is_local() or hackathon.config.get( 'cloud_provider') == CLOUD_PROVIDER.NONE: req = ok() elif hackathon.config.get( 'cloud_provider') == CLOUD_PROVIDER.AZURE: is_success = docker_host_manager.check_subscription_id( hackathon.id) if not is_success: req = general_error(code=HTTP_CODE.AZURE_KEY_NOT_READY ) # azure sub id is invalide elif hackathon.status == HACK_STATUS.ONLINE: req = ok() else: req = general_error(code=HTTP_CODE.CREATE_NOT_FINISHED) if req.get('error') is None: hackathon.status = HACK_STATUS.ONLINE hackathon.save() self.create_hackathon_notice( hackathon.id, HACK_NOTICE_EVENT.HACK_ONLINE, HACK_NOTICE_CATEGORY.HACKATHON) # hackathon online return req
def update_team_member_status(self, operator, user_team_rel_id, status): """ update user's status on selected team. if current user doesn't have permission, return bad request. Else, update user's status :type status: int :param status: the status of the team member, see TeamMemberStatus in constants.py :rtype: bool :return: if update success, return ok. if not , return bad request. """ rel = self.db.find_first_object_by(UserTeamRel, id=user_team_rel_id) if not rel: return not_found() team = rel.team self.__validate_team_permission(rel.hackathon_id, team, operator) if rel.user_id == team.leader_id: return precondition_failed("cannot update status of team leader") if status == TeamMemberStatus.Approved: # disable previous team first self.db.delete_all_objects_by(UserTeamRel, hackathon_id=rel.hackathon_id, user_id=rel.user_id, status=TeamMemberStatus.Approved) self.db.delete_all_objects_by(Team, hackathon_id=rel.hackathon_id, leader_id=rel.user_id) rel.status = TeamMemberStatus.Approved rel.update_time = self.util.get_now() self.db.commit() return ok("approved") if status == TeamMemberStatus.Denied: self.db.delete_object(rel) return ok("Your request has been denied, please rejoin another team.")
def check_sub_id(self, subscription_id): azure_key = AzureKey.objects(subscription_id=subscription_id).first() if self.util.is_local(): if azure_key is not None: azure_key.verified = True azure_key.save() return ok(True) if azure_key is None: return ok(False) try: sms = CloudServiceAdapter(azure_key.subscription_id, azure_key.get_local_pem_url(), host=azure_key.management_host) sms.list_hosted_services() azure_key.verified = True azure_key.save() except Exception as e: return ok(False) return ok(True)
def send_email_azure(self, kwargs): # team information team = self.__get_team_by_id(kwargs["id"]) if not team: return not_found("team not exists") azure = team.azure if not azure.strip(): if Azure.objects(status="0").count() == 0: return ok("请联系管理员.") azure_info = Azure.objects(status="0").first() else: azure_info = Azure.objects(account=azure).first() if not azure_info: return ok("请联系管理员!") primary_emails = [] for i in xrange(0, len(team.members)): mem = team.members[i] resp = self.user_manager.user_display_info(mem.user) primary_emails.append(resp['emails'][0]['email']) Azure.objects(account=azure_info.account).update_one(status="1") Team.objects(id=team.id).update_one(azure=azure_info.account) sender = '' email_title = '' email_content = '' return self.util.send_emails(sender, primary_emails, email_title, email_content)
def check_notice_and_set_read_if_necessary(self, id): hackathon_notice = HackathonNotice.objects(id=id).first() if hackathon_notice: user = g.user if not user or user.id != hackathon_notice.receiver.id: # not the user return ok() hackathon_notice.is_read = True if hackathon_notice.event == HACK_NOTICE_EVENT.HACK_PLAN: # set is_read = True if dev_plan is complete user = hackathon_notice.receiver hackathon = hackathon_notice.hackathon team = Team.objects(members__user=user, hackathon=hackathon).first() if team: if not team.dev_plan: # the dev_plan isn't submitted hackathon_notice.is_read = False elif hackathon.config.get( HACKATHON_CONFIG.REAL_NAME_AUTH_21V, False): self.create_hackathon_notice( hackathon.id, HACK_NOTICE_EVENT.HACK_REGISTER_AZURE, HACK_NOTICE_CATEGORY.HACKATHON, {'receiver': user}) hackathon_notice.save() return ok()
def quit_team_forcedly(self, team, user): """ The operator(admin or superadmin) forces a user(team leader or other members) to quit a team. If the user is the only member of the team, the team will be deleted. Else if the user is the leader of a team with several members, the team will be decomposed into several new teams. Else if the user is not the leader of a team with several members, just the user quits the team. :rtype: bool :return: if dismiss success, return ok. if not ,return bad request. """ # here we don't check whether the operator has the permission, if not team.members or len(team.members) == 0: self.log.warn("this team doesn't have any members") return ok() member_users = [m.user for m in team.members if m.status == TEAM_MEMBER_STATUS.APPROVED] num_team_members = len(member_users) hackathon = team.hackathon if num_team_members > 1: if team.leader == user: team.delete() for u in member_users: if u.id != user.id: self.create_default_team(hackathon, u) else: Team.objects(id=team.id).update_one(pull__members__user=user) else: # num_team_members == 1 team.delete() return ok()
def leave_team(self, hackathon_id, team_name): """Leave a team by user :type hackathon_id: int :param hid: hackathon id :type team_name: str|unicode :param team_name: team name :rtype: bool :return: if leave_team success, return ok. if not ,return bad request. """ team = self.__get_team_by_name(hackathon_id, team_name) if not team: # if team don't exist, do nothing return ok() # if user is not team leader if team.leader_id != g.user.id: self.db.delete_all_objects_by(UserTeamRel, hackathon_id=hackathon_id, user_id=g.user.id) return ok("You have left the team") # if user is team leader if len(self.__get_team_members(team)) >= 2: return precondition_failed( "Please promote a new team leader, before leave team.") else: return self.dismiss_team(hackathon_id, team_name)
def leave_team(self, hackathon_id, team_name): """Leave a team by user :type hackathon_id: int :param hid: hackathon id :type team_name: str|unicode :param team_name: team name :rtype: bool :return: if leave_team success, return ok. if not ,return bad request. """ team = self.__get_team_by_name(hackathon_id, team_name) if not team: # if team don't exist, do nothing return ok() # if user is not team leader if team.leader_id != g.user.id: self.db.delete_all_objects_by(UserTeamRel, hackathon_id=hackathon_id, user_id=g.user.id) return ok("You have left the team") # if user is team leader if len(self.__get_team_members(team)) >= 2: return precondition_failed("Please promote a new team leader, before leave team.") else: return self.dismiss_team(hackathon_id, team_name)
def delete_template(self, template_id): self.log.debug("delete template [%d]" % template_id) try: template = self.db.get_object(Template, template_id) if template is None: return ok("already removed") # user can only delete the template which created by himself except super admin if g.user.id != template.creator_id and not self.user_manager.is_super_admin( g.user): return forbidden() if len( self.db.find_all_objects_by(Experiment, template_id=template_id)) > 0: return forbidden("template already in use") # remove template cache and storage self.cache.invalidate(self.__get_template_cache_key(template_id)) self.storage.delete(template.url) # remove record in DB self.db.delete_all_objects_by(HackathonTemplateRel, template_id=template.id) self.db.delete_object(template) return ok("delete template success") except Exception as ex: self.log.error(ex) return internal_server_error("delete template failed")
def delete_registration(self, args): """ Delete the registration of a user in a hackathon, also do operation on the user's team. """ if "id" not in args: return bad_request("id not invalid") try: register = self.get_registration_by_id(args["id"]) if register is not None: register.delete() hackathon = register.hackathon self.__update_register_stat(hackathon) team = self.team_manager.get_team_by_user_and_hackathon( register.user, hackathon) if not team: self.log.warn("team of this registered user is not found!") return ok() self.team_manager.quit_team_forcedly(team, register.user) return ok() except Exception as ex: self.log.error(ex) return internal_server_error("failed in delete register: %s" % args["id"])
def send_email_azure(self, kwargs): # team information team = self.__get_team_by_id(kwargs["id"]) if not team: return not_found("team not exists") azure = team.azure if not azure.strip(): if Azure.objects(status="0").count() == 0: return ok("请联系管理员.") azure_info = Azure.objects(status="0").first() else: azure_info = Azure.objects(account=azure).first() if not azure_info: return ok("请联系管理员!") primary_emails = [] for i in range(0, len(team.members)): mem = team.members[i] resp = self.user_manager.user_display_info(mem.user) primary_emails.append(resp['emails'][0]['email']) Azure.objects(account=azure_info.account).update_one(status="1") Team.objects(id=team.id).update_one(azure=azure_info.account) sender = '' email_title = '' email_content = '' return self.util.send_emails(sender, primary_emails, email_title, email_content)
def stop_expr(self, expr_id, force=0): """ :param expr_id: experiment id :param force: 0: only stop container and release ports, 1: force stop and delete container and release ports. :return: """ self.log.debug("begin to stop %d" % expr_id) expr = self.db.find_first_object_by(Experiment, id=expr_id, status=EStatus.RUNNING) if expr is not None: # Docker docker = self.docker.get_docker(expr.hackathon) if expr.template.provider == VE_PROVIDER.DOCKER: # stop containers for c in expr.virtual_environments.all(): try: self.log.debug("begin to stop %s" % c.name) if force: docker.delete(c.name, virtual_environment=c, container=c.container, expr_id=expr_id) c.status = VEStatus.DELETED else: docker.stop(c.name, virtual_environment=c, container=c.container, expr_id=expr_id) c.status = VEStatus.STOPPED except Exception as e: self.log.error(e) self.__roll_back(expr_id) return internal_server_error( 'Failed stop/delete container') if force: expr.status = EStatus.DELETED else: expr.status = EStatus.STOPPED self.db.commit() else: try: # todo support delete azure vm azure_key_id = self.docker.load_azure_key_id(expr.id) context = Context(azure_key_id=azure_key_id, experiment_id=expr.id, action=AVMStatus.STOPPED_DEALLOCATED) self.azure_vm_service.stop_vm_entry(context) except Exception as e: self.log.error(e) return internal_server_error('Failed stopping azure') self.log.debug("experiment %d ended success" % expr_id) return ok('OK') else: return ok('expr not exist')
def stop_expr(self, expr_id, force=0): """ :param expr_id: experiment id :param force: 0: only stop container and release ports, 1: force stop and delete container and release ports. :return: """ self.log.debug("begin to stop %d" % expr_id) expr = self.db.find_first_object_by(Experiment, id=expr_id, status=EStatus.RUNNING) if expr is not None: # Docker if expr.template.provider == VE_PROVIDER.DOCKER: # stop containers for c in expr.virtual_environments.all(): try: self.log.debug("begin to stop %s" % c.name) docker = self.__get_docker(expr.hackathon, c) if force: docker.delete(c.name, virtual_environment=c, container=c.container, expr_id=expr_id) c.status = VEStatus.DELETED else: docker.stop(c.name, virtual_environment=c, container=c.container, expr_id=expr_id) c.status = VEStatus.STOPPED except Exception as e: self.log.error(e) self.__roll_back(expr_id) return internal_server_error('Failed stop/delete container') if force: expr.status = EStatus.DELETED else: expr.status = EStatus.STOPPED self.db.commit() else: try: # todo support delete azure vm # hosted_docker = RequiredFeature("hosted_docker") # af = AzureFormation(hosted_docker.load_azure_key_id(expr_id)) # af.stop(expr_id, AVMStatus.STOPPED_DEALLOCATED) template = self.db.get_object(Template, expr.template_id) template_content = self.template_library.load_template(template) azure_keys = self.azure_cert_manager.get_certificates_by_expr(expr_id) # TODO: which key to use azure_key = azure_keys[0] # TODO: elimate virtual_environments arg and expr_id arg self.azure_formation.stop_vm( expr_id, azure_key, template_content.units, expr.virtual_environments.all(), expr_id) except Exception as e: self.log.error(e) return internal_server_error('Failed stopping azure') self.log.debug("experiment %d ended success" % expr_id) return ok('OK') else: return ok()
def stop_expr(self, expr_id): """ :param expr_id: experiment id :return: """ self.log.debug("begin to stop %s" % str(expr_id)) expr = Experiment.objects(id=expr_id, status=EStatus.RUNNING).first() if expr is not None: starter = self.get_starter(expr.hackathon, expr.template) if starter: starter.stop_expr(Context(experiment_id=expr.id, experiment=expr)) self.log.debug("experiment %s ended success" % expr_id) return ok('OK') else: return ok()
def stop_expr(self, expr_id): """ :param expr_id: experiment id :return: """ self.log.debug("begin to stop %s" % str(expr_id)) expr = Experiment.objects(id=expr_id).first() if expr is not None: starter = self.get_starter(expr.hackathon, expr.template) if starter: starter.stop_expr(Context(experiment_id=expr.id, experiment=expr)) self.log.debug("experiment %s ended success" % expr_id) return ok('OK') else: return ok()
def delete_certificate(self, certificate_id, hackathon): """Delete certificate by azureKey.id and hackathon Delete the hackathon-azureKey relationship first. If the auzreKey is not needed any more, delete the azureKey too :type certificate_id: int :param certificate_id: id of AzureKey :type hackathon: Hackathon :param hackathon: instance of Hackathon """ # delete all hackathon-azureKey relationships first azure_key = AzureKey.objects(id=certificate_id).first() # if no relations left, delete the azureKey itself if azure_key in hackathon.azure_keys: try: if isfile(azure_key.cert_url): os.remove(azure_key.cert_url) else: self.storage.delete(azure_key.cert_url) if isfile(azure_key.pem_url): os.remove(azure_key.pem_url) else: self.storage.delete(azure_key.pem_url) except Exception as e: self.log.error(e) hackathon.azure_keys.remove(azure_key) hackathon.save() return ok(True)
def add_admin(self, args): """Add a new administrator on a hackathon :type args: dict :param args: http request body in json format :return hackathon response 'ok' if successfully added. 'not_found' if email is invalid or user not found. 'internal_server_error' if any other unexpected exception caught """ user = self.user_manager.get_user_by_email(args.get("email")) if user is None: return not_found("user not found") try: ahl = self.db.find_first_object(AdminHackathonRel, AdminHackathonRel.user_id == user.id, AdminHackathonRel.hackathon_id == g.hackathon.id) if ahl is None: ahl = AdminHackathonRel( user_id=user.id, role_type=args.get("role_type", ADMIN_ROLE_TYPE.ADMIN), hackathon_id=g.hackathon.id, remarks=args.get("remarks"), create_time=self.util.get_now() ) self.db.add_object(ahl) return ok() except Exception as e: self.log.error(e) return internal_server_error("create admin failed")
def update_hackathon(self, args): """Update hackathon properties :type args: dict :param args: arguments from http request body that contains properties with new values :rtype dict :return hackathon in dict if updated successfully. """ hackathon = g.hackathon try: update_items = self.__parse_update_items(args, hackathon) self.log.debug("update hackathon items :" + str(args.keys())) if 'config' in update_items: self.set_basic_property(hackathon, update_items.get('config', {})) update_items.pop('config', None) if 'status' in update_items and int(update_items['status']) == HACK_STATUS.ONLINE: self.create_hackathon_notice(hackathon.id, HACK_NOTICE_EVENT.HACK_ONLINE, HACK_NOTICE_CATEGORY.HACKATHON) # hackathon online # basic xss prevention if 'description' in update_items and update_items['description']: update_items['description'] = self.cleaner.clean_html(update_items['description']) self.log.debug("hackathon description :" + update_items['description']) hackathon.modify(**update_items) hackathon.save() return ok() except Exception as e: self.log.error(e) return internal_server_error("fail to update hackathon")
def test_delete_registration_not_found(self): db_adapter = Mock() db_adapter.find_first_object_by.return_value = None rm = RegisterManager(db_adapter) args = {'id': 1} self.assertEqual(rm.delete_registration(args), ok()) db_adapter.find_first_object_by.assert_called_once_with(UserHackathonRel, id == 1)
def create_host_server(self, hackathon_id, args): """ create a docker host DB object for a hackathon and insert record into the database. param-"args" contain all necessary infos to new a docker_host :param hackathon_id: the id of hackathon in DB :type hackathon_id: Integer :return: return True if succeed, otherwise return False :rtype: bool """ host_server = DockerHostServer(vm_name=args.vm_name, public_dns=args.public_dns, public_ip=args.public_ip, public_docker_api_port=args.public_docker_api_port, private_ip=args.private_ip, private_docker_api_port=args.private_docker_api_port, container_count=0, container_max_count=args.container_max_count, is_auto=AzureVMStartMethod.MANUAL, disabled=args.disabled, create_time=self.util.get_now(), update_time=self.util.get_now(), hackathon_id=hackathon_id) if self.hosted_docker.ping(host_server, 5): host_server.state = DockerHostServerStatus.DOCKER_READY else: host_server.state = DockerHostServerStatus.UNAVAILABLE self.db.add_object(host_server) return ok()
def update_admin(self, args): """Update hackathon admin :returns ok() if updated successfully bad_request() if "id" not in request body not_found() if specific AdminHackathonRel not found internal_server_error() if DB exception raised """ user_hackathon_id = args.get("id", None) if not user_hackathon_id: return bad_request("invalid user_hackathon_id") user_hackathon = UserHackathon.objects(id=user_hackathon_id).first() if not user_hackathon: return not_found("admin does not exist") try: user_hackathon.update_time = self.util.get_now() if 'role' in args: user_hackathon.role = args['role'] if 'remark' in args: user_hackathon.remark = args['remark'] user_hackathon.save() return ok('update hackathon admin successfully') except Exception as e: self.log.error(e) return internal_server_error(e)
def delete_certificate(self, certificate_id, hackathon): """Delete certificate by azureKey.id and hackathon Delete the hackathon-azureKey relationship first. If the auzreKey is not needed any more, delete the azureKey too :type certificate_id: int :param certificate_id: id of AzureKey :type hackathon: Hackathon :param hackathon: instance of Hackathon """ # delete all hackathon-azureKey relationships first self.db.delete_all_objects_by(HackathonAzureKey, hackathon_id=hackathon.id, azure_key_id=certificate_id) # if no relations left, delete the azureKey itself if self.db.count_by(HackathonAzureKey, azure_key_id=certificate_id) == 0: azure_key = self.db.get_object(AzureKey, certificate_id) if azure_key: try: if isfile(azure_key.cert_url): os.remove(azure_key.cert_url) else: self.storage.delete(azure_key.cert_url) except Exception as e: self.log.error(e) self.db.delete_all_objects_by(AzureKey, id=certificate_id) self.db.commit() return ok()
def add_admin(self, args): """Add a new administrator on a hackathon :type args: dict :param args: http request body in json format :return hackathon response 'ok' if successfully added. 'not_found' if email is invalid or user not found. 'internal_server_error' if any other unexpected exception caught """ user = self.user_manager.get_user_by_email(args.get("email")) if user is None: return not_found("user not found") try: ahl = self.db.find_first_object( AdminHackathonRel, AdminHackathonRel.user_id == user.id, AdminHackathonRel.hackathon_id == g.hackathon.id) if ahl is None: ahl = AdminHackathonRel(user_id=user.id, role_type=args.get( "role_type", ADMIN_ROLE_TYPE.ADMIN), hackathon_id=g.hackathon.id, remarks=args.get("remarks"), create_time=self.util.get_now()) self.db.add_object(ahl) return ok() except Exception as e: self.log.error(e) return internal_server_error("create admin failed")
def join_team(self, user, team_id): """Join a team will create a record on user_team_rel table which status will be 0. :type user: User :param user: the user to join a team :rtype: dict :return: if user already joined team or team not exist, return bad request. Else, return a dict of joined details. """ if self.db.find_first_object_by(UserTeamRel, user_id=user.id, team_id=team_id): return ok("You already joined this team.") team = self.__get_team_by_id(team_id) if not team: return not_found() cur_team = self.__get_valid_team_by_user(user.id, team.hackathon_id) if cur_team and cur_team.team.user_team_rels.count() > 1: return precondition_failed("Team leader cannot join another team for team member count greater than 1") if not self.register_manager.is_user_registered(user.id, team.hackathon): return precondition_failed("user not registerd") candidate = UserTeamRel(join_time=self.util.get_now(), update_time=self.util.get_now(), status=TeamMemberStatus.Init, hackathon_id=team.hackathon.id, user_id=user.id, team_id=team.id) self.db.add_object(candidate) return candidate.dic()
def delete_template_from_hackathon(self, template_id, team_id=-1): self.db.delete_all_objects_by(HackathonTemplateRel, template_id=template_id, hackathon_id=g.hackathon.id, team_id=team_id) # self.db.delete_object(htr) return ok()
def update_hackathon(self, args): """Update hackathon properties :type args: dict :param args: arguments from http request body that contains properties with new values :rtype dict :return hackathon in dict if updated successfully. """ hackathon = g.hackathon try: update_items = self.__parse_update_items(args, hackathon) self.log.debug("update hackathon items :" + str(args.keys())) if 'config' in update_items: self.set_basic_property(hackathon, update_items.get('config', {})) update_items.pop('config', None) # basic xss prevention if 'description' in update_items and update_items['description']: #update_items['description'] = self.cleaner.clean_html(update_items['description']) self.log.debug("hackathon description :" + update_items['description']) hackathon.modify(**update_items) hackathon.save() return ok() except Exception as e: self.log.error(e) return internal_server_error("fail to update hackathon")
def kick_or_leave(self, operator, team_id, user_id): try: team = Team.objects(id=team_id, members__user=user_id).first() except ValidationError: return not_found() if not team: return not_found() mem = filter(lambda x: str(x.user.id) == user_id, team.members) assert len(mem) < 2 if not mem: return not_found() mem = mem[0] hackathon = team.hackathon user = mem.user if str(team.leader.id) == user_id: # if the user to be leaved or kicked is team leader return precondition_failed("leader cannot leave team") if str(operator.id) == user_id: # leave team team.members.remove(mem) team.save() self.create_default_team(hackathon, user) else: # kick somebody else self.__validate_team_permission(hackathon.id, team, operator) team.members.remove(mem) team.save() self.create_default_team(hackathon, user) return ok()
def stop_expr(self, expr_id): """ :param expr_id: experiment id :param force: 0: only stop container and release ports, 1: force stop and delete container and release ports. :return: """ self.log.debug("begin to stop %d" % expr_id) expr = Experiment.objects(id=expr_id, status=EStatus.RUNNING) if expr is not None: starter = self.get_starter(expr.hackathon, expr.template) if starter: starter.stop_expr(Context(experiment=expr)) self.log.debug("experiment %d ended success" % expr_id) return ok('OK') else: return ok()
def delete_hackathon_organizer(self, hackathon, organizer_id): if hackathon.organizers.filter(id=organizer_id): hackathon.update(pull__organizers=hackathon.organizers.get(id=organizer_id)) hackathon.update_time = self.util.get_now() hackathon.save() return ok()
def delete_hackathon_notice(self, notice_id): hackathon_notice = HackathonNotice.objects(id=notice_id).first() if not hackathon_notice: return not_found('Hackathon notice not found') hackathon_notice.delete() return ok()
def join_team(self, user, team_id): """Join a team will create a record on user_team_rel table which status will be 0. :type user: User :rtype: dict :return: if user already joined team or team not exist, return bad request. Else, return a dict of joined details. """ if Team.objects(id=team_id, members__user=user.id).count(): return ok("You already joined this team.") team = self.__get_team_by_id(team_id) if not team: return not_found() cur_team = self.__get_valid_team_by_user(user.id, team.hackathon.id) if cur_team and cur_team.members.count() > 1: return precondition_failed( "Team leader cannot join another team for team member count greater than 1" ) if not self.register_manager.is_user_registered( user.id, team.hackathon): return precondition_failed("user not registerd") mem = TeamMember(join_time=self.util.get_now(), status=TEAM_MEMBER_STATUS.INIT, user=user) team.members.append(mem) team.save() return to_dic(mem)
def join_team(self, user, team_id): """Join a team will create a record on user_team_rel table which status will be 0. :type user: User :rtype: dict :return: if user already joined team or team not exist, return bad request. Else, return a dict of joined details. """ if Team.objects(id=team_id, members__user=user.id).count(): return ok("You already joined this team.") team = self.__get_team_by_id(team_id) if not team: return not_found() cur_team = self.__get_valid_team_by_user(user.id, team.hackathon.id) if cur_team and cur_team.members.count() > 1: return precondition_failed("Team leader cannot join another team for team member count greater than 1") if not self.register_manager.is_user_registered(user.id, team.hackathon): return precondition_failed("user not registerd") mem = TeamMember( join_time=self.util.get_now(), status=TEAM_MEMBER_STATUS.INIT, user=user) team.members.append(mem) team.save() return to_dic(mem)
def kick_or_leave(self, operator, team_id, user_id): try: team = Team.objects(id=team_id, members__user=user_id).first() except ValidationError: return not_found() if not team: return not_found() mem = [x for x in team.members if str(x.user.id) == user_id] assert len(mem) < 2 if not mem: return not_found() mem = mem[0] hackathon = team.hackathon user = mem.user if str( team.leader.id ) == user_id: # if the user to be leaved or kicked is team leader return precondition_failed("leader cannot leave team") if str(operator.id) == user_id: # leave team team.members.remove(mem) team.save() self.create_default_team(hackathon, user) else: # kick somebody else self.__validate_team_permission(hackathon.id, team, operator) team.members.remove(mem) team.save() self.create_default_team(hackathon, user) return ok()
def stop_expr(self, expr_id, force=0): """ :param expr_id: experiment id :param force: 0: only stop container and release ports, 1: force stop and delete container and release ports. :return: """ self.log.debug("begin to stop %d" % expr_id) expr = self.db.find_first_object_by(Experiment, id=expr_id, status=EStatus.RUNNING) if expr is not None: # Docker docker = self.docker.get_docker(expr.hackathon) if expr.template.provider == VE_PROVIDER.DOCKER: # stop containers for c in expr.virtual_environments.all(): try: self.log.debug("begin to stop %s" % c.name) if force: docker.delete(c.name, virtual_environment=c, container=c.container, expr_id=expr_id) c.status = VEStatus.DELETED else: docker.stop(c.name, virtual_environment=c, container=c.container, expr_id=expr_id) c.status = VEStatus.STOPPED except Exception as e: self.log.error(e) self.__roll_back(expr_id) return internal_server_error('Failed stop/delete container') if force: expr.status = EStatus.DELETED else: expr.status = EStatus.STOPPED self.db.commit() else: try: # todo support delete azure vm azure_key_id = self.docker.load_azure_key_id(expr.id) context = Context(azure_key_id=azure_key_id, experiment_id=expr.id, action=AVMStatus.STOPPED_DEALLOCATED) self.azure_vm_service.stop_vm_entry(context) except Exception as e: self.log.error(e) return internal_server_error('Failed stopping azure') self.log.debug("experiment %d ended success" % expr_id) return ok('OK') else: return ok('expr not exist')
def set_basic_property(self, hackathon, properties): """Set basic property in table HackathonConfig""" hackathon.config.update(properties) hackathon.save() self.cache.invalidate(self.__get_config_cache_key(hackathon)) return ok()
def unlike_hackathon(self, user, hackathon): self.db.delete_all_objects_by(HackathonLike, user_id=user.id, hackathon_id=hackathon.id) self.db.commit() # sync the like count like_count = self.db.count_by(HackathonLike, hackathon_id=hackathon.id) self.update_hackathon_stat(hackathon, HACKATHON_STAT.LIKE, like_count) return ok()
def delete_hackathon_organizer(self, hackathon, organizer_id): if hackathon.organizers.filter(id=organizer_id): hackathon.update(pull__organizers=hackathon.organizers.get( id=organizer_id)) hackathon.update_time = self.util.get_now() hackathon.save() return ok()
def test_delete_registration_not_found(self): db_adapter = Mock() db_adapter.find_first_object_by.return_value = None rm = RegisterManager(db_adapter) args = {'id': 1} self.assertEqual(rm.delete_registration(args), ok()) db_adapter.find_first_object_by.assert_called_once_with( UserHackathonRel, id == 1)
def delete_team_show(self, user, show_id): show = self.db.find_first_object_by(TeamShow, id=show_id) if show: self.__validate_team_permission(show.team.hackathon_id, show.team, user) self.db.delete_object(show) self.db.commit() return ok()
def heart_beat(self, expr_id): expr = self.db.find_first_object_by(Experiment, id=expr_id, status=EStatus.RUNNING) if expr is None: return not_found('Experiment is not running') expr.last_heart_beat_time = self.util.get_now() self.db.commit() return ok()
def heart_beat(self, expr_id): expr = Experiment.objects(id=expr_id, status=EStatus.RUNNING).first() if expr is None: return not_found('Experiment is not running') expr.last_heart_beat_time = self.util.get_now() expr.save() return ok()
def stop_expr(self, expr_id, force=0): """ :param expr_id: experiment id :param force: 0: only stop container and release ports, 1: force stop and delete container and release ports. :return: """ self.log.debug("begin to stop %d" % expr_id) expr = self.db.find_first_object_by(Experiment, id=expr_id, status=EStatus.RUNNING) if expr is not None: # Docker if expr.template.provider == VE_PROVIDER.DOCKER: # stop containers for c in expr.virtual_environments.all(): try: self.log.debug("begin to stop %s" % c.name) docker = self.__get_docker(expr.hackathon, c) if force: docker.delete(c.name, virtual_environment=c, container=c.container, expr_id=expr_id) c.status = VEStatus.DELETED else: docker.stop(c.name, virtual_environment=c, container=c.container, expr_id=expr_id) c.status = VEStatus.STOPPED except Exception as e: self.log.error(e) self.__roll_back(expr_id) return internal_server_error("Failed stop/delete container") if force: expr.status = EStatus.DELETED else: expr.status = EStatus.STOPPED self.db.commit() else: try: # todo support delete azure vm hosted_docker = RequiredFeature("hosted_docker") af = AzureFormation(hosted_docker.load_azure_key_id(expr_id)) af.stop(expr_id, AVMStatus.STOPPED_DEALLOCATED) except Exception as e: self.log.error(e) return internal_server_error("Failed stopping azure") self.log.debug("experiment %d ended success" % expr_id) return ok("OK") else: return ok()
def test_validate_deleted_args_already_missed(self): db_adapter = Mock() db_adapter.find_first_object.return_value = None am = AdminManager(db_adapter) status, return_info = am.validate_deleted_args(1) self.assertFalse(status) self.assertEqual(return_info, ok()) db_adapter.find_first_object(AdminHackathonRel, ANY)
def check_notice_and_set_read_if_necessary(self, id): hackathon_notice = HackathonNotice.objects(id=id).first() if hackathon_notice: user = g.user if not user or user.id != hackathon_notice.receiver.id: # not the user return ok() hackathon_notice.is_read = True if hackathon_notice.event == HACK_NOTICE_EVENT.HACK_PLAN: # set is_read = True if dev_plan is complete user = hackathon_notice.receiver hackathon = hackathon_notice.hackathon team = Team.objects(members__user=user, hackathon=hackathon).first() if team: if not team.dev_plan: # the dev_plan isn't submitted hackathon_notice.is_read = False hackathon_notice.save() return ok()
def delete_basic_property(self, hackathon, keys): if isinstance(keys, str): keys = keys.split() map(lambda key: hackathon.config.pop(key, None), keys) hackathon.save() self.cache.invalidate(self.__get_config_cache_key(hackathon)) return ok()
def delete_admin(self, user_hackathon_id): """Delete admin on a hackathon creator of the hackathon cannot be deleted. :returns ok() if succeeds or it's deleted before. precondition_failed if try to delete the creator """ user_hackathon = UserHackathon.objects(id=user_hackathon_id).first() if not user_hackathon: return ok() hackathon = user_hackathon.hackathon if hackathon and hackathon.creator == user_hackathon.user: return precondition_failed("hackathon creator can not be deleted") user_hackathon.delete() return ok()
def set_basic_property(self, hackathon, properties): """Set basic property in table HackathonConfig""" if isinstance(properties, list): map(lambda p: self.__set_basic_property(hackathon, p), properties) else: self.__set_basic_property(hackathon, properties) self.cache.invalidate(self.__get_config_cache_key(hackathon)) return ok()