def get_instance(self, id): url = self.api_endpoint + 'services/{0}/{1}/instances/{2}'.format(self.namespace, self.name, id) r = requests.get(url, headers=self.headers) util.check_response(r) data = json.loads(r.text) instance = Instance(service=self, uuid=data['uuid'], details=r.text) return instance
def _check_image_tag(self, repo_name, namespace, image_tag): print ('[alauda] Checking if the image tag is valid') url = ( self.api_endpoint + 'repositories/{}/{}'.format(namespace, repo_name) ) response = requests.get(url, headers=self.headers) util.check_response(response) data = json.loads(response.text) tags = [ item['docker_repo_tag'] for item in data['build_config']['tag_configs'] ] if not image_tag and len(tags) == 1: print ('[alauda] using {} as the image tag.'.format(tags[0])) image_tag = tags[0] elif not image_tag and len(tags) > 1: raise AlaudaInputError( 'please specify an image tag using -t, here is the ' 'tag list for your repo: {}'.format(tags) ) elif image_tag and image_tag not in tags: raise AlaudaInputError( '"{}" is not a valid tag, here is the tag list for your repo: ' '{}'.format(image_tag, tags) ) return image_tag
def _check_image_tag(self, repo_name, namespace, image_tag): print('[alauda] Checking if the image tag is valid') url = (self.api_endpoint + 'repositories/{}/{}'.format(namespace, repo_name)) response = requests.get(url, headers=self.headers) util.check_response(response) data = json.loads(response.text) tags = [ item['docker_repo_tag'] for item in data['build_config']['tag_configs'] ] if not image_tag and len(tags) == 1: print('[alauda] using {} as the image tag.'.format(tags[0])) image_tag = tags[0] elif not image_tag and len(tags) > 1: raise AlaudaInputError( 'please specify an image tag using -t, here is the ' 'tag list for your repo: {}'.format(tags)) elif image_tag and image_tag not in tags: raise AlaudaInputError( '"{}" is not a valid tag, here is the tag list for your repo: ' '{}'.format(image_tag, tags)) return image_tag
def inspect(self): if not self.details: url = self.api_endpoint + 'services/{}/'.format(self.namespace) + self.name r = requests.get(url, headers=self.headers) util.check_response(r) self.details = r.text return self.details
def get_exec_endpoint(namespace, container): try: _, _, username = auth.load_token() if namespace != username: verbose("use default exec endpoint: {0}".format(DEFAULT_EXEC_ENDPOINT)) return DEFAULT_EXEC_ENDPOINT except: verbose("use default exec endpoint: {0}".format(DEFAULT_EXEC_ENDPOINT)) return DEFAULT_EXEC_ENDPOINT service_name, _ = parse_container_arg(container) verbose("service name: {0}".format(service_name)) try: exec_endpoint = load_exec_endpoint(service_name) except: api_endpoint, token, username = auth.load_token() url = api_endpoint + "/services/{0}/{1}".format(namespace, service_name) headers = auth.build_headers(token) r = requests.get(url, headers=headers) util.check_response(r) data = json.loads(r.text) exec_endpoint = data["exec_endpoint"] save_exec_endpoint(service_name, exec_endpoint) return exec_endpoint
def get(self): url = "{}applications/{}/{}/".format(self.api_endpoint, self.namespace, self.name) r = requests.get(url=url, headers=self.headers) util.check_response(r) services = json.loads(r.text) services = services["services"] return services
def _check_repo_type(self, repo_name, namespace): print ("[alauda] Checking the repository's type") url = ( self.api_endpoint + 'repositories/{}/{}'.format(namespace, repo_name) ) response = requests.get(url, headers=self.headers) util.check_response(response) data = json.loads(response.text) if not data['is_automated']: raise AlaudaInputError( '{} is not an automated buid repo.'.format(repo_name) ) if data['build_config']['code_repo_client'] == 'FileUpload': print ( "[alauda] The repository's client type you specified " "is FileUpload" ) return settings.BUILD_REPO_TYPE['file'] else: print ( "[alauda] The repository's client type you specified " "is {}".format(data['build_config']['code_repo_client']) ) return settings.BUILD_REPO_TYPE['code_repo']
def get(self): url = '{}applications/{}/{}/'.format(self.api_endpoint, self.namespace, self.name) r = requests.get(url=url, headers=self.headers) util.check_response(r) services = json.loads(r.text) services = services['services'] return services
def stop(self): print '[alauda] Stopping service "{}"'.format(self.name) self.target_state = 'STOPPED' url = self.api_endpoint + 'services/{}/'.format( self.namespace) + self.name + '/stop/' r = requests.put(url, headers=self.headers) util.check_response(r)
def logs(self, start_time, end_time): start, end = util.parse_time(start_time, end_time) url = self.api_endpoint + 'services/{0}/{1}/logs?start_time={2}&end_time={3}'.format( self.namespace, self.name, start, end) r = requests.get(url, headers=self.headers) util.check_response(r) return r.text
def _create_remote(self, target_state): linked_to = self._update_envvars_with_links(self.instance_envvars, self.links, self.namespace) util.expand_environment(self.instance_envvars) url = self.api_endpoint + 'services/{}/'.format(self.namespace) payload = { "app_name": self.name, "target_num_instances": self.target_num_instances, "image_name": self.image_name, "image_tag": self.image_tag, "instance_size": self.instance_size, "scaling_mode": "MANUAL", "target_state": target_state, "run_command": self.run_command, "instance_envvars": self.instance_envvars, "instance_ports": self.instance_ports, 'linked_to_apps': linked_to, "volumes": self.volumes, 'scaling_mode': self.scaling_mode, 'autoscaling_config': self.autoscaling_config, 'custom_domain_name': self.custom_domain_name } if self.region_name: payload['region_name'] = self.region_name r = requests.post(url, headers=self.headers, data=json.dumps(payload)) util.check_response(r)
def inspect(self): if not self.details: url = self.api_endpoint + 'services/{}/'.format( self.namespace) + self.name r = requests.get(url, headers=self.headers) util.check_response(r) self.details = r.text return self.details
def get_instance(self, id): url = self.api_endpoint + 'services/{0}/{1}/instances/{2}'.format( self.namespace, self.name, id) r = requests.get(url, headers=self.headers) util.check_response(r) data = json.loads(r.text) instance = Instance(service=self, uuid=data['uuid'], details=r.text) return instance
def fetch(cls, id, namespace=None): api_endpoint, token, username = auth.load_token() url = api_endpoint + 'backups/{0}/{1}/'.format(namespace or username, id) headers = auth.build_headers(token) r = requests.get(url, headers=headers) util.check_response(r) data = json.loads(r.text) backup = cls(name=data['name'], details=r.text) return backup
def fetch(cls, name): api_endpoint, token, _ = auth.load_token() headers = auth.build_headers(token) url = api_endpoint + 'orgs/{}/'.format(name) r = requests.get(url, headers=headers) util.check_response(r) result = json.loads(r.text) organization = cls(result['name'], result['company'], r.text) return organization
def update(self, company): api_endpoint, token, _ = auth.load_token() headers = auth.build_headers(token) url = api_endpoint + 'orgs/{}/'.format(self.name) payload = { 'company': company } r = requests.put(url, headers=headers, data=json.dumps(payload)) util.check_response(r)
def create(self): api_endpoint, token, _ = auth.load_token() headers = auth.build_headers(token) url = api_endpoint + 'orgs/' payload = { 'name': self.name, 'company': self.company } r = requests.post(url, headers=headers, data=json.dumps(payload)) util.check_response(r)
def _get_upload_auth_info(self, target_path): print('[alauda] Applying to upload auth info.') with open(target_path, 'rb') as data: fingerprint = hashlib.sha256(data.read()).hexdigest() params = {'action': 's3_upload', 'fingerprint': fingerprint} url = self.api_endpoint + 'cloud-storage/aws/auth' response = requests.get(url, headers=self.headers, params=params) util.check_response(response) data = json.loads(response.text) return data['auth_headers'], data['bucket'], data['object_key']
def list_instances(self): url = self.api_endpoint + 'services/{0}/{1}/instances/'.format(self.namespace, self.name) r = requests.get(url, headers=self.headers) util.check_response(r) data = json.loads(r.text) instance_list = [] for instance in data: instance = Instance(service=self, uuid=instance['uuid'], details=json.dumps(instance)) instance_list.append(instance) return instance_list
def logs(self, start_time, end_time): start, end = util.parse_time(start_time, end_time) api_endpoint, token, _ = auth.load_token() url = api_endpoint + 'services/{0}/{1}/instances/{2}/logs?start_time={3}&end_time={4}'.format(self.service.namespace, self.service.name, self.uuid, start, end) headers = auth.build_headers(token) r = requests.get(url, headers=headers) util.check_response(r) return r.text
def scale(self, target_num_instances): self.target_num_instances = target_num_instances print '[alauda] Scaling service: {0} -> {1}'.format(self.name, self.target_num_instances) url = self.api_endpoint + 'services/{}/'.format(self.namespace) + self.name payload = { "app_name": self.name, "target_num_instances": self.target_num_instances, } r = requests.put(url, headers=self.headers, data=json.dumps(payload)) util.check_response(r)
def enable_autoscaling(self, autoscaling_config): print '[alauda] Enabling auto-scaling for {0}'.format(self.name) url = self.api_endpoint + 'services/{}/'.format(self.namespace) + self.name payload = { "scaling_mode": 'AUTO', "autoscaling_config": autoscaling_config, 'app_name': self.name } r = requests.put(url, headers=self.headers, data=json.dumps(payload)) util.check_response(r)
def _upload(self, target_path, upload_auth_headers, upload_bucket, upload_object_key): print('[alauda] Uploading {} to {}'.format(target_path, upload_object_key)) with open(target_path, 'rb') as data: response = requests.put('http://{}/{}/{}'.format( upload_auth_headers['Host'], upload_bucket, upload_object_key), data=data, headers=upload_auth_headers) util.check_response(response)
def enable_autoscaling(self, autoscaling_config): print '[alauda] Enabling auto-scaling for {0}'.format(self.name) url = self.api_endpoint + 'services/{}/'.format( self.namespace) + self.name payload = { "scaling_mode": 'AUTO', "autoscaling_config": autoscaling_config, 'app_name': self.name } r = requests.put(url, headers=self.headers, data=json.dumps(payload)) util.check_response(r)
def create(self): print '[alauda] Creating backup "{}"'.format(self.name) url = self.service.api_endpoint + 'backups/{}/'.format(self.service.namespace) data = json.loads(self.service.details) payload = { 'app_id': data['unique_name'], 'name': self.name, 'app_volume_dir': self.mounted_dir } r = requests.post(url, headers=self.service.headers, data=json.dumps(payload)) util.check_response(r)
def disable_autoscaling(self, target_num_instances): if target_num_instances is not None: self.target_num_instances = target_num_instances print '[alauda] Disabling auto-scaling for {0}. Target number of instances: {1}'.format(self.name, self.target_num_instances) url = self.api_endpoint + 'services/{}/'.format(self.namespace) + self.name payload = { "app_name": self.name, "target_num_instances": self.target_num_instances, 'scaling_mode': 'MANUAL' } r = requests.put(url, headers=self.headers, data=json.dumps(payload)) util.check_response(r)
def list(cls, namespace=None): api_endpoint, token, username = auth.load_token() url = api_endpoint + 'backups/{}/'.format(namespace or username) headers = auth.build_headers(token) r = requests.get(url, headers=headers) util.check_response(r) backups = json.loads(r.text) backup_list = [] for data in backups: backup = Backup.fetch(data['backup_id'], namespace) backup_list.append(backup) return backup_list
def scale(self, target_num_instances): self.target_num_instances = target_num_instances print '[alauda] Scaling service: {0} -> {1}'.format( self.name, self.target_num_instances) url = self.api_endpoint + 'services/{}/'.format( self.namespace) + self.name payload = { "app_name": self.name, "target_num_instances": self.target_num_instances, } r = requests.put(url, headers=self.headers, data=json.dumps(payload)) util.check_response(r)
def remove(cls, id, namespace=None): api_endpoint, token, username = auth.load_token() url = api_endpoint + 'backups/{0}/{1}/'.format(namespace or username, id) headers = auth.build_headers(token) r = requests.delete(url, headers=headers) try: util.check_response(r) except AlaudaServerError as ex: if ex.status_code == 400: print '[alauda] backup "{}" does not exist'.format(id) else: raise ex
def create(self): try: app_info = self.load_app_file(self.file) self.remove_extend_keyword(app_info) files = {"services": ("{}.yml".format(self.name), json.dumps(app_info))} except: files = "" url = "{}applications/{}/".format(self.api_endpoint, self.namespace) data = {"app_name": self.name, "region": self.region, "namespace": self.namespace} print self.headers r = requests.request("POST", url, headers=self.headers, data=data, files=files) util.check_response(r)
def create(self): try: app_info = self.load_app_file(self.file) self.remove_extend_keyword(app_info) files = {'services': ('{}.yml'.format(self.name), json.dumps(app_info))} except: files = '' url = '{}applications/{}/'.format(self.api_endpoint, self.namespace) data = {'app_name': self.name, 'region': self.region, 'namespace': self.namespace} print self.headers r = requests.request("POST", url, headers=self.headers, data=data, files=files) util.check_response(r)
def remove(cls, name, namespace=None): print '[alauda] Removing service "{}"'.format(name) api_endpoint, token, username = auth.load_token() url = api_endpoint + 'services/{}/'.format(namespace or username) + name headers = auth.build_headers(token) try: r = requests.delete(url, headers=headers) util.check_response(r) except AlaudaServerError as ex: if ex.status_code == 404: print '[alauda] Service "{}" does not exist'.format(name) else: raise ex
def search(session, text): r = session.get("https://vk.com/feed?q=%s§ion=search" % urllib.quote(text.encode('utf-8'))) check_response(r) posts = [] soup = BeautifulSoup(r.text, "lxml") soup.prettify() for post_html in soup.find_all("div", {"class":"post_table"}): post = Post(post_html) posts.append(post) return posts
def list_instances(self): url = self.api_endpoint + 'services/{0}/{1}/instances/'.format( self.namespace, self.name) r = requests.get(url, headers=self.headers) util.check_response(r) data = json.loads(r.text) instance_list = [] for instance in data: instance = Instance(service=self, uuid=instance['uuid'], details=json.dumps(instance)) instance_list.append(instance) return instance_list
def _get_upload_auth_info(self, target_path): print ('[alauda] Applying to upload auth info.') with open(target_path, 'rb') as data: fingerprint = hashlib.sha256(data.read()).hexdigest() params = { 'action': 's3_upload', 'fingerprint': fingerprint } url = self.api_endpoint + 'cloud-storage/aws/auth' response = requests.get(url, headers=self.headers, params=params) util.check_response(response) data = json.loads(response.text) return data['auth_headers'], data['bucket'], data['object_key']
def list(cls): api_endpoint, token, _ = auth.load_token() headers = auth.build_headers(token) url = api_endpoint + 'orgs/' r = requests.get(url, headers=headers) util.check_response(r) organization_list = [] if r.text: organizations = json.loads(r.text) for data in organizations: organization = Organization.fetch(data['name']) organization_list.append(organization) return organization_list
def fetch(cls, name, namespace=None): service_name = name.split(".")[0] api_endpoint, token, username = auth.load_token() url = api_endpoint + 'services/{}/'.format(namespace or username) + service_name headers = auth.build_headers(token) r = requests.get(url, headers=headers) util.check_response(r) data = json.loads(r.text) executer = cls(name=name, username=username, exec_endpoint=data['exec_endpoint'], namespace=data['namespace']) return executer
def disable_autoscaling(self, target_num_instances): if target_num_instances is not None: self.target_num_instances = target_num_instances print '[alauda] Disabling auto-scaling for {0}. Target number of instances: {1}'.format( self.name, self.target_num_instances) url = self.api_endpoint + 'services/{}/'.format( self.namespace) + self.name payload = { "app_name": self.name, "target_num_instances": self.target_num_instances, 'scaling_mode': 'MANUAL' } r = requests.put(url, headers=self.headers, data=json.dumps(payload)) util.check_response(r)
def create(self): print '[alauda] Creating backup "{}"'.format(self.name) url = self.service.api_endpoint + 'backups/{}/'.format( self.service.namespace) data = json.loads(self.service.details) payload = { 'app_id': data['unique_name'], 'name': self.name, 'app_volume_dir': self.mounted_dir } r = requests.post(url, headers=self.service.headers, data=json.dumps(payload)) util.check_response(r)
def fetch(cls, name, namespace=None): api_endpoint, token, username = auth.load_token() url = api_endpoint + 'services/{}/'.format(namespace or username) + name headers = auth.build_headers(token) r = requests.get(url, headers=headers) util.check_response(r) data = json.loads(r.text) service = cls(name=data['service_name'], image_name=data['image_name'], image_tag=data['image_tag'], target_num_instances=data['target_num_instances'], instance_size=data['instance_size'], details=r.text, namespace=data['namespace']) return service
def set_match_config(game, basechiptype, playmode, roomlevel, baseconfig="BASE_CHIPS-1000,LOW_LIMIT-30000,ROBOT_MAX_NUMBER-5", extraconfig="ROBOT_PLACE_BASE_TIMEOUT-30,PLAYEROUTCARDTIMEOUT-20"): ''' @brief 更新子游戏场次配置 @param game: 游戏id @param basechiptype: 底注类型 @param playmode: 玩法 @param roomlevel: 场次 @param baseconfig: 通用配置,key-value,key1-value1, key为要配置的参数,value为对应的值,多个参数用英文逗号分开 @param extraconfig: 额外配置, 有的游戏没有额外配置,默认即可 @return: 1:成功; 0:失败 ''' url = util.AUTO_TEST_URL postdata = { "ops": "setmatchconfig", "game": game, "basechiptype": basechiptype, "playmode": playmode, "roomlevel": roomlevel, "baseconfig": baseconfig, "extraconfig": extraconfig, } result = util.post(url, postdata) return util.check_response(result)
def add_proxy(mid, pno, name, invitepno, region=1, isstore=1, sjname='test', sjarea=1, partner=1): ''' @brief 添加代理商 @param mid: 用户mid @param pno: 用户手机号 @param name: 用户姓名 @param invitepno: 上级代理商id @param region: 地区id @param isstore: 是否商家摊位 0:否 ; 1:是 @param sjname: 商家名称 @param sjarea: 商家区域 1:延吉市; 2:图们市; 3:敦化市; 4:龙井市 ; 5:珲春市; 6:和龙市 ; 7:汪清县; 8:安图县 @param partner: 是否推广员 0:否; 1:是 @return: 1:成功; 0:失败 ''' url = util.AUTO_TEST_URL postdata = { "ops": 'agent', "mid": mid, "pno": pno, "name": name, "isstore": isstore, "region": region, "invitepno": invitepno, # 2031899, "sjname": sjname, "sjarea": sjarea, "partner": partner } result = util.post(url, postdata) return util.check_response(result)
def send_message(mid, title, bodys, tool_id=None, num=3, havegot=0): ''' @brief 发送私信 @param mid: 用户mid @param title: 标题 @param bodys: 内容 @param tool_id: 道具id或者id数组 @param num: 数量 @param havegot: @return: 1:成功 ; 0:失败 ''' url = util.AUTO_TEST_URL if tool_id: if type(tool_id) == type(0): tool_id = [tool_id] assert type(tool_id) == type([]) else: tool_id = [] tool_id = tool_id if tool_id else [22] postdata = { "ops": "message", "title": title, "bodys": bodys, "mids": [mid], "rewards": json.dumps([{'type': tid, 'num': num, 'havegot': havegot} for tid in tool_id]) } result = util.post(url, postdata) return util.check_response(result, only_check_code=True)
def set_notice(title, content, id=1, app_id=103000, region=1, weight=1, start_time=int(time.time()), end_time=int(time.time() + 60 * 10), is_html=1, status=1, conditions={"min_version": "0", "max_version": "0", "stime": "08:4:38", "etime": "20:4:40", "week":[0,1,2,3,4,5,6],"sendtype":0,"poptype":0,"isLogined":0}): ''' @brief 公告设置 @param title: 标题 @param content: 内容 @param id:公告id @param app_id: 应用id @param region: 区域id @param weight: 排序权重 @param start_time: 开始时间:从1970开始的秒数(默认从当前时间开始) @param end_time: 结束时间:从1970开始的秒数(默认从当前开始时间+10分钟) @param is_html: 0:文本公告 ; 1:富文本公告 ; 2:图片公告 @param status: 状态 0:关闭 1:正常 @param conditions: 附加条件(min_version:最小版本,max_version:最大版本,stime:生效开始,etime:生效结束,poptype:弹出频次 0:只弹一次 1:每天一次 2:每次弹出) @return: 1:成功; 0:失败 ''' url = util.AUTO_TEST_URL postdata = { "ops": 'notice', "id" : id, "app_id": app_id, "title": title, "content": json.dumps(content) if is_html ==2 else content, "weight": weight, "region": region, "start_time": time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(start_time)), "end_time": time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(end_time)), "is_html": is_html, "status": status, "conditions": json.dumps(conditions) } result = util.post(url, postdata) return util.check_response(result)
def list(cls, namespace, page): api_endpoint, token, username = auth.load_token() url = api_endpoint + 'services/{}/?page={}'.format(namespace or username, page) headers = auth.build_headers(token) r = requests.get(url, headers=headers) util.check_response(r) service_list = [] services = json.loads(r.text) services = services.get('results', []) for data in services: try: service = Service.fetch(data['service_name'], namespace) service_list.append(service) except AlaudaServerError: continue return service_list
def set_splash( region, start_time=int(time.time()), end_time=int(time.time() * 60 * 10), background="https://dfqppic.266.com/dfqp/pic/flashscreen/4e05xkrv.jpg", splashscreen="https://dfqppic.266.com/dfqp/pic/flashscreen/4e05xkrv.jpg" ): ''' @brief 设置闪屏图片 @param start_time: 开始时间:从1970开始的秒数(默认从当前时间开始) @param end_time: 结束时间:从1970开始的秒数(默认从当前开始时间+10分钟) @param backgroun: 背景图片url @param splashscreen: 闪屏图片url @return: 1:成功 ; 0:失败 ''' url = util.AUTO_TEST_URL postdata = { "ops": 'bg', "region": region, "stime": start_time, "etime": end_time, "background": background, "splashScreen": splashscreen } result = util.post(url, postdata) return util.check_response(result)
def set_robot_flag(gameid, basechiptype=0, playmode=1, roomlevel=1, robotflag=0): ''' @brief 设置场次配置机器人状态 @param gameid: 游戏id @param basechiptype: 底注 @param playmode: 玩法 @param roomlevel: 场次 @param robotflag: 机器人状态 0 关闭 1 开启 2 开启等待时间 @return: 1:成功; 0:失败 ''' url = util.AUTO_TEST_URL postdata = { "ops": "setrobotflag", "game": gameid, "basechiptype": basechiptype, "playmode": playmode, "roomlevel": roomlevel, "robotflag": robotflag } result = util.post(url, postdata) return util.check_response(result)
def login(username, password, cloud, endpoint): if not username: username = raw_input('Username: '******'generate-api-token/' payload = {'username': username, 'password': password} r = requests.post(url, payload) util.check_response(r) d = json.loads(r.text) token = d['token'] auth.save_token(api_endpoint, token, username) print '[alauda] Successfully logged in as {}.'.format(username)
def list(cls, namespace, page): api_endpoint, token, username = auth.load_token() url = api_endpoint + 'services/{}/?page={}'.format( namespace or username, page) headers = auth.build_headers(token) r = requests.get(url, headers=headers) util.check_response(r) service_list = [] services = json.loads(r.text) services = services.get('results', []) for data in services: try: service = Service.fetch(data['service_name'], namespace) service_list.append(service) except AlaudaServerError: continue return service_list
def login(username, password, cloud, endpoint): if not username: username = raw_input("Username: "******"generate-api-token/" payload = {"username": username, "password": password} r = requests.post(url, payload) util.check_response(r) d = json.loads(r.text) token = d["token"] auth.save_token(api_endpoint, token, username) print "[alauda] Successfully logged in as {}.".format(username)
def _upload( self, target_path, upload_auth_headers, upload_bucket, upload_object_key ): print ( '[alauda] Uploading {} to {}'.format( target_path, upload_object_key ) ) with open(target_path, 'rb') as data: response = requests.put( 'http://{}/{}/{}'.format( upload_auth_headers['Host'], upload_bucket, upload_object_key ), data=data, headers=upload_auth_headers ) util.check_response(response)