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

348

349

350

351

352

353

354

355

356

357

358

359

360

361

362

363

364

365

366

367

368

369

370

371

372

373

374

375

376

377

378

379

380

381

382

383

384

385

386

387

388

389

390

391

392

393

394

395

396

397

398

399

400

401

402

403

404

405

406

407

408

409

410

411

412

413

414

415

416

417

418

419

420

421

422

423

424

425

426

427

428

429

430

431

432

433

434

435

436

437

438

439

440

441

# coding=utf-8 

# 

# Copyright (C) 2010-2012 Platform Computing 

# 

# This library is free software; you can redistribute it and/or 

# modify it under the terms of the GNU Lesser General Public 

# License as published by the Free Software Foundation; either 

# version 2.1 of the License, or (at your option) any later version. 

# 

# This library 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 

# Lesser General Public License for more details. 

# 

# You should have received a copy of the GNU Lesser General Public 

# License along with this library; if not, write to the Free Software 

# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA 

# 

''' 

Python module holding routines for handling resources and collections. 

 

Created on Jun 30, 2011 

 

@author: tmetsch 

''' 

 

from occi.backend import UserDefinedMixinBackend 

from occi.core_model import Resource, Link, Mixin 

from occi.exceptions import HTTPError 

import uuid 

 

#============================================================================== 

# Handling of Resources & Links 

#============================================================================== 

 

 

def create_entity(key, entity, registry, extras): 

    ''' 

    Handles all the model magic during creation of an entity. 

 

    If it's an resource it will verify that all links are created. 

 

    If it's a link it will ensure that source and target are properly set. 

 

    key -- The key for the entity. 

    entity -- The entity itself - either Link or Resource instance. 

    registry -- The registry used for this process. 

    extras -- Any extra arguments which are defined by the user. 

    ''' 

    entity.identifier = key 

 

    # if it is an resource we create make sure we create the links properly 

    if isinstance(entity, Resource): 

        # if it's a resource - set/create links properly. 

        for link in entity.links: 

            # FUTURE_IMPROVEMENT: string links 

            if link.identifier is None: 

                link.identifier = create_id(link.kind) 

            elif link.identifier in registry.get_resource_keys(extras): 

                raise AttributeError('A link with that id is already present') 

 

            for back in registry.get_all_backends(link, extras): 

                back.create(link, extras) 

 

            registry.add_resource(link.identifier, link, extras) 

    elif isinstance(entity, Link): 

        entity.source.links.append(entity) 

 

    # call all the backends who are associated with this entity.kind... 

    backends = registry.get_all_backends(entity, extras) 

    for backend in backends: 

        backend.create(entity, extras) 

 

    registry.add_resource(key, entity, extras) 

 

 

def delete_entity(entity, registry, extras): 

    ''' 

    Handles all the model magic during deletion if an entity. 

 

    If it's a link it will remove the link from the entity source links list. 

 

    entity -- The entity itself - either Link or Resource instance. 

    registry -- The registry used for this process. 

    extras -- Any extra arguments which are defined by the user. 

    ''' 

    if isinstance(entity, Resource): 

        # it's an resource - so delete all it's links 

        # FUTURE_IMPROVEMENT: string links 

        for link in entity.links: 

            for back in registry.get_all_backends(link, extras): 

                back.delete(link, extras) 

            registry.delete_resource(link.identifier, extras) 

    elif isinstance(entity, Link): 

        entity.source.links.remove(entity) 

 

    # call all the backends who are associated with this entity.kind... 

    backends = registry.get_all_backends(entity, extras) 

 

    for backend in backends: 

        backend.delete(entity, extras) 

 

    registry.delete_resource(entity.identifier, extras) 

 

 

def replace_entity(old, new, registry, extras): 

    ''' 

    Replace an entity - backends decide what is done. 

 

    If it's a link the entities must be replaced. 

 

    old -- The old entity. 

    new -- The new entity. 

    registry -- The registry used for this process. 

    extras -- Any extra arguments which are defined by the user. 

    ''' 

    if isinstance(new, Resource) and len(new.links) is not 0: 

        raise HTTPError(400, 'It is not recommend to have links in a full' + 

                        ' update request') 

 

    if new.kind is not old.kind: 

        raise AttributeError('It is not possible to change the kind of an' + 

                             ' entity.') 

 

    # call all the backends who are associated with this entity.kind... 

    backends = registry.get_all_backends(old, extras) 

    new_backends = registry.get_all_backends(new, extras) 

    for backend in backends: 

        backend.replace(old, new, extras) 

    for backend in unique(new_backends, backends): 

        backend.create(new, extras) 

    for backend in unique(backends, new_backends): 

        backend.delete(old, extras) 

    del new 

 

 

def update_entity(old, new, registry, extras): 

    ''' 

    Update an entity - backends decide what is done. 

 

    If it's a link the entities must be updated. 

 

    old -- The old entity. 

    new -- The new entity. 

    registry -- The registry used for this process. 

    extras -- Any extra arguments which are defined by the user. 

    ''' 

    if isinstance(new, Resource) and len(new.links) is not 0: 

        raise HTTPError(400, 'It is not recommend to have links in a full' + 

                        ' update request') 

 

    # call all the backends who are associated with this entity.kind... 

    backends = registry.get_all_backends(old, extras) 

    new_backends = registry.get_all_backends(new, extras) 

    for backend in backends: 

        backend.update(old, new, extras) 

    for backend in unique(new_backends, backends): 

        # for added mixins called create! 

        backend.create(old, extras) 

 

    del new 

 

 

def retrieve_entity(entity, registry, extras): 

    ''' 

    Retrieves/refreshed an entity. 

 

    If it's a link the entities must be retrieved/refreshed. 

 

    entity -- The entity which is to be retrieved. 

    registry -- The registry used for this process. 

    extras -- Any extra arguments which are defined by the user. 

    ''' 

    if isinstance(entity, Resource): 

        # if it's a resource - retrieve all links... 

        for link in entity.links: 

            # FUTURE_IMPROVEMENT: string links 

            for back in registry.get_all_backends(link, extras): 

                back.retrieve(link, extras) 

 

    # call all the backends who are associated with this entity.kind... 

    backends = registry.get_all_backends(entity, extras) 

    for backend in backends: 

        backend.retrieve(entity, extras) 

 

 

def action_entity(entity, action, registry, attributes, extras): 

    ''' 

    Performs an action on the entity. 

 

    entity -- The entity on which to perform the operation. 

    action -- The action definition. 

    registry -- The registry used for this process. 

    attributes -- The attributes fro the operation. 

    extras -- Any extra arguments which are defined by the user. 

    ''' 

    backend = registry.get_backend(action, extras) 

    backend.action(entity, action, attributes, extras) 

 

#============================================================================== 

# Collections 

#============================================================================== 

 

 

def update_collection(mixin, old_entities, new_entities, registry, extras): 

    ''' 

    Updates a Collection of Mixin. If not present in the current collections 

    entities will be added to the collection (aka. assigned the Mixin). 

 

    mixin -- The mixin which defines the collection. 

    old_entities -- The entities which are in the collection to date. 

    new_entities -- The entities which should be added to the collection. 

    registry -- The registry used for this process. 

    extras -- Any extra arguments which are defined by the user. 

    ''' 

    if not isinstance(mixin, Mixin): 

        raise AttributeError('This operation is only supported on Collections' 

                             + ' of Mixins.') 

    for entity in unique(new_entities, old_entities): 

        entity.mixins.append(mixin) 

        backend = registry.get_backend(mixin, extras) 

        backend.create(entity, extras) 

    del new_entities 

 

 

def replace_collection(mixin, old_entities, new_entities, registry, extras): 

    ''' 

    Replaces a Collection of Mixin. If not present in the current collections 

    entities will be added to the collection (aka. assigned the Mixin). If old 

    entities are not present in the new collection the mixin will be removed 

    from them. 

 

    mixin -- The mixin which defines the collection. 

    old_entities -- The entities which are in the collection to date. 

    new_entities -- The new collection of entities. 

    registry -- The registry used for this process. 

    extras -- Any extra arguments which are defined by the user. 

    ''' 

    if not isinstance(mixin, Mixin): 

        raise AttributeError('This operation is only supported on Collections' 

                             + ' of Mixins.') 

    for entity in unique(new_entities, old_entities): 

        entity.mixins.append(mixin) 

        backend = registry.get_backend(mixin, extras) 

        backend.create(entity, extras) 

    for entity in unique(old_entities, new_entities): 

        backend = registry.get_backend(mixin, extras) 

        backend.delete(entity, extras) 

        entity.mixins.remove(mixin) 

    del new_entities 

 

 

def delete_from_collection(mixin, entities, registry, extras): 

    ''' 

    Removes entities from a collection by removing the mixin from their list. 

 

    mixin -- The mixin which defines the collection. 

    entities -- The entities which are to be removed. 

    registry -- The registry used for this process. 

    extras -- Any extra arguments which are defined by the user. 

    ''' 

    if not isinstance(mixin, Mixin): 

        raise AttributeError('This operation is only supported on Collections' 

                             + ' of Mixins.') 

 

    for entity in intersect(entities, registry.get_resources(extras)): 

        backend = registry.get_backend(mixin, extras) 

        backend.delete(entity, extras) 

        entity.mixins.remove(mixin) 

 

 

def get_entities_under_path(path, registry, extras): 

    ''' 

    Return all entities which fall under a path. 

 

    If the path is in locations return all entities of the kind which defines 

    the location. 

 

    If the path is just a path return all children. 

 

    path -- The path under which to look... 

    registry -- The registry used for this process. 

    extras -- Any extra arguments which are defined by the user. 

    ''' 

    result = [] 

    if registry.get_category(path, extras) is None: 

        for res in registry.get_resources(extras): 

            if not res.identifier.find(path): 

                result.append(res) 

        return result 

    else: 

        cat = registry.get_category(path, extras) 

        for res in registry.get_resources(extras): 

            if cat == res.kind or cat in res.mixins: 

                result.append(res) 

        return result 

 

 

def filter_entities(entities, categories, attributes): 

    ''' 

    Filters a set of entities and return those who match the given categories 

    and attributes. 

 

    entities -- The entities which are to be filtered. 

    categories -- Categories which must be present in the entity. 

    attributes -- Attributes which must match with the entity's attrs. 

    ''' 

    result = [] 

    if len(categories) == 0 and len(attributes.keys()) == 0: 

        return entities 

 

    for entity in entities: 

        indy = 0 

        if entity.kind in categories: 

            indy += 1 

        if len(intersect(categories, entity.mixins)): 

            indy += 1 

        for attr in intersect(attributes.keys(), entity.attributes.keys()): 

            if entity.attributes[attr] == attributes[attr]: 

                indy += 3 

 

        if len(categories) > 0 and len(attributes.keys()) == 0 and indy >= 1: 

            result.append(entity) 

        elif len(categories) == 0 and len(attributes.keys()) > 0 and indy == 3: 

            result.append(entity) 

        elif len(categories) > 0 and len(attributes.keys()) > 0 and indy >= 4: 

            result.append(entity) 

 

    return result 

 

#============================================================================== 

# Query Interface 

#============================================================================== 

 

 

def filter_categories(categories, registry, extras): 

    ''' 

    Filter the categories. Only those requested should be added to the 

    resulting list. 

 

    categories -- The list of categories to filter against. 

    registry -- The registry used for this process. 

    extras -- Passed on extra object. 

    ''' 

    if not len(categories): 

        return registry.get_categories(extras) 

 

    result = [] 

    for cat in registry.get_categories(extras): 

        if cat in categories: 

            result.append(cat) 

    return result 

 

 

def append_mixins(mixins, registry, extras): 

    ''' 

    Add a mixin to the service. 

 

    mixins -- The mixins which are to be added. 

    registry -- The registry used for this process. 

    extras -- Passed on extra object. 

    ''' 

    for mixin in mixins: 

        if not isinstance(mixin, Mixin): 

            raise AttributeError('Needs to be of type Mixin.') 

        if registry.get_category(mixin.location, extras): 

            raise AttributeError('Location overlaps with existing one.') 

 

        try: 

            registry.get_backend(mixin, extras) 

        except AttributeError: 

            pass 

        else: 

            raise AttributeError('Category with same term, scheme already' + 

                                 ' exists.') 

 

        registry.set_backend(mixin, UserDefinedMixinBackend(), extras) 

 

 

def remove_mixins(mixins, registry, extras): 

    ''' 

    Remove a mixin from the service. 

 

    mixins -- The mixin which are to be removed. 

    registry -- The registry used for this process. 

    extras -- Any extra arguments which are defined by the user. 

    ''' 

    for mixin in mixins: 

        if not isinstance(mixin, Mixin): 

            raise AttributeError('Needs to be of type Mixin.') 

 

        try: 

            backend = registry.get_backend(mixin, extras) 

        except AttributeError: 

            raise HTTPError(400, 'This Mixin is not registered!') 

 

        if not isinstance(backend, UserDefinedMixinBackend): 

            raise HTTPError(403, 'This Mixin cannot be deleted!') 

 

        entities = get_entities_under_path(mixin.location, registry, extras) 

        for entity in entities: 

            entity.mixins.remove(mixin) 

        registry.delete_mixin(mixin, extras) 

        del mixin 

 

#============================================================================== 

# Convenient stuff 

#============================================================================== 

 

 

def create_id(kind): 

    ''' 

    Create a key with the hierarchy of the entity encapsulated. 

 

    kind -- The kind which this id should be created for. 

    ''' 

    key = kind.location + str(uuid.uuid4()) 

    return key 

 

 

def intersect(list_a, list_b): 

    ''' 

    Returns the intersection of two lists. 

 

    list_a -- The first list. 

    list_b -- Another list. 

    ''' 

    if len(list_a) > 0 and len(list_b) > 0: 

        return list(set(list_a) & set(list_b)) 

    else: 

        return list() 

 

 

def unique(list_a, list_b): 

    ''' 

    Returns a list of elements which are only in list_a. 

 

    list_a -- The list to look into for unique elements. 

    list_b -- Ths list the verify against. 

    ''' 

    return [item for item in list_a if item not in list_b]