全部產品
Search
文件中心

Resource Orchestration Service:SDK常見問題

更新時間:Aug 24, 2023

本文為您介紹使用SDK時,可能遇到的問題。

使用SDK時遇到報錯ErrCode:SDK.ServerUnreachable怎麼辦?

問題現象

當您使用SDK時,遇到以下報錯資訊(請求逾時或伺服器不可達):

ErrCode:ServerUnreachable
ErrMsg:SocketTimeoutException has occurred on a socket read or accept.

解決方案

  1. 在請求中設定ClientToken參數避免多次重試帶來重複操作的問題。

    說明

    調用介面前,需配置環境變數,通過環境變數讀取存取憑證。更多資訊,請參見配置訪問憑證

    AccessKey ID和AccessKey Secret的環境變數名:ALIBABA_CLOUD_ACCESS_KEY_ID、ALIBABA_CLOUD_ACCESS_KEY_SECRET。

    Python範例程式碼如下:

    # coding=utf-8
    import time
    import uuid
    
    from alibabacloud_ros20190910 import models as ros20190910_models
    from aliyunsdkcore.acs_exception.exceptions import ClientException, ServerException
    from alibabacloud_tea_openapi import models as open_api_models
    from alibabacloud_credentials.client import Client as CredClient
    from alibabacloud_ros20190910.client import Client as ROS20190910Client
    
    
    def generate_client_token(prefix, add_uuid, *suffix_list):
        if prefix:
            t = [prefix]
        else:
            t = []
        if add_uuid:
            t.append(str(uuid.uuid1())[:-13])
        t.extend(suffix_list)
        r = '_'.join(t)
        if len(r) > 64:
            r = r[:64]
        return r
    
    
    def retry_with_client_token(retry_interval=10, retry_time_out=300):
        def wrapper(fun):
            def retry_func(*args, **kwargs):
                retry_timeout = retry_time_out
                elapsed_time = 0
                # 保證請求的等冪性。該值由用戶端產生,並且必須是全域唯一的。
                kwargs['client_token'] = generate_client_token(None, True)
                while True:
                    try:
                        retry_timeout -= elapsed_time
                        return fun(*args, **kwargs)
                    except Exception as e:
                        if isinstance(e, ClientException):
                            if e.error_code != 'SDK.HttpError':
                                raise
                        elif isinstance(e, ServerException):
                            if e.error_code not in ('LastTokenProcessing', 'ServiceUnavailable'):
                                raise
                        else:
                            raise
    
                        time.sleep(retry_interval)
                        elapsed_time += retry_interval
                        if elapsed_time >= retry_timeout:
                            raise
    
            return retry_func
    
        return wrapper
    
    
    class RosClient(object):
    
        @staticmethod
        def create_client():
            """
            初始化帳號Client
            @return: Client
            @throws Exception
            """
            cred = CredClient()
            config = open_api_models.Config(
                credential=cred
            )
            # 訪問的網域名稱
            config.endpoint = 'ros.aliyuncs.com'
    
            return ROS20190910Client(config)
    
        @retry_with_client_token(retry_interval=10, retry_time_out=300)
        def create_stack(self, region_id, stack_name, template_body, **kwargs):
            client = self.create_client()
            create_stack_request = ros20190910_models.CreateStackRequest(
                region_id=region_id,
                stack_name=stack_name,
                # 若模板較大,建議使用TemplateURL參數,避免URL過長,調用失敗。
                # 您也可以使用Body Param + HTTP POST的方式傳遞模板內容。
                template_body=template_body,
                disable_rollback=True,
                **kwargs
            )
            response = client.create_stack(create_stack_request)
    
            return response.body
    
    
    if __name__ == '__main__':
        regin_id = 'cn-beijing'
        ros_client = RosClient()
        stack_name = 'test'
        template_body = "{\"ROSTemplateFormatVersion\": \"2015-09-01\"}"
        result = ros_client.create_stack(region_id=regin_id, stack_name=stack_name, template_body=template_body)
        print('stack_id:', result)
  2. 如果問題依然存在,請提交工單擷取支援。