Example #1
0
 def test_ecs_ram_role_signer(self, mock_urlopen):
     credential = EcsRamRoleCredential("role")
     signer = EcsRamRoleSigner(credential)
     request = RpcRequest("product", "version", "action_name")
     res = Mock()
     res.read.return_value = ensure_bytes('{"Code": "Success","AccessKeyId":"access_key_id",\
         "AccessKeySecret":"access_key_secret","Expiration":3600,\
         "SecurityToken": "security_token"}')
     mock_urlopen.return_value = res
     headers, url = signer.sign('cn-hangzhou', request)
     mock_urlopen.assert_called_once_with(
         'http://100.100.100.200/latest/meta-data/ram/security-credentials/role')
     self.assertEqual(request.get_query_params().get(
         "SecurityToken"), 'security_token')
     # self.assertEqual(url, '/?SignatureVersion=1.0&Format=None"
     # "&Timestamp=2018-12-02T11%3A03%3A01Z&RegionId=cn-hangzhou"
     # "&AccessKeyId=access_key_id&SignatureMethod=HMAC-SHA1"
     # "&Version=version&Signature=AmdeJh1ZOW6PgwM3%2BROhEnbKII4%3D"
     # "&Action=action_name&SignatureNonce=d5e6e832-7f95-4f26-9e28-017f735721f8&SignatureType=')
     request = RoaRequest("product", "version",
                          "action_name", uri_pattern="/")
     request.set_method('get')
     self.assertIsNone(request.get_headers().get("x-acs-security-token"))
     headers, url = signer.sign('cn-hangzhou', request)
     self.assertEqual(request.get_headers().get(
         "x-acs-security-token"), 'security_token')
 def test_ecs_ram_role(self):
     # push ecs
     from aliyunsdkcore.auth.credentials import EcsRamRoleCredential
     ecs_ram_role_credential = EcsRamRoleCredential("TestRole")
     acs_client = AcsClient(region_id="cn-hangzhou", credential=ecs_ram_role_credential)
     request = DescribeRegionsRequest()
     response = acs_client.do_action_with_exception(request)
Example #3
0
 def _prepare_kms(self):
     if not ((self.region_id and self.kms_ak and self.kms_secret) or (self.region_id and self.ram_role_name)):
         return False
     if not self.kms_client:
         if self.ram_role_name:
             self.kms_client = AcsClient(region_id=self.region_id,
                                         credential=EcsRamRoleCredential(self.ram_role_name))
         else:
             self.kms_client = AcsClient(ak=self.kms_ak, secret=self.kms_secret, region_id=self.region_id)
     return True
Example #4
0
    def test_ecs_ram_role_signer_unsuccess(self, mock_urlopen):
        credential = EcsRamRoleCredential("role")
        signer = EcsRamRoleSigner(credential)
        request = RpcRequest("product", "version", "action_name")
        res = Mock()
        res.read.return_value = ensure_bytes('{"Code": "400"}')
        mock_urlopen.return_value = res
        with self.assertRaises(ServerException) as ex:
            signer.sign('cn-hangzhou', request)

        self.assertEqual(
            "refresh Ecs sts token err, code is 400", ex.exception.message)
Example #5
0
def main():
    conn = None

    device_opt = [
        "port", "no_password", "region", "access_key", "secret_key", "ram_role"
    ]

    atexit.register(atexit_handler)

    define_new_opts()

    all_opt["power_timeout"]["default"] = "60"

    options = check_input(device_opt, process_input(device_opt))

    docs = {}
    docs["shortdesc"] = "Fence agent for Aliyun (Aliyun Web Services)"
    docs["longdesc"] = "fence_aliyun is an I/O Fencing agent for Aliyun"
    docs["vendorurl"] = "http://www.aliyun.com"
    show_docs(options, docs)

    run_delay(options)

    if "--region" in options:
        region = options["--region"]
        if "--access-key" in options and "--secret-key" in options:
            access_key = options["--access-key"]
            secret_key = options["--secret-key"]
            conn = client.AcsClient(access_key, secret_key, region)
        elif "--ram-role" in options:
            ram_role = options["--ram-role"]
            role = EcsRamRoleCredential(ram_role)
            conn = client.AcsClient(region_id=region, credential=role)
        else:
            fail_usage(
                "Failed: User credentials are not set. Please set the Access Key and the Secret Key, or configure the RAM role."
            )

        # Use intranet endpoint to access ECS service
        try:
            region_provider.modify_point('Ecs', region,
                                         'ecs.%s.aliyuncs.com' % region)
        except Exception as e:
            logging.warn(
                "Failed: failed to modify endpoint to 'ecs.%s.aliyuncs.com': %s"
                % (region, e))

    # Operate the fencing device
    result = fence_action(conn, options, set_power_status, get_power_status,
                          get_nodes_list)
    sys.exit(result)
Example #6
0
    def make_request_new(self, params):
        if not params:
            raise Exception("Request parameters should not be empty.")

        conn = None
        if self.acs_access_key_id and self.acs_secret_access_key:
            conn = client.AcsClient(self.acs_access_key_id, self.acs_secret_access_key, self.region, user_agent=self.user_agent)
            if self.security_token:
                sts_token_credential = StsTokenCredential(self.access_key, self.secret_key, self.security_token)
                conn = client.AcsClient(region_id=self.region, user_agent=self.user_agent, credential=sts_token_credential)
        else:
            if self.ecs_role_name:
                ecs_ram_role_credential = EcsRamRoleCredential(self.ecs_role_name)
                conn = client.AcsClient(region_id=self.region, user_agent=self.user_agent, credential=ecs_ram_role_credential)

        if not conn:
            footmark.log.error('%s %s' % ('Null AcsClient ', conn))
            raise self.FootmarkClientError('Null AcsClient ', conn)

        timeout = 200
        delay = 3
        if not isinstance(params, dict):
            raise Exception("Invalid request parameters: {0} should be a dict.".format(params))

        if not params.get('Action', params.get('action')):
            raise Exception("'Action' is required for this request.")

        while timeout > 0:
            request = self.import_request(params.get('Action', params.get('action')))
            request.set_accept_format('json')
            try:
                for k, v in list(params.items()):
                    if hasattr(request, k):
                        getattr(request, k)(v)
                    else:
                        request.add_query_param(k[4:], v)
                return conn.do_action_with_exception(request)
            except ServerException as e:
                if str(e.error_code) == "SDK.ServerUnreachable" \
                        or str(e.message).__contains__("SDK.ServerUnreachable") \
                        or str(e.message).__contains__("Unable to connect server: timed out"):
                    time.sleep(delay)
                    timeout -= delay
                    continue
                raise e
            except Exception as e:
                raise e

        return None
Example #7
0
def main():
    conn = None

    device_opt = [
        "port", "no_password", "region", "access_key", "secret_key", "ram_role"
    ]

    atexit.register(atexit_handler)

    define_new_opts()

    all_opt["power_timeout"]["default"] = "60"

    options = check_input(device_opt, process_input(device_opt))

    docs = {}
    docs["shortdesc"] = "Fence agent for Aliyun (Aliyun Web Services)"
    docs["longdesc"] = "fence_aliyun is an I/O Fencing agent for Aliyun"
    docs["vendorurl"] = "http://www.aliyun.com"
    show_docs(options, docs)

    run_delay(options)

    if "--region" in options:
        region = options["--region"]
        if "--access-key" in options and "--secret-key" in options:
            access_key = options["--access-key"]
            secret_key = options["--secret-key"]
            conn = client.AcsClient(access_key, secret_key, region)
        elif "--ram-role" in options:
            ram_role = options["--ram-role"]
            _check_role(ram_role)
            role = EcsRamRoleCredential(ram_role)
            conn = client.AcsClient(region_id=region, credential=role)
        region_provider.modify_point('Ecs', region,
                                     'ecs.%s.aliyuncs.com' % region)

    # Operate the fencing device
    result = fence_action(conn, options, set_power_status, get_power_status,
                          get_nodes_list)
    sys.exit(result)
Example #8
0
import sys
if (len(sys.argv) != 4):
    print("usage: " + sys.argv[0] + " zone_id reverse_zone_id role_name")
    exit(1)
else:
    zone_id = sys.argv[1]
    reverse_zone_id = sys.argv[2]
    role_name = sys.argv[3]

print("hostname=" + hostname)
print("ip=" + ip)
print("record=" + record)
print("zone_id=" + zone_id)
print("reverse_zone_id=" + reverse_zone_id)

credential = EcsRamRoleCredential(role_name)
client = AcsClient(credential=credential)

# get zone name from zone_id
request = DescribeZoneInfoRequest()
request.set_accept_format('json')
request.set_ZoneId(zone_id)
response = client.do_action_with_exception(request)

import json
json = json.loads(response)
domain_name = json["ZoneName"]
print("domain_name=" + domain_name)

request = AddZoneRecordRequest()
request.set_accept_format('json')
Example #9
0
 def test_EcsRamRoleCredential(self):
     c = EcsRamRoleCredential("role_name")
     self.assertEqual("role_name", c.role_name)