summaryrefslogtreecommitdiffstats
path: root/cli/objects/images.py
blob: dff2f9cacbb6be0f1caa2cd139191efbafb2638e (plain)
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
# Copyright (C) 2020-2024 Soleta Networks <opengnsys@soleta.eu>
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the
# Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.

from urllib.parse import urlparse
from cli.utils import *

import argparse
import requests

def get_repository(repository_id, rest):
    repositories = get_repositories(rest)
    if not repositories:
        return None
    [repository] = [repository for repository in repositories
                    if repository['id'] == repository_id]
    return repository


def get_repositories(rest):
    r = rest.get('/repositories')
    if not r or r.status_code != requests.codes.ok:
        return None
    repositories = r.json()['repositories']
    return repositories


class OgImage():

    @staticmethod
    def list_images(rest):
        r = rest.get('/images')
        print_json(r.text)

    @staticmethod
    def restore_image(rest, args):
        parser = argparse.ArgumentParser(prog='ogcli restore image')
        parser.add_argument('--disk',
                            nargs='?',
                            required=True,
                            help='Disk')
        parser.add_argument('--part',
                            nargs='?',
                            required=True,
                            help='Partition')
        parser.add_argument('--id',
                            nargs='?',
                            type=int,
                            required=True,
                            help='Image id to be restored')
        parser.add_argument('--type',
                            nargs='?',
                            required=False,
                            choices=['unicast',
                                     'unicast-direct', 'tiptorrent'],
                            default='tiptorrent',
                            help='Transfer method. (Default: tiptorrent)')
        parser.add_argument('--repo',
                            nargs='?',
                            required=False,
                            help='Repository IP address')
        group = parser.add_argument_group('clients', 'Client selection args')
        group.add_argument('--center-id',
                           type=int,
                           action='append',
                           default=[],
                           required=False,
                           help='Clients from given center id')
        group.add_argument('--room-id',
                           type=int,
                           action='append',
                           default=[],
                           required=False,
                           help='Clients from given room id')
        group.add_argument('--client-ip',
                           action='append',
                           default=[],
                           required=False,
                           help='Specific client IP')
        parsed_args = parser.parse_args(args)

        r = rest.get('/scopes')
        scopes = r.json()
        ips = set()

        for center in parsed_args.center_id:
            center_scope = scope_lookup(center, 'center', scopes)
            ips.update(ips_in_scope(center_scope))
        for room in parsed_args.room_id:
            room_scope = scope_lookup(room, 'room', scopes)
            ips.update(ips_in_scope(room_scope))
        for l in parsed_args.client_ip:
            ips.add(l)

        if not ips:
            print('Missing --client-ip, or --room-id/--center-id. No clients provided.')
            return

        r = rest.get('/images')
        images = r.json()
        found_image = [img for img in images['images']
                       if img['id'] == parsed_args.id]
        if not found_image:
            print(f'Image with id {parsed_args.id} not found.')
            return
        else:
            found_image = found_image[0]

        if not parsed_args.repo:
            repository = get_repository(found_image['repo_id'], rest)
            if not repository:
                print(f'Could not find repository for image {found_image["name"]}')
                return
            parsed_args.repo = repository['ip']

        payload = {'disk': parsed_args.disk, 'partition': parsed_args.part,
                   'id': str(parsed_args.id), 'name': found_image['name'],
                   'profile': str(found_image['software_id']),
                   'repository': parsed_args.repo,
                   'type': parsed_args.type.upper(), 'clients': list(ips)}
        r = rest.post('/image/restore', payload=payload)

    @staticmethod
    def create_image(rest, args):
        parser = argparse.ArgumentParser(prog='ogcli create image')
        parser.add_argument('--disk',
                            nargs='?',
                            required=True,
                            help='Disk')
        parser.add_argument('--part',
                            nargs='?',
                            required=True,
                            help='Partition')
        parser.add_argument('--name',
                            nargs='?',
                            required=True,
                            help='Image name')
        parser.add_argument('--desc',
                            nargs='?',
                            required=True,
                            help='Image description')
        group = parser.add_argument_group('clients', 'Client selection args')
        group.add_argument('--client-ip',
                           action='append',
                           default=[],
                           required=True,
                           help='Specific client IP')
        parsed_args = parser.parse_args(args)

        r = rest.get('/client/info', payload={'client': parsed_args.client_ip})
        center_id = r.json()['center']
        repo_id = r.json()['repo_id']

        r = rest.get('/client/setup',
                     payload={'client': parsed_args.client_ip})
        if r.status_code == 200:
            part_info = list(filter(lambda x: x['disk'] == int(parsed_args.disk) and
                             x['partition'] == int(parsed_args.part),
                             r.json()['partitions']))
            if not part_info:
                print('Partition not found.')
                return
            fs_code = list(part_info)[0]['code']

        image_name = remove_accents(parsed_args.name)
        payload = {'clients': parsed_args.client_ip, 'disk': parsed_args.disk, 'center_id': center_id,
                   'partition': parsed_args.part, 'code': str(fs_code), 'name': image_name,
                   'id': '0', 'repository_id': repo_id}
        if parsed_args.desc:
            payload['description'] = parsed_args.desc

        rest.post('/image/create', payload=payload)

    @staticmethod
    def update_image(rest, args):
        parser = argparse.ArgumentParser(prog='ogcli update image')
        parser.add_argument('--disk',
                            nargs='?',
                            required=True,
                            help='Disk')
        parser.add_argument('--part',
                            nargs='?',
                            required=True,
                            help='Partition')
        parser.add_argument('--id',
                            type=int,
                            nargs='?',
                            required=True,
                            help='Image id')
        parser.add_argument('--backup',
                            action='store_true',
                            required=False,
                            default=False,
                            help='Create a backup before updating the image (No backup is created by default)')
        group = parser.add_argument_group('clients', 'Client selection args')
        group.add_argument('--client-ip',
                           action='append',
                           default=[],
                           required=True,
                           help='Specific client IP')
        parsed_args = parser.parse_args(args)

        r = rest.get('/client/info', payload={'client': parsed_args.client_ip})
        center_id = r.json()['center']
        repo_id = int(r.json()['repo_id'])

        r = rest.get('/client/setup',
                     payload={'client': parsed_args.client_ip})
        if r.status_code == 200:
            part_info = list(filter(lambda x: x['disk'] == int(parsed_args.disk) and
                             x['partition'] == int(parsed_args.part),
                             r.json()['partitions']))
            if not part_info:
                print('Partition not found.')
                return
            fs_code = list(part_info)[0]['code']

        r = rest.get('/images')
        image_name = None
        if r.status_code == 200:
            for image in r.json()['images']:
                if image['id'] == int(parsed_args.id):
                    image_name = image['name']
                    break

        if not image_name:
            print('Image not found')
            return
        else:
            print(f'Updating {image_name} image')

        payload = {'repository_id': repo_id,
                   'clients': parsed_args.client_ip,
                   'partition': parsed_args.part,
                   'backup': parsed_args.backup,
                   'disk': parsed_args.disk,
                   'center_id': center_id,
                   'id': str(parsed_args.id),
                   'code': str(fs_code),
                   'name': image_name}

        rest.post('/image/update', payload=payload)