aboutsummaryrefslogtreecommitdiffstats
path: root/sdv/docker/sdvmodel/resource-estimation/server
blob: bae978196131a74dc0643e37a742111605f9fcfb (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
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
#!/usr/bin/env python3

# Copyright 2020 Spirent Communications, University Of Delhi.
#
# 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.


"""
Server
"""


import logging
import os
import sys
import copy
import json
from tornado.web import Application
from tornado.ioloop import IOLoop
import tornado.concurrent
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.log
import jinja2

# SOF: 11124247: Massey101 and Corey Klein
class StreamToLogger():
    """
    file-like stream object that redirects writes to a logger instance.
    """
    def __init__(self, logger, log_level=logging.INFO):
        self.logger = logger
        self.log_level = log_level
        self.linebuf = ''

    def write(self, buf):
        """
        write logs
        """
        temp_linebuf = self.linebuf + buf
        self.linebuf = ''
        for line in temp_linebuf.splitlines(True):
            # From the io.TextIOWrapper docs:
            #   On output, if newline is None, any '\n' characters written
            #   are translated to the system default line separator.
            # By default sys.stdout.write() expects '\n' newlines and then
            # translates them so this is still cross platform.
            if line[-1] == '\n':
                self.logger.log(self.log_level, line.rstrip())
            else:
                self.linebuf += line

    def flush(self):
        """
        flush the buffer
        """
        if self.linebuf != '':
            self.logger.log(self.log_level, self.linebuf.rstrip())
        self.linebuf = ''



class Server():
    """
    Server
    """
    # pylint: disable=too-many-instance-attributes

    def __init__(self, hw_profile):
        self.vcpus = hw_profile['vcpus']
        self.numas = hw_profile['numas']
        self.numa_vcpu_map = []
        self.sriov_support = False
        self.hosted_vnfs = []
        for count in range(int(self.numas)):
            self.numa_vcpu_map.append(hw_profile['numa'
                                                 +str(count)
                                                 +'_cpus_4vnfs'])
        self.create_numa_sriov_map(hw_profile['nics'])
        self.zone = 'default'
        self.cpu_isolation = hw_profile['cpu_isol_set']
        self.available_cpu_map = self.numa_vcpu_map

    def create_numa_sriov_map(self, nics):
        """
        Search for all sriov and nonsriov numas
        """
        self.sriov_numas = []
        self.nonsriov_numas = []
        for nic in nics:
            if nic['type'] == 'sriov':
                self.sriov_support = True
                if nic['numa'] not in self.sriov_numas:
                    self.sriov_numas.append(int(nic['numa']))
            else:
                if nic['numa'] not in self.sriov_numas:
                    self.nonsriov_numas.append(int(nic['numa']))

    def dump_profile(self):
        """
        Print Server Profile
        """
        print("The number of vCPUs: %s" %self.vcpus)
        print("Number of NUMA nodes on this server: %s" %self.numas)
        print("vCPUs available for the application in each NUMA: %s" %self.numa_vcpu_map)
        print("SRIOV Support? %s" %self.sriov_support)
        print("The Zone this server belongs to: %s" %self.zone)
        print("vCPUs Isolated: %s" %self.cpu_isolation)
        print("Numa to which SRIOV Nics belogs to: %s" %str(self.sriov_numas))

class Deployment():
    """
    Model deployment
    """
    def __init__(self, rack_count, hw_profile):
        self.server_list = []
        self.total_servers = 0
        self.hw_profile = hw_profile
        self.rack_count = rack_count
        self.server_zones = {}

    def create_deployment(self, vnf_profiles):
        """
        Understand zones.
        """
        zones = []
        for vnf in vnf_profiles:
            if vnf['availability_zone'] not in zones:
                zones.append(vnf['availability_zone'])
        # print(zones)
        for zone in zones:
            for vnf in vnf_profiles:
                if zone == vnf['availability_zone']:
                    for count in range(int(vnf['num_of_vnfs'])):
                        self.deploy(vnf, count)
            self.server_zones[zone] = copy.deepcopy(self.server_list)
            self.total_servers += len(self.server_list)
            self.server_list.clear()

    def deploy(self, vnf, suffix):
        """
        Understand deployment
        """
        # pylint: disable=too-many-branches

        deploy = False
        # If no servers, just do the deployment there and apped it.
        if len(self.server_list) == 0:
            server = Server(self.hw_profile)
            for cnt in  range(len(server.available_cpu_map)):
                if int(server.available_cpu_map[cnt]) >= int(vnf['vcpus']):
                    if not ((vnf['sriov_support'] == 'yes' and cnt not in server.sriov_numas) or\
                        (vnf['sriov_support'] == 'no' and cnt not in server.nonsriov_numas)):
                        server.available_cpu_map[cnt] = str(
                            int(server.available_cpu_map[cnt]) - int(vnf['vcpus']))
                        deploy = True
                        server.hosted_vnfs.append({'vnf':vnf['profile_name'] +\
                                                   str(suffix), 'numa': cnt})
                        self.server_list.append(server)
                        return
            if not deploy:
                print("The existing hardware profile is not Suitable")
                sys.exit()
        # Servers already exist. Check if any eserver can accommodate the vnf:
        for server in self.server_list:
            # Check if SRIOV support is required for VNF and server supports
            # Check if cpus are available in any of the numas
            for cnt in  range(len(server.available_cpu_map)):
                if int(server.available_cpu_map[cnt]) >= int(vnf['vcpus']):
                    if not ((vnf['sriov_support'] == 'yes' and cnt not in server.sriov_numas) or\
                        (vnf['sriov_support'] == 'no' and cnt not in server.nonsriov_numas)):
                        server.available_cpu_map[cnt] = str(int(server.available_cpu_map[cnt])
                                                            - int(vnf['vcpus']))
                        deploy = True
                        server.hosted_vnfs.append({'vnf':vnf['profile_name'] +\
                                                   str(suffix), 'numa': cnt})
                        return
        # We need to create new server, do deployment there and append it the list
        if not deploy:
            server = Server(self.hw_profile)
            for cnt in  range(len(server.available_cpu_map)):
                if int(server.available_cpu_map[cnt]) >= int(vnf['vcpus']):
                    if not ((vnf['sriov_support'] == 'yes' and cnt not in server.sriov_numas) or\
                        (vnf['sriov_support'] == 'no' and cnt not in server.nonsriov_numas)):
                        server.available_cpu_map[cnt] = str(
                            int(server.available_cpu_map[cnt]) - int(vnf['vcpus']))
                        deploy = True
                        server.hosted_vnfs.append({'vnf':vnf['profile_name'] +\
                                                  str(suffix), 'numa': cnt})
                        self.server_list.append(server)
                        return
            if not deploy:
                print("The existing hardware profile is not Suitable")
                sys.exit()

    def display_deployment(self):
        """
        Print Deployment Report
        """
        print("Number of servers used %d" % self.total_servers)
        print("------------------------------------------------")
        count = 0
        for zone, server_list in self.server_zones.items():
            print("SERVERS IN AVAILABILITY ZONE: %s" %(zone))
            print("------------------------------------------------")
            for server in server_list:
                print("Server ID: " + str(count))
                for vnf in server.hosted_vnfs:
                    print("VNF: " + vnf['vnf'] + "  NUMA: " + str(vnf['numa']))
                count = count + 1
                print("------------------------------------------------")

    def get_deployment(self):
        """
        Returns servers and zones
        """
        return self.total_servers, self.server_zones


# pylint: disable=W0223

class Estimate(tornado.web.RequestHandler):
    """
    Resource estimator
    """
    # def set_default_headers(self):
    #     self.set_header('Content-Type', 'application/json')

    def post(self):
        """
        Server Resource Modelling Report
        """
        model = {}
        config = self.get_argument('config', None)
        data = json.loads(config)

        vnf_profiles = (data['vnf_profiles'])
        hw_profile = (data['hardware_profile'])
        model['vnf_profiles'] = vnf_profiles
        print("--------- Resource Modelling Report ------------")
        print("------------------------------------------------")
        print("The VNFs:")
        for profile in vnf_profiles:
            print(profile['profile_name'])
        print("------------------------------------------------")
        print("The Compute-Server Profile:")
        server = Server(hw_profile)
        server.dump_profile()
        model['server'] = hw_profile
        print("------------------------------------------------")
        deployment = Deployment(2, hw_profile)
        deployment.create_deployment(vnf_profiles)
        deployment.display_deployment()
        count, placement = deployment.get_deployment()
        model['deployment_count'] = count
        model['deployment'] = placement
        loader = jinja2.FileSystemLoader(searchpath="template/")
        jenv = jinja2.Environment(loader=loader)
        template = jenv.get_template('report.html')
        htmlout = template.render(model=model)

        self.finish(htmlout)


class HomeHandler(tornado.web.RequestHandler):
    """
    Handler for '/' endpoint
    """
    def get(self):
        """
        Server Home Page
        """
        self.render('/website/index.html')



def server_main_block():
    """
    Main Function
    """

    app = Application([('/validate', Estimate),
                       ('/', HomeHandler),
                       ('/(.*)', tornado.web.StaticFileHandler, {'path' : '/website'})])

    # Cli Config
    tornado.options.define("port", default=80, help="run on the given port", type=int)
    tornado.options.parse_command_line()


    # Server Config
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(tornado.options.options.port)

    est_file = "/tmp/estimate.txt"
    if os.path.exists(est_file):
        os.remove(est_file)

    # Logging
    logging.basicConfig(
        level=logging.DEBUG,
        format='%(message)s',
        filename=est_file,
        filemode='a'
    )

    stdout_logger = logging.getLogger('STDOUT')
    sys.stdout = StreamToLogger(stdout_logger, logging.INFO)

    stderr_logger = logging.getLogger('STDERR')
    sys.stderr = StreamToLogger(stderr_logger, logging.ERROR)

    tornado.log.enable_pretty_logging()

    # Tornado's event loop handles it from here
    print("# Servering.... \n [Ctrl + C] to quit")

    try:
        tornado.ioloop.IOLoop.instance().start()
    except KeyboardInterrupt:
        tornado.ioloop.IOLoop.instance().stop()

    # start
    IOLoop.instance().start()


if __name__ == "__main__":
    server_main_block()