Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

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

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

338

339

340

341

342

343

344

345

346

347

# All Rights Reserved. 

# 

#    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. 

 

import datetime 

 

import glanceclient.exc 

import pecan 

from pecan import rest 

import wsme 

from wsme import types as wtypes 

import wsmeext.pecan as wsme_pecan 

 

from magnum.api.controllers import base 

from magnum.api.controllers import link 

from magnum.api.controllers.v1 import collection 

from magnum.api.controllers.v1 import types 

from magnum.api.controllers.v1 import utils as api_utils 

from magnum.common import clients 

from magnum.common import exception 

from magnum import objects 

 

 

class BayModelPatchType(types.JsonPatchType): 

    pass 

 

 

class BayModel(base.APIBase): 

    """API representation of a baymodel. 

 

    This class enforces type checking and value constraints, and converts 

    between the internal object model and the API representation of a baymodel. 

    """ 

 

    _coe = None 

 

    def _get_coe(self): 

        return self._coe 

 

    def _set_coe(self, value): 

        if value and self._coe != value: 

            self._coe = value 

exit        elif value == wtypes.Unset: 

            self._coe = wtypes.Unset 

 

    uuid = types.uuid 

    """Unique UUID for this baymodel""" 

 

    name = wtypes.StringType(min_length=1, max_length=255) 

    """The name of the bay model""" 

 

    coe = wsme.wsproperty(wtypes.text, _get_coe, _set_coe, mandatory=True) 

    """The Container Orchestration Engine for this bay model""" 

 

    image_id = wsme.wsattr(wtypes.StringType(min_length=1, max_length=255), 

                           mandatory=True) 

    """The image name or UUID to use as a base image for this baymodel""" 

 

    flavor_id = wtypes.StringType(min_length=1, max_length=255) 

    """The flavor of this bay model""" 

 

    master_flavor_id = wtypes.StringType(min_length=1, max_length=255) 

    """The flavor of the master node for this bay model""" 

 

    dns_nameserver = types.IPv4AddressType() 

    """The DNS nameserver address""" 

 

    keypair_id = wsme.wsattr(wtypes.StringType(min_length=1, max_length=255), 

                             mandatory=True) 

    """The name or id of the nova ssh keypair""" 

 

    external_network_id = wtypes.StringType(min_length=1, max_length=255) 

    """The external network to attach the Bay""" 

 

    fixed_network = wtypes.StringType(min_length=1, max_length=255) 

    """The fixed network name to attach the Bay""" 

 

    apiserver_port = wtypes.IntegerType(minimum=1024, maximum=65535) 

    """The API server port for k8s""" 

 

    docker_volume_size = wtypes.IntegerType(minimum=1) 

    """The size in GB of the docker volume""" 

 

    ssh_authorized_key = wtypes.StringType(min_length=1) 

    """The SSH Authorized Key""" 

 

    cluster_distro = wtypes.StringType(min_length=1, max_length=255) 

    """The Cluster distro for the bay, ex - coreos, fedora-atomic.""" 

 

    links = wsme.wsattr([link.Link], readonly=True) 

    """A list containing a self link and associated baymodel links""" 

 

    def __init__(self, **kwargs): 

        self.fields = [] 

        for field in objects.BayModel.fields: 

            # Skip fields we do not expose. 

            if not hasattr(self, field): 

                continue 

            self.fields.append(field) 

            setattr(self, field, kwargs.get(field, wtypes.Unset)) 

 

    @staticmethod 

    def _convert_with_links(baymodel, url, expand=True): 

        if not expand: 

            baymodel.unset_fields_except(['uuid', 'name', 'image_id', 

                                          'apiserver_port', 'coe']) 

 

        baymodel.links = [link.Link.make_link('self', url, 

                                          'baymodels', baymodel.uuid), 

                      link.Link.make_link('bookmark', url, 

                                          'baymodels', baymodel.uuid, 

                                          bookmark=True) 

                     ] 

        return baymodel 

 

    @classmethod 

    def convert_with_links(cls, rpc_baymodel, expand=True): 

        baymodel = BayModel(**rpc_baymodel.as_dict()) 

        return cls._convert_with_links(baymodel, pecan.request.host_url, 

                                       expand) 

 

    @classmethod 

    def sample(cls, expand=True): 

        sample = cls(uuid='27e3153e-d5bf-4b7e-b517-fb518e17f34c', 

                    name='example', 

                    image_id='Fedora-k8s', 

                    flavor_id='m1.small', 

                    master_flavor_id='m1.small', 

                    dns_nameserver='8.8.1.1', 

                    keypair_id='keypair1', 

                    external_network_id='ffc44e4a-2319-4062-bce0-9ae1c38b05ba', 

                    fixed_network='private', 

                    apiserver_port=8080, 

                    docker_volume_size=25, 

                    cluster_distro='fedora-atomic', 

                    ssh_authorized_key='ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAB', 

                    coe='kubernetes', 

                    created_at=datetime.datetime.utcnow(), 

                    updated_at=datetime.datetime.utcnow()) 

        return cls._convert_with_links(sample, 'http://localhost:9511', expand) 

 

 

class BayModelCollection(collection.Collection): 

    """API representation of a collection of baymodels.""" 

 

    baymodels = [BayModel] 

    """A list containing baymodels objects""" 

 

    def __init__(self, **kwargs): 

        self._type = 'baymodels' 

 

    @staticmethod 

    def convert_with_links(rpc_baymodels, limit, url=None, expand=False, 

                           **kwargs): 

        collection = BayModelCollection() 

        collection.baymodels = [BayModel.convert_with_links(p, expand) 

                            for p in rpc_baymodels] 

        collection.next = collection.get_next(limit, url=url, **kwargs) 

        return collection 

 

    @classmethod 

    def sample(cls): 

        sample = cls() 

        sample.baymodels = [BayModel.sample(expand=False)] 

        return sample 

 

 

class BayModelsController(rest.RestController): 

    """REST controller for BayModels.""" 

 

    from_baymodels = False 

    """A flag to indicate if the requests to this controller are coming 

    from the top-level resource BayModels.""" 

 

    _custom_actions = { 

        'detail': ['GET'], 

    } 

 

    def _get_baymodels_collection(self, marker, limit, 

                              sort_key, sort_dir, expand=False, 

                              resource_url=None): 

 

        limit = api_utils.validate_limit(limit) 

        sort_dir = api_utils.validate_sort_dir(sort_dir) 

 

        marker_obj = None 

198        if marker: 

            marker_obj = objects.BayModel.get_by_uuid(pecan.request.context, 

                                                  marker) 

 

        baymodels = objects.BayModel.list(pecan.request.context, limit, 

                                marker_obj, sort_key=sort_key, 

                                sort_dir=sort_dir) 

 

        return BayModelCollection.convert_with_links(baymodels, limit, 

                                                url=resource_url, 

                                                expand=expand, 

                                                sort_key=sort_key, 

                                                sort_dir=sort_dir) 

 

    def _get_image_data(self, context, image_ident): 

        """Retrieves os_distro and other metadata from the Glance image. 

 

        :param image_ident: image id or name of baymodel. 

        """ 

        try: 

            cli = clients.OpenStackClients(context) 

            return api_utils.get_openstack_resource(cli.glance().images, 

                                                    image_ident, 'images') 

        except glanceclient.exc.NotFound: 

            raise exception.ImageNotFound(image_id=image_ident) 

        except glanceclient.exc.HTTPForbidden: 

            raise exception.ImageNotAuthorized(image_id=image_ident) 

 

    @wsme_pecan.wsexpose(BayModelCollection, types.uuid, 

                         types.uuid, int, wtypes.text, wtypes.text) 

    def get_all(self, baymodel_uuid=None, marker=None, limit=None, 

                sort_key='id', sort_dir='asc'): 

        """Retrieve a list of baymodels. 

 

        :param marker: pagination marker for large data sets. 

        :param limit: maximum number of resources to return in a single result. 

        :param sort_key: column to sort results by. Default: id. 

        :param sort_dir: direction to sort. "asc" or "desc". Default: asc. 

        """ 

        return self._get_baymodels_collection(marker, limit, sort_key, 

                                         sort_dir) 

 

    @wsme_pecan.wsexpose(BayModelCollection, types.uuid, 

                         types.uuid, int, wtypes.text, wtypes.text) 

    def detail(self, baymodel_uuid=None, marker=None, limit=None, 

                sort_key='id', sort_dir='asc'): 

        """Retrieve a list of baymodels with detail. 

 

        :param baymodel_uuid: UUID of a baymodel, to get only baymodels for 

               that baymodel. 

        :param marker: pagination marker for large data sets. 

        :param limit: maximum number of resources to return in a single result. 

        :param sort_key: column to sort results by. Default: id. 

        :param sort_dir: direction to sort. "asc" or "desc". Default: asc. 

        """ 

        # NOTE(lucasagomes): /detail should only work agaist collections 

        parent = pecan.request.path.split('/')[:-1][-1] 

        if parent != "baymodels": 

            raise exception.HTTPNotFound 

 

        expand = True 

        resource_url = '/'.join(['baymodels', 'detail']) 

        return self._get_baymodels_collection(marker, limit, 

                                         sort_key, sort_dir, expand, 

                                         resource_url) 

 

    @wsme_pecan.wsexpose(BayModel, types.uuid_or_name) 

    def get_one(self, baymodel_ident): 

        """Retrieve information about the given baymodel. 

 

        :param baymodel_ident: UUID or logical name of a baymodel. 

        """ 

270        if self.from_baymodels: 

            raise exception.OperationNotPermitted 

 

        rpc_baymodel = api_utils.get_rpc_resource('BayModel', baymodel_ident) 

        return BayModel.convert_with_links(rpc_baymodel) 

 

    @wsme_pecan.wsexpose(BayModel, body=BayModel, status_code=201) 

    def post(self, baymodel): 

        """Create a new baymodel. 

 

        :param baymodel: a baymodel within the request body. 

        """ 

282        if self.from_baymodels: 

            raise exception.OperationNotPermitted 

 

        baymodel_dict = baymodel.as_dict() 

        context = pecan.request.context 

        auth_token = context.auth_token_info['token'] 

        baymodel_dict['project_id'] = auth_token['project']['id'] 

        baymodel_dict['user_id'] = auth_token['user']['id'] 

        image_data = self._get_image_data(context, baymodel_dict['image_id']) 

        if image_data.get('os_distro'): 

            baymodel_dict['cluster_distro'] = image_data['os_distro'] 

        else: 

            raise exception.OSDistroFieldNotFound( 

                image_id=baymodel_dict['image_id']) 

        new_baymodel = objects.BayModel(context, **baymodel_dict) 

        new_baymodel.create() 

        # Set the HTTP Location Header 

        pecan.response.location = link.build_url('baymodels', 

                                  new_baymodel.uuid) 

        return BayModel.convert_with_links(new_baymodel) 

 

    @wsme.validate(types.uuid, [BayModelPatchType]) 

    @wsme_pecan.wsexpose(BayModel, types.uuid, body=[BayModelPatchType]) 

    def patch(self, baymodel_uuid, patch): 

        """Update an existing baymodel. 

 

        :param baymodel_uuid: UUID of a baymodel. 

        :param patch: a json PATCH document to apply to this baymodel. 

        """ 

311        if self.from_baymodels: 

            raise exception.OperationNotPermitted 

 

        rpc_baymodel = objects.BayModel.get_by_uuid(pecan.request.context, 

            baymodel_uuid) 

        try: 

            baymodel_dict = rpc_baymodel.as_dict() 

            baymodel = BayModel(**api_utils.apply_jsonpatch(baymodel_dict, 

                patch)) 

        except api_utils.JSONPATCH_EXCEPTIONS as e: 

            raise exception.PatchError(patch=patch, reason=e) 

 

        # Update only the fields that have changed 

        for field in objects.BayModel.fields: 

            try: 

                patch_val = getattr(baymodel, field) 

            except AttributeError: 

                # Ignore fields that aren't exposed in the API 

                continue 

            if patch_val == wtypes.Unset: 

                patch_val = None 

            if rpc_baymodel[field] != patch_val: 

                rpc_baymodel[field] = patch_val 

 

        rpc_baymodel.save() 

        return BayModel.convert_with_links(rpc_baymodel) 

 

    @wsme_pecan.wsexpose(None, types.uuid_or_name, status_code=204) 

    def delete(self, baymodel_ident): 

        """Delete a baymodel. 

 

        :param baymodel_uuid: UUID or logical name of a baymodel. 

        """ 

344        if self.from_baymodels: 

            raise exception.OperationNotPermitted 

 

        rpc_baymodel = api_utils.get_rpc_resource('BayModel', baymodel_ident) 

        rpc_baymodel.destroy()