1# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
2#
3# Licensed under the Apache License, Version 2.0 (the "License"). You
4# may not use this file except in compliance with the License. A copy of
5# the License is located at
6#
7# http://aws.amazon.com/apache2.0/
8#
9# or in the "license" file accompanying this file. This file is
10# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
11# ANY KIND, either express or implied. See the License for the specific
12# language governing permissions and limitations under the License.
13
14import json
15import yaml
16
17from awscli.customizations.ecs import exceptions
18
19MAX_CHAR_LENGTH = 46
20APP_PREFIX = 'AppECS-'
21DGP_PREFIX = 'DgpECS-'
22
23
24def find_required_key(resource_name, obj, key):
25
26    if obj is None:
27        raise exceptions.MissingPropertyError(
28            resource=resource_name, prop_name=key)
29
30    result = _get_case_insensitive_key(obj, key)
31
32    if result is None:
33        raise exceptions.MissingPropertyError(
34            resource=resource_name, prop_name=key)
35    else:
36        return result
37
38
39def _get_case_insensitive_key(target_obj, target_key):
40    key_to_match = target_key.lower()
41    key_list = target_obj.keys()
42
43    for key in key_list:
44        if key.lower() == key_to_match:
45            return key
46
47
48def get_app_name(service, cluster, app_value):
49    if app_value is not None:
50        return app_value
51    else:
52        suffix = _get_ecs_suffix(service, cluster)
53        return APP_PREFIX + suffix
54
55
56def get_cluster_name_from_arn(arn):
57    return arn.split('/')[1]
58
59
60def get_deploy_group_name(service, cluster, dg_value):
61    if dg_value is not None:
62        return dg_value
63    else:
64        suffix = _get_ecs_suffix(service, cluster)
65        return DGP_PREFIX + suffix
66
67
68def _get_ecs_suffix(service, cluster):
69    if cluster is None:
70        cluster_name = 'default'
71    else:
72        cluster_name = cluster[:MAX_CHAR_LENGTH]
73
74    return cluster_name + '-' + service[:MAX_CHAR_LENGTH]
75
76
77def parse_appspec(appspec_str):
78    try:
79        return json.loads(appspec_str)
80    except ValueError:
81        return yaml.safe_load(appspec_str)
82