~pwlars/adt-continuous-deployer/clean-up-core-images

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#!/usr/bin/env python3
#
# Copyright (C) 2015 Canonical
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
"""CI Automation: monitoring (purging obsolete deployments) services."""

import argparse
import os
import sys


from ci_automation.nova import get_services_map
from ci_automation.utils import setup_logger


def main():
    parser = argparse.ArgumentParser(
        description="Check the number of deployments for a service")
    parser.add_argument(
        '--base-dir', '-b',
        default=os.path.expanduser("~/ci-cd-identifiers"),
        help="The directory where identifiers are stored "
        " (eg. ~/ci-cd-identifiers)")
    parser.add_argument(
        '--max-deployments', '-m', type=int, default=2,
        help="The maximum number of deployments to keep.")
    parser.add_argument(
        'stage_dirname',
        help="the mojo stage directory name (eg. mojo-ue-core-image-tester")

    args = parser.parse_args()
    logger = setup_logger()

    deployments = get_services_map(args.base_dir).get(args.stage_dirname)
    if deployments is None:
        print('No deployments found!')
        return

    sorted_deployments = sorted(
        deployments.items(), key=lambda d: d[1]['epoch'], reverse=True)
    for identifier, _ in sorted_deployments[args.max_deployments:]:
        extra = {
            "service": "ci/cd",
            "deployment_status": "DESTROYED",
            "deployment_name": args.stage_dirname,
            "deployment_identifier": identifier,
        }
        logger.info(
            "Destroying deployment %s", identifier, extra=extra)

    return 0


if __name__ == "__main__":
    sys.exit(main())