update from RIFT as of 696b75d2fe9fb046261b08c616f1bcf6c0b54a9b second try
[osm/SO.git] / rwcal / rift / cal / server / server.py
1 """
2 #
3 # Copyright 2016 RIFT.IO Inc
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16 #
17
18 @file cal_server.py
19 @author Austin Cormier(austin.cormier@riftio.com)
20 @author Varun Prasad(varun.prasad@riftio.com)
21 @date 2016-06-14
22 """
23
24 import asyncio
25 import logging
26 import os
27 import signal
28 import sys
29
30 import tornado
31 import tornado.httpserver
32 import tornado.web
33 import tornado.platform.asyncio
34
35 import gi
36 gi.require_version('RwcalYang', '1.0')
37 gi.require_version('RwCal', '1.0')
38 gi.require_version('RwLog', '1.0')
39 gi.require_version('RwTypes', '1.0')
40 from gi.repository import (
41 RwcalYang,
42 RwLog
43 )
44
45 import rw_peas
46 import rift.tasklets
47 import rift.rwcal.cloudsim.net
48 import rift.rwcal.cloudsim.lvm as lvm
49 import rift.rwcal.cloudsim.lxc as lxc
50 import rift.rwcal.cloudsim.shell as shell
51
52 from . import app
53
54 logger = logging.getLogger(__name__)
55
56 if sys.version_info < (3, 4, 4):
57 asyncio.ensure_future = asyncio.async
58
59
60 class CalServer():
61 HTTP_PORT = 9002
62 cal_interface = None
63
64 @staticmethod
65 def verify_requirements(log):
66 """
67 Check if all the requirements are met
68 1. bridgeutils should be installed
69 2. The user should be root
70 """
71 try:
72 shell.command('/usr/sbin/brctl show')
73 except shell.ProcessError:
74 log.exception('/usr/sbin/brctl command not found, please install '
75 'bridge-utils (yum install bridge-utils)')
76 sys.exit(1)
77
78 if os.geteuid() != 0:
79 log.error("User should be root to start the server.")
80 sys.exit(1)
81
82 def __init__(self, logging_level=logging.DEBUG):
83 self.app = None
84 self.server = None
85 self.log_hdl = RwLog.Ctx.new("a")
86 self.log = logger
87 self.log.setLevel(logging_level)
88
89 def get_cal_interface(self):
90 self.log.debug("Creating CAL interface.")
91 if CalServer.cal_interface is None:
92 plugin = rw_peas.PeasPlugin('rwcal_cloudsim', 'RwCal-1.0')
93 engine, info, extension = plugin()
94
95 CalServer.cal_interface = plugin.get_interface("Cloud")
96 CalServer.cal_interface.init(self.log_hdl)
97
98 return CalServer.cal_interface
99
100 def cleanup(self):
101 self.log.info("Cleaning up resources and backing store.")
102 for container in lxc.containers():
103 self.log.debug("Stopping {}".format(container))
104 lxc.stop(container)
105
106 for container in lxc.containers():
107 lxc.destroy(container)
108
109 lvm.destroy('rift')
110
111
112 def start(self):
113 """Start the server."""
114
115 cal = self.get_cal_interface()
116 account = RwcalYang.YangData_RwProject_Project_CloudAccounts_CloudAccountList(account_type="cloudsim")
117
118 tornado.platform.asyncio.AsyncIOMainLoop().install()
119 loop = asyncio.get_event_loop()
120
121 self.app = app.CalProxyApp(self.log, loop, cal, account)
122 self.server = tornado.httpserver.HTTPServer(self.app)
123
124 self.log.info("Starting Cal Proxy Http Server on port %s",
125 CalServer.HTTP_PORT)
126 self.server.listen(CalServer.HTTP_PORT)
127
128 def startup():
129 self.log.info("Creating a default network")
130 rift.rwcal.cloudsim.net.virsh_initialize_default()
131 self.log.info("Creating backing store")
132 lvm.create('rift')
133
134 loop.add_signal_handler(signal.SIGHUP, self.cleanup)
135 loop.add_signal_handler(signal.SIGTERM, self.cleanup)
136
137 try:
138 loop.run_in_executor(None, startup)
139 loop.run_forever()
140 except KeyboardInterrupt:
141 self.cleanup()
142 except Exception as exc:
143 self.log.exception(exc)
144
145
146 def stop(self):
147 try:
148 self.server.stop()
149 except Exception:
150 self.log.exception("Caught Exception in LP stop:", sys.exc_info()[0])
151 raise