All Products
Search
Document Center

Resource Orchestration Service:FAQ about SDKs

Last Updated:Jun 25, 2023

This topic provides answers to some commonly asked questions about SDKs.

What do I do if the ErrCode:SDK.ServerUnreachable error occurs when I use SDKs?

Problem description

When you use SDKs, the following error occurs. The error indicates that the request times out or the server cannot be connected:

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

Solutions

  1. Specify the ClientToken parameter in the request to prevent the client from repeatedly sending the request.

    Note

    Before you call the operation, configure environment variables and obtain access credentials from the environment variables. For more information, see Configure access credentials.

    The environment variables of the AccessKey ID and the AccessKey secret are ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET.

    The following section provides the Python sample code:

    # 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
                # Specify the client token that is used to ensure the idempotence of the request. You can use the client to generate the token, but you must make sure that the token is unique among different requests. 
                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():
            """
            Initialize the client.
            @return: Client
            @throws Exception
            """
            cred = CredClient()
            config = open_api_models.Config(
                credential=cred
            )
            # Specify the domain name that you want to access.
            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,
                # If the length of the template body exceeds the upper limit, we recommend that you use the TemplateURL parameter to prevent request failures caused by excessively long URLs. 
                # You can also add parameters to the HTTP POST request body. 
                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. If the error persists, submit a ticket to obtain technical support.