File: endpoints.py

package info (click to toggle)
python-coriolisclient 1.0.9-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 596 kB
  • sloc: python: 5,614; makefile: 23; sh: 2
file content (265 lines) | stat: -rw-r--r-- 9,689 bytes parent folder | download
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
# Copyright (c) 2017 Cloudbase Solutions Srl
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Command-line interface sub-commands related to endpoints.
"""
import argparse
import json

from cliff import command
from cliff import lister
from cliff import show

from coriolisclient.cli import formatter
from coriolisclient import exceptions


def add_connection_info_args_to_parser(parser):
    """ Given an `argparse.ArgumentParser` instance, add the arguments required
    for the 'connection_info' field for both endpoint creation and updates.
    """
    conn_info_group = parser.add_mutually_exclusive_group()
    conn_info_group.add_argument('--connection',
                                 help='JSON encoded connection data')
    conn_info_group.add_argument('--connection-file',
                                 type=argparse.FileType('r'),
                                 help='Relative/full path to a file containing'
                                      ' the connection info in JSON format')
    conn_info_group.add_argument('--connection-secret',
                                 help='The url of the Barbican secret '
                                      'containing the JSON connection info')
    return parser


def get_connection_info_from_args(args, raise_if_none=True):
    """ Returns a dict with the connection info from the arguments. """
    conn_info = None
    raw_conn_info = None
    if args.connection:
        raw_conn_info = args.connection
    elif args.connection_file:
        with args.connection_file as fin:
            raw_conn_info = fin.read()
    elif args.connection_secret:
        conn_info = {"secret_ref": args.connection_secret}

    if not conn_info and raw_conn_info:
        try:
            conn_info = json.loads(raw_conn_info)
        except ValueError as ex:
            raise ValueError(
                "Error while parsing connection info JSON: %s" % str(ex))

    if not conn_info and raise_if_none:
        raise ValueError(
            "No '--connection[-file/secret]' parameter provided.")

    return conn_info


class EndpointFormatter(formatter.EntityFormatter):

    columns = ("ID",
               "Name",
               "Type",
               "Description",
               "Mapped Region IDs")

    def _get_sorted_list(self, obj_list):
        return sorted(obj_list, key=lambda o: o.created_at)

    def _get_formatted_data(self, obj):
        data = (obj.id,
                obj.name,
                obj.type,
                obj.description or "",
                obj.mapped_regions or [],
                )
        return data


class EndpointDetailFormatter(formatter.EntityFormatter):

    def __init__(self, show_instances_data=False):
        self.columns = [
            "id",
            "name",
            "type",
            "description",
            "connection_info",
            "mapped_regions",
            "created_at",
            "last_updated",
        ]

    def _get_formatted_data(self, obj):
        data = [obj.id,
                obj.name,
                obj.type,
                obj.description or "",
                obj.connection_info.to_dict(),
                obj.mapped_regions or [],
                obj.created_at,
                obj.updated_at,
                ]

        return data


class CreateEndpoint(show.ShowOne):
    """Creates a new endpoint"""
    def get_parser(self, prog_name):
        parser = super(CreateEndpoint, self).get_parser(prog_name)

        parser.add_argument('--name', required=True,
                            help='The endpoints\'s name')
        parser.add_argument('--provider', required=True,
                            help='The provider, e.g.: '
                            'vmware_vsphere, openstack')
        parser.add_argument('--description',
                            help='A description for this endpoint')
        parser.add_argument('--skip-validation', dest='skip_validation',
                            action='store_true',
                            help='Whether to skip validating the connection '
                            'when creating the endpoint.')
        parser.add_argument('--coriolis-region', action='append',
                            dest='regions', default=[],
                            help="ID of a region the endpoint should be  "
                            "associated with. Can be supplied multiple times.")
        add_connection_info_args_to_parser(parser)

        return parser

    def take_action(self, args):
        if args.connection_secret and args.connection:
            raise exceptions.CoriolisException(
                "Please specify either --connection or "
                "--connection-secret, but not both")

        conn_info = get_connection_info_from_args(args)
        endpoint = self.app.client_manager.coriolis.endpoints.create(
            args.name,
            args.provider,
            conn_info,
            args.description,
            regions=args.regions)

        if not args.skip_validation:
            valid, message = (
                self.app.client_manager.coriolis.endpoints.validate_connection(
                    endpoint.id))
            if not valid:
                raise exceptions.EndpointConnectionValidationFailed(message)

        return EndpointDetailFormatter().get_formatted_entity(endpoint)


class UpdateEndpoint(show.ShowOne):
    """Updates an endpoint"""
    def get_parser(self, prog_name):
        parser = super(UpdateEndpoint, self).get_parser(prog_name)
        parser.add_argument('id', help='The endpoint\'s id')
        parser.add_argument('--name',
                            help='The endpoints\'s name')
        parser.add_argument('--description',
                            help='A description for this endpoint')
        parser.add_argument('--coriolis-region', action='append',
                            dest='regions', default=[],
                            help="ID of a region the endpoint should be  "
                                 "associated with. Can be supplied multiple "
                                 "times. Update will override all existing "
                                 "region associations with the one(s) provided"
                                 " if at least one region is given.")
        add_connection_info_args_to_parser(parser)
        return parser

    def take_action(self, args):
        if args.connection_secret and args.connection:
            raise exceptions.CoriolisException(
                "Please specify either --connection or "
                "--connection-secret, but not both")

        conn_info = get_connection_info_from_args(args, raise_if_none=False)
        updated_values = {}
        if args.name is not None:
            updated_values["name"] = args.name
        if args.description is not None:
            updated_values["description"] = args.description
        if conn_info:
            updated_values["connection_info"] = conn_info
        if args.regions:
            updated_values["mapped_regions"] = args.regions

        endpoint = self.app.client_manager.coriolis.endpoints.update(
            args.id, updated_values)

        return EndpointDetailFormatter().get_formatted_entity(endpoint)


class ShowEndpoint(show.ShowOne):
    """Show an endpoint"""

    def get_parser(self, prog_name):
        parser = super(ShowEndpoint, self).get_parser(prog_name)
        parser.add_argument('id', help='The endpoint\'s id')
        return parser

    def take_action(self, args):
        client = self.app.client_manager.coriolis.endpoints
        endpoint_id = client.get_endpoint_id_for_name(args.id)
        endpoint = client.get(endpoint_id)
        return EndpointDetailFormatter().get_formatted_entity(endpoint)


class DeleteEndpoint(command.Command):
    """Delete an endpoint"""

    def get_parser(self, prog_name):
        parser = super(DeleteEndpoint, self).get_parser(prog_name)
        parser.add_argument('id', help='The endpoint\'s id')
        return parser

    def take_action(self, args):
        client = self.app.client_manager.coriolis.endpoints
        endpoint_id = client.get_endpoint_id_for_name(args.id)
        client.delete(endpoint_id)


class ListEndpoint(lister.Lister):
    """List endpoints"""

    def get_parser(self, prog_name):
        parser = super(ListEndpoint, self).get_parser(prog_name)
        return parser

    def take_action(self, args):
        obj_list = self.app.client_manager.coriolis.endpoints.list()
        return EndpointFormatter().list_objects(obj_list)


class EndpointValidateConnection(command.Command):
    """validates an edpoint's connection"""

    def get_parser(self, prog_name):
        parser = super(EndpointValidateConnection, self).get_parser(prog_name)
        parser.add_argument('id', help='The endpoint\'s id')
        return parser

    def take_action(self, args):
        endpoints = self.app.client_manager.coriolis.endpoints
        endpoint_id = endpoints.get_endpoint_id_for_name(args.id)
        valid, message = endpoints.validate_connection(endpoint_id)
        if not valid:
            raise exceptions.EndpointConnectionValidationFailed(message)