Started implementing authentication
[snf-occi] / snf-occi-server.py
1 #!/usr/bin/env python
2
3 from kamaki.clients.compute import ComputeClient
4 from kamaki.clients.cyclades import CycladesClient
5 from kamaki.config  import Config
6
7 from occi.core_model import Mixin
8 from occi.backend import ActionBackend, KindBackend, MixinBackend
9 from occi.extensions.infrastructure import COMPUTE, START, STOP, SUSPEND, RESTART, RESOURCE_TEMPLATE, OS_TEMPLATE
10
11 from occi.wsgi import Application
12
13 from wsgiref.simple_server import make_server
14 from wsgiref.validate import validator
15
16
17 class MyBackend(KindBackend, ActionBackend):
18     '''
19     An very simple abstract backend which handles update and replace for
20     attributes. Support for links and mixins would need to added.
21     '''
22
23     def update(self, old, new, extras):
24         # here you can check what information from new_entity you wanna bring
25         # into old_entity
26
27         # trigger your hypervisor and push most recent information
28         print('Updating a resource with id: ' + old.identifier)
29         for item in new.attributes.keys():
30             old.attributes[item] = new.attributes[item]
31
32     def replace(self, old, new, extras):
33         print('Replacing a resource with id: ' + old.identifier)
34         old.attributes = {}
35         for item in new.attributes.keys():
36             old.attributes[item] = new.attributes[item]
37         old.attributes['occi.compute.state'] = 'inactive'
38
39
40 class ComputeBackend(MyBackend):
41     '''
42     Backend for Cyclades/Openstack compute instances
43     '''
44
45     def create(self, entity, extras):
46     
47         for mixin in entity.mixins:
48             if mixin.related[0].term == 'os_tpl':
49                 image = mixin
50                 image_id = mixin.attributes['occi.core.id']
51             if mixin.related[0].term == 'resource_tpl':
52                 flavor = mixin
53                 flavor_id = mixin.attributes['occi.core.id']
54                 
55         entity.attributes['occi.compute.state'] = 'active'
56         entity.actions = [STOP, SUSPEND, RESTART]
57
58         #Registry identifier is the uuid key occi.handler assigns
59         #attribute 'occi.core.id' will be the snf-server id
60
61         snf = ComputeClient(Config())
62         vm_name = entity.attributes['occi.compute.hostname']
63         info = snf.create_server(vm_name, flavor_id, image_id)
64         entity.attributes['occi.core.id'] = str(info['id'])
65         entity.attributes['occi.compute.cores'] = flavor.attributes['occi.compute.cores']
66         entity.attributes['occi.compute.memory'] = flavor.attributes['occi.compute.memory']
67
68     def retrieve(self, entity, extras):
69         
70         # triggering cyclades to retrieve up to date information
71         snf = ComputeClient(Config())
72
73         vm_id = int(entity.attributes['occi.core.id'])
74         vm_info = snf.get_server_details(vm_id)
75         vm_state = vm_info['status']
76         
77         status_dict = {'ACTIVE' : 'active',
78                        'STOPPED' : 'inactive',
79                        'ERROR' : 'inactive',
80                        'BUILD' : 'inactive',
81                        'DELETED' : 'inactive',
82                        }
83         
84         entity.attributes['occi.compute.state'] = status_dict[vm_state]
85
86         if entity.attributes['occi.compute.state'] == 'inactive':
87             entity.actions = [START]
88         if entity.attributes['occi.compute.state'] == 'active': 
89             entity.actions = [STOP, SUSPEND, RESTART]
90         if entity.attributes['occi.compute.state'] == 'suspended':
91             entity.actions = [START]
92
93
94     def delete(self, entity, extras):
95
96         # delete vm with vm_id = entity.attributes['occi.core.id']
97         snf = ComputeClient(Config())
98         vm_id = int(entity.attributes['occi.core.id'])
99         snf.delete_server(vm_id)
100
101
102     def action(self, entity, action, extras):
103         
104         client = CycladesClient(Config())
105         vm_id = int(entity.attributes['occi.core.id'])
106
107         if action not in entity.actions:
108             raise AttributeError("This action is currently no applicable.")
109
110         elif action == START:
111             print "Starting VM"
112             client.start_server(vm_id)
113
114
115         elif action == STOP:
116             print "Stopping VM"
117             client.shutdown_server(vm_id)
118             
119         elif action == RESTART:
120             print "Restarting VM"
121             snf.reboot_server(vm_id)
122
123
124         elif action == SUSPEND:
125             #TODO VM suspending
126             print "Suspending VM"
127
128
129 class MyAPP(Application):
130     '''
131     An OCCI WSGI application.
132     '''
133
134     def __call__(self, environ, response):
135
136         token =  environ['HTTP_AUTH_TOKEN']
137
138         # token will be represented in self.extras
139
140         return self._call_occi(environ, response, token)
141
142 if __name__ == '__main__':
143
144     APP = MyAPP()
145     COMPUTE_BACKEND = ComputeBackend()
146
147     APP.register_backend(COMPUTE, COMPUTE_BACKEND)
148     APP.register_backend(START, COMPUTE_BACKEND)
149     APP.register_backend(STOP, COMPUTE_BACKEND)
150     APP.register_backend(RESTART, COMPUTE_BACKEND)
151     APP.register_backend(SUSPEND, COMPUTE_BACKEND)
152     APP.register_backend(RESOURCE_TEMPLATE, MixinBackend())
153     APP.register_backend(OS_TEMPLATE, MixinBackend())
154     
155     snf = ComputeClient(Config())
156     images = snf.list_images()
157     for image in images:
158         IMAGE_ATTRIBUTES = {'occi.core.id': str(image['id'])}
159         IMAGE = Mixin("http://schemas.ogf.org/occi/infrastructure#", str(image['name']), [OS_TEMPLATE], attributes = IMAGE_ATTRIBUTES)
160         APP.register_backend(IMAGE, MixinBackend())
161
162     flavors = snf.list_flavors()
163     for flavor in flavors:
164         FLAVOR_ATTRIBUTES = {'occi.core.id': flavor['id'],
165                              'occi.compute.cores': snf.get_flavor_details(flavor['id'])['cpu'],
166                              'occi.compute.memory': snf.get_flavor_details(flavor['id'])['ram'],
167                              'occi.storage.size': snf.get_flavor_details(flavor['id'])['disk'],
168                              }
169         FLAVOR = Mixin("http://schemas.ogf.org/occi/infrastructure#", str(flavor['name']), [RESOURCE_TEMPLATE], attributes = FLAVOR_ATTRIBUTES)
170         APP.register_backend(FLAVOR, MixinBackend())
171
172  
173     VALIDATOR_APP = validator(APP)
174     HTTPD = make_server('', 8888, VALIDATOR_APP)
175     HTTPD.serve_forever()
176