2 # -*- coding: utf-8 -*-
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
8 # http://www.apache.org/licenses/LICENSE-2.0
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
21 import osm_nbi
.html_out
as html
23 import logging
.handlers
27 from osm_nbi
.authconn
import AuthException
, AuthconnException
28 from osm_nbi
.auth
import Authenticator
29 from osm_nbi
.engine
import Engine
, EngineException
30 from osm_nbi
.subscriptions
import SubscriptionThread
31 from osm_nbi
.validation
import ValidationError
32 from osm_common
.dbbase
import DbException
33 from osm_common
.fsbase
import FsException
34 from osm_common
.msgbase
import MsgException
35 from http
import HTTPStatus
36 from codecs
import getreader
37 from os
import environ
, path
38 from osm_nbi
import version
as nbi_version
, version_date
as nbi_version_date
40 __author__
= "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
42 __version__
= "0.1.3" # file version, not NBI version
43 version_date
= "Aug 2019"
45 database_version
= '1.2'
46 auth_database_version
= '1.0'
47 nbi_server
= None # instance of Server class
48 subscription_thread
= None # instance of SubscriptionThread class
52 North Bound Interface (O: OSM specific; 5,X: SOL005 not implemented yet; O5: SOL005 implemented)
53 URL: /osm GET POST PUT DELETE PATCH
55 /ns_descriptors_content O O
61 /artifacts[/<artifactPath>] O
69 /vnf_packages_content O O
73 /package_content O5 O5
76 /artifacts[/<artifactPath>] O5
81 /ns_instances_content O O
93 /vnf_instances (also vnfrs for compatibility) O
109 /vim_accounts (also vims for compatibility) O O
117 /netslice_templates_content O O
119 /netslice_templates O O
123 /artifacts[/<artifactPath>] O
125 /<subscriptionId> X X
128 /netslice_instances_content O O
129 /<SliceInstanceId> O O
130 /netslice_instances O O
131 /<SliceInstanceId> O O
136 /<nsiLcmOpOccId> O O O
138 /<subscriptionId> X X
141 Follows SOL005 section 4.3.2 It contains extra METHOD to override http method, FORCE to force.
142 simpleFilterExpr := <attrName>["."<attrName>]*["."<op>]"="<value>[","<value>]*
143 filterExpr := <simpleFilterExpr>["&"<simpleFilterExpr>]*
144 op := "eq" | "neq" (or "ne") | "gt" | "lt" | "gte" | "lte" | "cont" | "ncont"
146 For filtering inside array, it must select the element of the array, or add ANYINDEX to apply the filtering over any
147 item of the array, that is, pass if any item of the array pass the filter.
148 It allows both ne and neq for not equal
149 TODO: 4.3.3 Attribute selectors
150 all_fields, fields=x,y,.., exclude_default, exclude_fields=x,y,...
151 (none) … same as “exclude_default”
152 all_fields … all attributes.
153 fields=<list> … all attributes except all complex attributes with minimum cardinality of zero that are not
154 conditionally mandatory, and that are not provided in <list>.
155 exclude_fields=<list> … all attributes except those complex attributes with a minimum cardinality of zero that
156 are not conditionally mandatory, and that are provided in <list>.
157 exclude_default … all attributes except those complex attributes with a minimum cardinality of zero that are not
158 conditionally mandatory, and that are part of the "default exclude set" defined in the present specification for
159 the particular resource
160 exclude_default and include=<list> … all attributes except those complex attributes with a minimum cardinality
161 of zero that are not conditionally mandatory and that are part of the "default exclude set" defined in the
162 present specification for the particular resource, but that are not part of <list>
163 Additionally it admits some administrator values:
164 FORCE: To force operations skipping dependency checkings
165 ADMIN: To act as an administrator or a different project
166 PUBLIC: To get public descriptors or set a descriptor as public
167 SET_PROJECT: To make a descriptor available for other project
169 Header field name Reference Example Descriptions
170 Accept IETF RFC 7231 [19] application/json Content-Types that are acceptable for the response.
171 This header field shall be present if the response is expected to have a non-empty message body.
172 Content-Type IETF RFC 7231 [19] application/json The MIME type of the body of the request.
173 This header field shall be present if the request has a non-empty message body.
174 Authorization IETF RFC 7235 [22] Bearer mF_9.B5f-4.1JqM The authorization token for the request.
175 Details are specified in clause 4.5.3.
176 Range IETF RFC 7233 [21] 1000-2000 Requested range of bytes from a file
177 Header field name Reference Example Descriptions
178 Content-Type IETF RFC 7231 [19] application/json The MIME type of the body of the response.
179 This header field shall be present if the response has a non-empty message body.
180 Location IETF RFC 7231 [19] http://www.example.com/vnflcm/v1/vnf_instances/123 Used in redirection, or when a
181 new resource has been created.
182 This header field shall be present if the response status code is 201 or 3xx.
183 In the present document this header field is also used if the response status code is 202 and a new resource was
185 WWW-Authenticate IETF RFC 7235 [22] Bearer realm="example" Challenge if the corresponding HTTP request has not
186 provided authorization, or error details if the corresponding HTTP request has provided an invalid authorization
188 Accept-Ranges IETF RFC 7233 [21] bytes Used by the Server to signal whether or not it supports ranges for
190 Content-Range IETF RFC 7233 [21] bytes 21010-47021/ 47022 Signals the byte range that is contained in the
191 response, and the total length of the file.
192 Retry-After IETF RFC 7231 [19] Fri, 31 Dec 1999 23:59:59 GMT
195 valid_query_string
= ("ADMIN", "SET_PROJECT", "FORCE", "PUBLIC")
196 # ^ Contains possible administrative query string words:
197 # ADMIN=True(by default)|Project|Project-list: See all elements, or elements of a project
198 # (not owned by my session project).
199 # PUBLIC=True(by default)|False: See/hide public elements. Set/Unset a topic to be public
200 # FORCE=True(by default)|False: Force edition/deletion operations
201 # SET_PROJECT=Project|Project-list: Add/Delete the topic to the projects portfolio
203 valid_url_methods
= {
204 # contains allowed URL and methods, and the role_permission name
207 "tokens": {"METHODS": ("GET", "POST", "DELETE"),
208 "ROLE_PERMISSION": "tokens:",
209 "<ID>": {"METHODS": ("GET", "DELETE"),
210 "ROLE_PERMISSION": "tokens:id:"
213 "users": {"METHODS": ("GET", "POST"),
214 "ROLE_PERMISSION": "users:",
215 "<ID>": {"METHODS": ("GET", "POST", "DELETE", "PATCH", "PUT"),
216 "ROLE_PERMISSION": "users:id:"
219 "projects": {"METHODS": ("GET", "POST"),
220 "ROLE_PERMISSION": "projects:",
221 "<ID>": {"METHODS": ("GET", "DELETE", "PUT"),
222 "ROLE_PERMISSION": "projects:id:"}
224 "roles": {"METHODS": ("GET", "POST"),
225 "ROLE_PERMISSION": "roles:",
226 "<ID>": {"METHODS": ("GET", "POST", "DELETE", "PUT"),
227 "ROLE_PERMISSION": "roles:id:"
230 "vims": {"METHODS": ("GET", "POST"),
231 "ROLE_PERMISSION": "vims:",
232 "<ID>": {"METHODS": ("GET", "DELETE", "PATCH", "PUT"),
233 "ROLE_PERMISSION": "vims:id:"
236 "vim_accounts": {"METHODS": ("GET", "POST"),
237 "ROLE_PERMISSION": "vim_accounts:",
238 "<ID>": {"METHODS": ("GET", "DELETE", "PATCH", "PUT"),
239 "ROLE_PERMISSION": "vim_accounts:id:"
242 "wim_accounts": {"METHODS": ("GET", "POST"),
243 "ROLE_PERMISSION": "wim_accounts:",
244 "<ID>": {"METHODS": ("GET", "DELETE", "PATCH", "PUT"),
245 "ROLE_PERMISSION": "wim_accounts:id:"
248 "sdns": {"METHODS": ("GET", "POST"),
249 "ROLE_PERMISSION": "sdn_controllers:",
250 "<ID>": {"METHODS": ("GET", "DELETE", "PATCH", "PUT"),
251 "ROLE_PERMISSION": "sdn_controllers:id:"
258 "pdu_descriptors": {"METHODS": ("GET", "POST"),
259 "ROLE_PERMISSION": "pduds:",
260 "<ID>": {"METHODS": ("GET", "POST", "DELETE", "PATCH", "PUT"),
261 "ROLE_PERMISSION": "pduds:id:"
268 "ns_descriptors_content": {"METHODS": ("GET", "POST"),
269 "ROLE_PERMISSION": "nsds:",
270 "<ID>": {"METHODS": ("GET", "PUT", "DELETE"),
271 "ROLE_PERMISSION": "nsds:id:"
274 "ns_descriptors": {"METHODS": ("GET", "POST"),
275 "ROLE_PERMISSION": "nsds:",
276 "<ID>": {"METHODS": ("GET", "DELETE", "PATCH"),
277 "ROLE_PERMISSION": "nsds:id:",
278 "nsd_content": {"METHODS": ("GET", "PUT"),
279 "ROLE_PERMISSION": "nsds:id:content:",
281 "nsd": {"METHODS": ("GET",), # descriptor inside package
282 "ROLE_PERMISSION": "nsds:id:content:"
284 "artifacts": {"*": {"METHODS": ("GET",),
285 "ROLE_PERMISSION": "nsds:id:nsd_artifact:"
290 "pnf_descriptors": {"TODO": ("GET", "POST"),
291 "<ID>": {"TODO": ("GET", "DELETE", "PATCH"),
292 "pnfd_content": {"TODO": ("GET", "PUT")}
295 "subscriptions": {"TODO": ("GET", "POST"),
296 "<ID>": {"TODO": ("GET", "DELETE")}
302 "vnf_packages_content": {"METHODS": ("GET", "POST"),
303 "ROLE_PERMISSION": "vnfds:",
304 "<ID>": {"METHODS": ("GET", "PUT", "DELETE"),
305 "ROLE_PERMISSION": "vnfds:id:"}
307 "vnf_packages": {"METHODS": ("GET", "POST"),
308 "ROLE_PERMISSION": "vnfds:",
309 "<ID>": {"METHODS": ("GET", "DELETE", "PATCH"), # GET: vnfPkgInfo
310 "ROLE_PERMISSION": "vnfds:id:",
311 "package_content": {"METHODS": ("GET", "PUT"), # package
312 "ROLE_PERMISSION": "vnfds:id:",
313 "upload_from_uri": {"METHODS": (),
315 "ROLE_PERMISSION": "vnfds:id:upload:"
318 "vnfd": {"METHODS": ("GET", ), # descriptor inside package
319 "ROLE_PERMISSION": "vnfds:id:content:"
321 "artifacts": {"*": {"METHODS": ("GET", ),
322 "ROLE_PERMISSION": "vnfds:id:vnfd_artifact:"
327 "subscriptions": {"TODO": ("GET", "POST"),
328 "<ID>": {"TODO": ("GET", "DELETE")}
334 "ns_instances_content": {"METHODS": ("GET", "POST"),
335 "ROLE_PERMISSION": "ns_instances:",
336 "<ID>": {"METHODS": ("GET", "DELETE"),
337 "ROLE_PERMISSION": "ns_instances:id:"
340 "ns_instances": {"METHODS": ("GET", "POST"),
341 "ROLE_PERMISSION": "ns_instances:",
342 "<ID>": {"METHODS": ("GET", "DELETE"),
343 "ROLE_PERMISSION": "ns_instances:id:",
344 "scale": {"METHODS": ("POST",),
345 "ROLE_PERMISSION": "ns_instances:id:scale:"
347 "terminate": {"METHODS": ("POST",),
348 "ROLE_PERMISSION": "ns_instances:id:terminate:"
350 "instantiate": {"METHODS": ("POST",),
351 "ROLE_PERMISSION": "ns_instances:id:instantiate:"
353 "action": {"METHODS": ("POST",),
354 "ROLE_PERMISSION": "ns_instances:id:action:"
358 "ns_lcm_op_occs": {"METHODS": ("GET",),
359 "ROLE_PERMISSION": "ns_instances:opps:",
360 "<ID>": {"METHODS": ("GET",),
361 "ROLE_PERMISSION": "ns_instances:opps:id:"
364 "vnfrs": {"METHODS": ("GET",),
365 "ROLE_PERMISSION": "vnf_instances:",
366 "<ID>": {"METHODS": ("GET",),
367 "ROLE_PERMISSION": "vnf_instances:id:"
370 "vnf_instances": {"METHODS": ("GET",),
371 "ROLE_PERMISSION": "vnf_instances:",
372 "<ID>": {"METHODS": ("GET",),
373 "ROLE_PERMISSION": "vnf_instances:id:"
380 "netslice_templates_content": {"METHODS": ("GET", "POST"),
381 "ROLE_PERMISSION": "slice_templates:",
382 "<ID>": {"METHODS": ("GET", "PUT", "DELETE"),
383 "ROLE_PERMISSION": "slice_templates:id:", }
385 "netslice_templates": {"METHODS": ("GET", "POST"),
386 "ROLE_PERMISSION": "slice_templates:",
387 "<ID>": {"METHODS": ("GET", "DELETE"),
389 "ROLE_PERMISSION": "slice_templates:id:",
390 "nst_content": {"METHODS": ("GET", "PUT"),
391 "ROLE_PERMISSION": "slice_templates:id:content:"
393 "nst": {"METHODS": ("GET",), # descriptor inside package
394 "ROLE_PERMISSION": "slice_templates:id:content:"
396 "artifacts": {"*": {"METHODS": ("GET",),
397 "ROLE_PERMISSION": "slice_templates:id:content:"
402 "subscriptions": {"TODO": ("GET", "POST"),
403 "<ID>": {"TODO": ("GET", "DELETE")}
409 "netslice_instances_content": {"METHODS": ("GET", "POST"),
410 "ROLE_PERMISSION": "slice_instances:",
411 "<ID>": {"METHODS": ("GET", "DELETE"),
412 "ROLE_PERMISSION": "slice_instances:id:"
415 "netslice_instances": {"METHODS": ("GET", "POST"),
416 "ROLE_PERMISSION": "slice_instances:",
417 "<ID>": {"METHODS": ("GET", "DELETE"),
418 "ROLE_PERMISSION": "slice_instances:id:",
419 "terminate": {"METHODS": ("POST",),
420 "ROLE_PERMISSION": "slice_instances:id:terminate:"
422 "instantiate": {"METHODS": ("POST",),
423 "ROLE_PERMISSION": "slice_instances:id:instantiate:"
425 "action": {"METHODS": ("POST",),
426 "ROLE_PERMISSION": "slice_instances:id:action:"
430 "nsi_lcm_op_occs": {"METHODS": ("GET",),
431 "ROLE_PERMISSION": "slice_instances:opps:",
432 "<ID>": {"METHODS": ("GET",),
433 "ROLE_PERMISSION": "slice_instances:opps:id:",
443 "<ID>": {"METHODS": ("GET",),
444 "ROLE_PERMISSION": "reports:id:",
454 class NbiException(Exception):
456 def __init__(self
, message
, http_code
=HTTPStatus
.METHOD_NOT_ALLOWED
):
457 Exception.__init
__(self
, message
)
458 self
.http_code
= http_code
461 class Server(object):
463 # to decode bytes to str
464 reader
= getreader("utf-8")
468 self
.engine
= Engine()
469 self
.authenticator
= Authenticator(valid_url_methods
, valid_query_string
)
471 def _format_in(self
, kwargs
):
474 if cherrypy
.request
.body
.length
:
475 error_text
= "Invalid input format "
477 if "Content-Type" in cherrypy
.request
.headers
:
478 if "application/json" in cherrypy
.request
.headers
["Content-Type"]:
479 error_text
= "Invalid json format "
480 indata
= json
.load(self
.reader(cherrypy
.request
.body
))
481 cherrypy
.request
.headers
.pop("Content-File-MD5", None)
482 elif "application/yaml" in cherrypy
.request
.headers
["Content-Type"]:
483 error_text
= "Invalid yaml format "
484 indata
= yaml
.load(cherrypy
.request
.body
, Loader
=yaml
.SafeLoader
)
485 cherrypy
.request
.headers
.pop("Content-File-MD5", None)
486 elif "application/binary" in cherrypy
.request
.headers
["Content-Type"] or \
487 "application/gzip" in cherrypy
.request
.headers
["Content-Type"] or \
488 "application/zip" in cherrypy
.request
.headers
["Content-Type"] or \
489 "text/plain" in cherrypy
.request
.headers
["Content-Type"]:
490 indata
= cherrypy
.request
.body
# .read()
491 elif "multipart/form-data" in cherrypy
.request
.headers
["Content-Type"]:
492 if "descriptor_file" in kwargs
:
493 filecontent
= kwargs
.pop("descriptor_file")
494 if not filecontent
.file:
495 raise NbiException("empty file or content", HTTPStatus
.BAD_REQUEST
)
496 indata
= filecontent
.file # .read()
497 if filecontent
.content_type
.value
:
498 cherrypy
.request
.headers
["Content-Type"] = filecontent
.content_type
.value
500 # raise cherrypy.HTTPError(HTTPStatus.Not_Acceptable,
501 # "Only 'Content-Type' of type 'application/json' or
502 # 'application/yaml' for input format are available")
503 error_text
= "Invalid yaml format "
504 indata
= yaml
.load(cherrypy
.request
.body
, Loader
=yaml
.SafeLoader
)
505 cherrypy
.request
.headers
.pop("Content-File-MD5", None)
507 error_text
= "Invalid yaml format "
508 indata
= yaml
.load(cherrypy
.request
.body
, Loader
=yaml
.SafeLoader
)
509 cherrypy
.request
.headers
.pop("Content-File-MD5", None)
514 if cherrypy
.request
.headers
.get("Query-String-Format") == "yaml":
517 for k
, v
in kwargs
.items():
518 if isinstance(v
, str):
523 kwargs
[k
] = yaml
.load(v
, Loader
=yaml
.SafeLoader
)
526 elif k
.endswith(".gt") or k
.endswith(".lt") or k
.endswith(".gte") or k
.endswith(".lte"):
534 elif v
.find(",") > 0:
535 kwargs
[k
] = v
.split(",")
536 elif isinstance(v
, (list, tuple)):
537 for index
in range(0, len(v
)):
542 v
[index
] = yaml
.load(v
[index
], Loader
=yaml
.SafeLoader
)
547 except (ValueError, yaml
.YAMLError
) as exc
:
548 raise NbiException(error_text
+ str(exc
), HTTPStatus
.BAD_REQUEST
)
549 except KeyError as exc
:
550 raise NbiException("Query string error: " + str(exc
), HTTPStatus
.BAD_REQUEST
)
551 except Exception as exc
:
552 raise NbiException(error_text
+ str(exc
), HTTPStatus
.BAD_REQUEST
)
555 def _format_out(data
, token_info
=None, _format
=None):
557 return string of dictionary data according to requested json, yaml, xml. By default json
558 :param data: response to be sent. Can be a dict, text or file
559 :param token_info: Contains among other username and project
560 :param _format: The format to be set as Content-Type if data is a file
563 accept
= cherrypy
.request
.headers
.get("Accept")
565 if accept
and "text/html" in accept
:
566 return html
.format(data
, cherrypy
.request
, cherrypy
.response
, token_info
)
567 # cherrypy.response.status = HTTPStatus.NO_CONTENT.value
569 elif hasattr(data
, "read"): # file object
571 cherrypy
.response
.headers
["Content-Type"] = _format
572 elif "b" in data
.mode
: # binariy asssumig zip
573 cherrypy
.response
.headers
["Content-Type"] = 'application/zip'
575 cherrypy
.response
.headers
["Content-Type"] = 'text/plain'
576 # TODO check that cherrypy close file. If not implement pending things to close per thread next
579 if "application/json" in accept
:
580 cherrypy
.response
.headers
["Content-Type"] = 'application/json; charset=utf-8'
581 a
= json
.dumps(data
, indent
=4) + "\n"
582 return a
.encode("utf8")
583 elif "text/html" in accept
:
584 return html
.format(data
, cherrypy
.request
, cherrypy
.response
, token_info
)
586 elif "application/yaml" in accept
or "*/*" in accept
or "text/plain" in accept
:
588 # if there is not any valid accept, raise an error. But if response is already an error, format in yaml
589 elif cherrypy
.response
.status
>= 400:
590 raise cherrypy
.HTTPError(HTTPStatus
.NOT_ACCEPTABLE
.value
,
591 "Only 'Accept' of type 'application/json' or 'application/yaml' "
592 "for output format are available")
593 cherrypy
.response
.headers
["Content-Type"] = 'application/yaml'
594 return yaml
.safe_dump(data
, explicit_start
=True, indent
=4, default_flow_style
=False, tags
=False,
595 encoding
='utf-8', allow_unicode
=True) # , canonical=True, default_style='"'
598 def index(self
, *args
, **kwargs
):
601 if cherrypy
.request
.method
== "GET":
602 token_info
= self
.authenticator
.authorize()
603 outdata
= token_info
# Home page
605 raise cherrypy
.HTTPError(HTTPStatus
.METHOD_NOT_ALLOWED
.value
,
606 "Method {} not allowed for tokens".format(cherrypy
.request
.method
))
608 return self
._format
_out
(outdata
, token_info
)
610 except (EngineException
, AuthException
) as e
:
611 # cherrypy.log("index Exception {}".format(e))
612 cherrypy
.response
.status
= e
.http_code
.value
613 return self
._format
_out
("Welcome to OSM!", token_info
)
616 def version(self
, *args
, **kwargs
):
617 # TODO consider to remove and provide version using the static version file
619 if cherrypy
.request
.method
!= "GET":
620 raise NbiException("Only method GET is allowed", HTTPStatus
.METHOD_NOT_ALLOWED
)
622 raise NbiException("Invalid URL or query string for version", HTTPStatus
.METHOD_NOT_ALLOWED
)
623 # TODO include version of other modules, pick up from some kafka admin message
624 osm_nbi_version
= {"version": nbi_version
, "date": nbi_version_date
}
625 return self
._format
_out
(osm_nbi_version
)
626 except NbiException
as e
:
627 cherrypy
.response
.status
= e
.http_code
.value
629 "code": e
.http_code
.name
,
630 "status": e
.http_code
.value
,
633 return self
._format
_out
(problem_details
, None)
636 def _format_login(token_info
):
638 Changes cherrypy.request.login to include username/project_name;session so that cherrypy access log will
640 :param token_info: Dictionary with token content
643 cherrypy
.request
.login
= token_info
.get("username", "-")
644 if token_info
.get("project_name"):
645 cherrypy
.request
.login
+= "/" + token_info
["project_name"]
646 if token_info
.get("id"):
647 cherrypy
.request
.login
+= ";session=" + token_info
["id"][0:12]
650 def token(self
, method
, token_id
=None, kwargs
=None):
652 # self.engine.load_dbase(cherrypy.request.app.config)
653 indata
= self
._format
_in
(kwargs
)
654 if not isinstance(indata
, dict):
655 raise NbiException("Expected application/yaml or application/json Content-Type", HTTPStatus
.BAD_REQUEST
)
658 token_info
= self
.authenticator
.authorize()
660 self
._format
_login
(token_info
)
662 outdata
= self
.authenticator
.get_token(token_info
, token_id
)
664 outdata
= self
.authenticator
.get_token_list(token_info
)
665 elif method
== "POST":
667 token_info
= self
.authenticator
.authorize()
671 indata
.update(kwargs
)
672 # This is needed to log the user when authentication fails
673 cherrypy
.request
.login
= "{}".format(indata
.get("username", "-"))
674 outdata
= token_info
= self
.authenticator
.new_token(token_info
, indata
, cherrypy
.request
.remote
)
675 cherrypy
.session
['Authorization'] = outdata
["_id"]
676 self
._set
_location
_header
("admin", "v1", "tokens", outdata
["_id"])
678 self
._format
_login
(token_info
)
680 # cherrypy.response.cookie["Authorization"] = outdata["id"]
681 # cherrypy.response.cookie["Authorization"]['expires'] = 3600
682 elif method
== "DELETE":
683 if not token_id
and "id" in kwargs
:
684 token_id
= kwargs
["id"]
686 token_info
= self
.authenticator
.authorize()
688 self
._format
_login
(token_info
)
689 token_id
= token_info
["_id"]
690 outdata
= self
.authenticator
.del_token(token_id
)
692 cherrypy
.session
['Authorization'] = "logout"
693 # cherrypy.response.cookie["Authorization"] = token_id
694 # cherrypy.response.cookie["Authorization"]['expires'] = 0
696 raise NbiException("Method {} not allowed for token".format(method
), HTTPStatus
.METHOD_NOT_ALLOWED
)
697 return self
._format
_out
(outdata
, token_info
)
700 def test(self
, *args
, **kwargs
):
702 if args
and args
[0] == "help":
703 return "<html><pre>\ninit\nfile/<name> download file\ndb-clear/table\nfs-clear[/folder]\nlogin\nlogin2\n"\
704 "sleep/<time>\nmessage/topic\n</pre></html>"
706 elif args
and args
[0] == "init":
708 # self.engine.load_dbase(cherrypy.request.app.config)
709 self
.engine
.create_admin()
710 return "Done. User 'admin', password 'admin' created"
712 cherrypy
.response
.status
= HTTPStatus
.FORBIDDEN
.value
713 return self
._format
_out
("Database already initialized")
714 elif args
and args
[0] == "file":
715 return cherrypy
.lib
.static
.serve_file(cherrypy
.tree
.apps
['/osm'].config
["storage"]["path"] + "/" + args
[1],
716 "text/plain", "attachment")
717 elif args
and args
[0] == "file2":
718 f_path
= cherrypy
.tree
.apps
['/osm'].config
["storage"]["path"] + "/" + args
[1]
719 f
= open(f_path
, "r")
720 cherrypy
.response
.headers
["Content-type"] = "text/plain"
723 elif len(args
) == 2 and args
[0] == "db-clear":
724 deleted_info
= self
.engine
.db
.del_list(args
[1], kwargs
)
725 return "{} {} deleted\n".format(deleted_info
["deleted"], args
[1])
726 elif len(args
) and args
[0] == "fs-clear":
730 folders
= self
.engine
.fs
.dir_ls(".")
731 for folder
in folders
:
732 self
.engine
.fs
.file_delete(folder
)
733 return ",".join(folders
) + " folders deleted\n"
734 elif args
and args
[0] == "login":
735 if not cherrypy
.request
.headers
.get("Authorization"):
736 cherrypy
.response
.headers
["WWW-Authenticate"] = 'Basic realm="Access to OSM site", charset="UTF-8"'
737 cherrypy
.response
.status
= HTTPStatus
.UNAUTHORIZED
.value
738 elif args
and args
[0] == "login2":
739 if not cherrypy
.request
.headers
.get("Authorization"):
740 cherrypy
.response
.headers
["WWW-Authenticate"] = 'Bearer realm="Access to OSM site"'
741 cherrypy
.response
.status
= HTTPStatus
.UNAUTHORIZED
.value
742 elif args
and args
[0] == "sleep":
745 sleep_time
= int(args
[1])
747 cherrypy
.response
.status
= HTTPStatus
.FORBIDDEN
.value
748 return self
._format
_out
("Database already initialized")
749 thread_info
= cherrypy
.thread_data
751 time
.sleep(sleep_time
)
753 elif len(args
) >= 2 and args
[0] == "message":
755 return_text
= "<html><pre>{} ->\n".format(main_topic
)
757 if cherrypy
.request
.method
== 'POST':
758 to_send
= yaml
.load(cherrypy
.request
.body
, Loader
=yaml
.SafeLoader
)
759 for k
, v
in to_send
.items():
760 self
.engine
.msg
.write(main_topic
, k
, v
)
761 return_text
+= " {}: {}\n".format(k
, v
)
762 elif cherrypy
.request
.method
== 'GET':
763 for k
, v
in kwargs
.items():
764 self
.engine
.msg
.write(main_topic
, k
, yaml
.load(v
), Loader
=yaml
.SafeLoader
)
765 return_text
+= " {}: {}\n".format(k
, yaml
.load(v
), Loader
=yaml
.SafeLoader
)
766 except Exception as e
:
767 return_text
+= "Error: " + str(e
)
768 return_text
+= "</pre></html>\n"
772 "<html><pre>\nheaders:\n args: {}\n".format(args
) +
773 " kwargs: {}\n".format(kwargs
) +
774 " headers: {}\n".format(cherrypy
.request
.headers
) +
775 " path_info: {}\n".format(cherrypy
.request
.path_info
) +
776 " query_string: {}\n".format(cherrypy
.request
.query_string
) +
777 " session: {}\n".format(cherrypy
.session
) +
778 " cookie: {}\n".format(cherrypy
.request
.cookie
) +
779 " method: {}\n".format(cherrypy
.request
.method
) +
780 " session: {}\n".format(cherrypy
.session
.get('fieldname')) +
782 return_text
+= " length: {}\n".format(cherrypy
.request
.body
.length
)
783 if cherrypy
.request
.body
.length
:
784 return_text
+= " content: {}\n".format(
785 str(cherrypy
.request
.body
.read(int(cherrypy
.request
.headers
.get('Content-Length', 0)))))
787 return_text
+= "thread: {}\n".format(thread_info
)
788 return_text
+= "</pre></html>"
792 def _check_valid_url_method(method
, *args
):
794 raise NbiException("URL must contain at least 'main_topic/version/topic'", HTTPStatus
.METHOD_NOT_ALLOWED
)
796 reference
= valid_url_methods
800 if not isinstance(reference
, dict):
801 raise NbiException("URL contains unexpected extra items '{}'".format(arg
),
802 HTTPStatus
.METHOD_NOT_ALLOWED
)
805 reference
= reference
[arg
]
806 elif "<ID>" in reference
:
807 reference
= reference
["<ID>"]
808 elif "*" in reference
:
809 reference
= reference
["*"]
812 raise NbiException("Unexpected URL item {}".format(arg
), HTTPStatus
.METHOD_NOT_ALLOWED
)
813 if "TODO" in reference
and method
in reference
["TODO"]:
814 raise NbiException("Method {} not supported yet for this URL".format(method
), HTTPStatus
.NOT_IMPLEMENTED
)
815 elif "METHODS" in reference
and method
not in reference
["METHODS"]:
816 raise NbiException("Method {} not supported for this URL".format(method
), HTTPStatus
.METHOD_NOT_ALLOWED
)
817 return reference
["ROLE_PERMISSION"] + method
.lower()
820 def _set_location_header(main_topic
, version
, topic
, id):
822 Insert response header Location with the URL of created item base on URL params
829 # Use cherrypy.request.base for absoluted path and make use of request.header HOST just in case behind aNAT
830 cherrypy
.response
.headers
["Location"] = "/osm/{}/{}/{}/{}".format(main_topic
, version
, topic
, id)
834 def _extract_query_string_operations(kwargs
, method
):
840 query_string_operations
= []
842 for qs
in ("FORCE", "PUBLIC", "ADMIN", "SET_PROJECT"):
843 if qs
in kwargs
and kwargs
[qs
].lower() != "false":
844 query_string_operations
.append(qs
.lower() + ":" + method
.lower())
845 return query_string_operations
848 def _manage_admin_query(token_info
, kwargs
, method
, _id
):
850 Processes the administrator query inputs (if any) of FORCE, ADMIN, PUBLIC, SET_PROJECT
851 Check that users has rights to use them and returs the admin_query
852 :param token_info: token_info rights obtained by token
853 :param kwargs: query string input.
854 :param method: http method: GET, POSST, PUT, ...
856 :return: admin_query dictionary with keys:
857 public: True, False or None
859 project_id: tuple with projects used for accessing an element
860 set_project: tuple with projects that a created element will belong to
861 method: show, list, delete, write
863 admin_query
= {"force": False, "project_id": (token_info
["project_id"], ), "username": token_info
["username"],
864 "admin": token_info
["admin"], "public": None,
865 "allow_show_user_project_role": token_info
["allow_show_user_project_role"]}
868 if "FORCE" in kwargs
:
869 if kwargs
["FORCE"].lower() != "false": # if None or True set force to True
870 admin_query
["force"] = True
873 if "PUBLIC" in kwargs
:
874 if kwargs
["PUBLIC"].lower() != "false": # if None or True set public to True
875 admin_query
["public"] = True
877 admin_query
["public"] = False
880 if "ADMIN" in kwargs
:
881 behave_as
= kwargs
.pop("ADMIN")
882 if behave_as
.lower() != "false":
883 if not token_info
["admin"]:
884 raise NbiException("Only admin projects can use 'ADMIN' query string", HTTPStatus
.UNAUTHORIZED
)
885 if not behave_as
or behave_as
.lower() == "true": # convert True, None to empty list
886 admin_query
["project_id"] = ()
887 elif isinstance(behave_as
, (list, tuple)):
888 admin_query
["project_id"] = behave_as
889 else: # isinstance(behave_as, str)
890 admin_query
["project_id"] = (behave_as
, )
891 if "SET_PROJECT" in kwargs
:
892 set_project
= kwargs
.pop("SET_PROJECT")
894 admin_query
["set_project"] = list(admin_query
["project_id"])
896 if isinstance(set_project
, str):
897 set_project
= (set_project
, )
898 if admin_query
["project_id"]:
899 for p
in set_project
:
900 if p
not in admin_query
["project_id"]:
901 raise NbiException("Unauthorized for 'SET_PROJECT={p}'. Try with 'ADMIN=True' or "
902 "'ADMIN='{p}'".format(p
=p
), HTTPStatus
.UNAUTHORIZED
)
903 admin_query
["set_project"] = set_project
906 # if "PROJECT_READ" in kwargs:
907 # admin_query["project"] = kwargs.pop("project")
908 # if admin_query["project"] == token_info["project_id"]:
911 admin_query
["method"] = "show"
913 admin_query
["method"] = "list"
914 elif method
== "DELETE":
915 admin_query
["method"] = "delete"
917 admin_query
["method"] = "write"
921 def default(self
, main_topic
=None, version
=None, topic
=None, _id
=None, item
=None, *args
, **kwargs
):
928 engine_session
= None
930 if not main_topic
or not version
or not topic
:
931 raise NbiException("URL must contain at least 'main_topic/version/topic'",
932 HTTPStatus
.METHOD_NOT_ALLOWED
)
933 if main_topic
not in ("admin", "vnfpkgm", "nsd", "nslcm", "pdu", "nst", "nsilcm", "nspm"):
934 raise NbiException("URL main_topic '{}' not supported".format(main_topic
),
935 HTTPStatus
.METHOD_NOT_ALLOWED
)
937 raise NbiException("URL version '{}' not supported".format(version
), HTTPStatus
.METHOD_NOT_ALLOWED
)
939 if kwargs
and "METHOD" in kwargs
and kwargs
["METHOD"] in ("PUT", "POST", "DELETE", "GET", "PATCH"):
940 method
= kwargs
.pop("METHOD")
942 method
= cherrypy
.request
.method
944 role_permission
= self
._check
_valid
_url
_method
(method
, main_topic
, version
, topic
, _id
, item
, *args
)
945 query_string_operations
= self
._extract
_query
_string
_operations
(kwargs
, method
)
946 if main_topic
== "admin" and topic
== "tokens":
947 return self
.token(method
, _id
, kwargs
)
948 token_info
= self
.authenticator
.authorize(role_permission
, query_string_operations
, _id
)
949 engine_session
= self
._manage
_admin
_query
(token_info
, kwargs
, method
, _id
)
950 indata
= self
._format
_in
(kwargs
)
952 if topic
== "subscriptions":
953 engine_topic
= main_topic
+ "_" + topic
954 if item
and topic
!= "pm_jobs":
957 if main_topic
== "nsd":
958 engine_topic
= "nsds"
959 elif main_topic
== "vnfpkgm":
960 engine_topic
= "vnfds"
961 elif main_topic
== "nslcm":
962 engine_topic
= "nsrs"
963 if topic
== "ns_lcm_op_occs":
964 engine_topic
= "nslcmops"
965 if topic
== "vnfrs" or topic
== "vnf_instances":
966 engine_topic
= "vnfrs"
967 elif main_topic
== "nst":
968 engine_topic
= "nsts"
969 elif main_topic
== "nsilcm":
970 engine_topic
= "nsis"
971 if topic
== "nsi_lcm_op_occs":
972 engine_topic
= "nsilcmops"
973 elif main_topic
== "pdu":
974 engine_topic
= "pdus"
975 if engine_topic
== "vims": # TODO this is for backward compatibility, it will be removed in the future
976 engine_topic
= "vim_accounts"
979 if item
in ("nsd_content", "package_content", "artifacts", "vnfd", "nsd", "nst", "nst_content"):
980 if item
in ("vnfd", "nsd", "nst"):
984 elif item
== "artifacts":
988 file, _format
= self
.engine
.get_file(engine_session
, engine_topic
, _id
, path
,
989 cherrypy
.request
.headers
.get("Accept"))
992 outdata
= self
.engine
.get_item_list(engine_session
, engine_topic
, kwargs
)
994 if item
== "reports":
995 # TODO check that project_id (_id in this context) has permissions
997 outdata
= self
.engine
.get_item(engine_session
, engine_topic
, _id
)
998 elif method
== "POST":
999 cherrypy
.response
.status
= HTTPStatus
.CREATED
.value
1000 if topic
in ("ns_descriptors_content", "vnf_packages_content", "netslice_templates_content"):
1001 _id
= cherrypy
.request
.headers
.get("Transaction-Id")
1003 _id
, _
= self
.engine
.new_item(rollback
, engine_session
, engine_topic
, {}, None,
1004 cherrypy
.request
.headers
)
1005 completed
= self
.engine
.upload_content(engine_session
, engine_topic
, _id
, indata
, kwargs
,
1006 cherrypy
.request
.headers
)
1008 self
._set
_location
_header
(main_topic
, version
, topic
, _id
)
1010 cherrypy
.response
.headers
["Transaction-Id"] = _id
1011 outdata
= {"id": _id
}
1012 elif topic
== "ns_instances_content":
1014 _id
, _
= self
.engine
.new_item(rollback
, engine_session
, engine_topic
, indata
, kwargs
)
1016 indata
["lcmOperationType"] = "instantiate"
1017 indata
["nsInstanceId"] = _id
1018 nslcmop_id
, _
= self
.engine
.new_item(rollback
, engine_session
, "nslcmops", indata
, None)
1019 self
._set
_location
_header
(main_topic
, version
, topic
, _id
)
1020 outdata
= {"id": _id
, "nslcmop_id": nslcmop_id
}
1021 elif topic
== "ns_instances" and item
:
1022 indata
["lcmOperationType"] = item
1023 indata
["nsInstanceId"] = _id
1024 _id
, _
= self
.engine
.new_item(rollback
, engine_session
, "nslcmops", indata
, kwargs
)
1025 self
._set
_location
_header
(main_topic
, version
, "ns_lcm_op_occs", _id
)
1026 outdata
= {"id": _id
}
1027 cherrypy
.response
.status
= HTTPStatus
.ACCEPTED
.value
1028 elif topic
== "netslice_instances_content":
1029 # creates NetSlice_Instance_record (NSIR)
1030 _id
, _
= self
.engine
.new_item(rollback
, engine_session
, engine_topic
, indata
, kwargs
)
1031 self
._set
_location
_header
(main_topic
, version
, topic
, _id
)
1032 indata
["lcmOperationType"] = "instantiate"
1033 indata
["netsliceInstanceId"] = _id
1034 nsilcmop_id
, _
= self
.engine
.new_item(rollback
, engine_session
, "nsilcmops", indata
, kwargs
)
1035 outdata
= {"id": _id
, "nsilcmop_id": nsilcmop_id
}
1037 elif topic
== "netslice_instances" and item
:
1038 indata
["lcmOperationType"] = item
1039 indata
["netsliceInstanceId"] = _id
1040 _id
, _
= self
.engine
.new_item(rollback
, engine_session
, "nsilcmops", indata
, kwargs
)
1041 self
._set
_location
_header
(main_topic
, version
, "nsi_lcm_op_occs", _id
)
1042 outdata
= {"id": _id
}
1043 cherrypy
.response
.status
= HTTPStatus
.ACCEPTED
.value
1045 _id
, op_id
= self
.engine
.new_item(rollback
, engine_session
, engine_topic
, indata
, kwargs
,
1046 cherrypy
.request
.headers
)
1047 self
._set
_location
_header
(main_topic
, version
, topic
, _id
)
1048 outdata
= {"id": _id
}
1050 outdata
["op_id"] = op_id
1051 cherrypy
.response
.status
= HTTPStatus
.ACCEPTED
.value
1052 # TODO form NsdInfo when topic in ("ns_descriptors", "vnf_packages")
1054 elif method
== "DELETE":
1056 outdata
= self
.engine
.del_item_list(engine_session
, engine_topic
, kwargs
)
1057 cherrypy
.response
.status
= HTTPStatus
.OK
.value
1058 else: # len(args) > 1
1059 delete_in_process
= False
1060 if topic
== "ns_instances_content" and not engine_session
["force"]:
1062 "lcmOperationType": "terminate",
1063 "nsInstanceId": _id
,
1066 opp_id
, _
= self
.engine
.new_item(rollback
, engine_session
, "nslcmops", nslcmop_desc
, None)
1068 delete_in_process
= True
1069 outdata
= {"_id": opp_id
}
1070 cherrypy
.response
.status
= HTTPStatus
.ACCEPTED
.value
1071 elif topic
== "netslice_instances_content" and not engine_session
["force"]:
1073 "lcmOperationType": "terminate",
1074 "netsliceInstanceId": _id
,
1077 opp_id
, _
= self
.engine
.new_item(rollback
, engine_session
, "nsilcmops", nsilcmop_desc
, None)
1079 delete_in_process
= True
1080 outdata
= {"_id": opp_id
}
1081 cherrypy
.response
.status
= HTTPStatus
.ACCEPTED
.value
1082 if not delete_in_process
:
1083 self
.engine
.del_item(engine_session
, engine_topic
, _id
)
1084 cherrypy
.response
.status
= HTTPStatus
.NO_CONTENT
.value
1085 if engine_topic
in ("vim_accounts", "wim_accounts", "sdns"):
1086 cherrypy
.response
.status
= HTTPStatus
.ACCEPTED
.value
1088 elif method
in ("PUT", "PATCH"):
1090 if not indata
and not kwargs
and not engine_session
.get("set_project"):
1091 raise NbiException("Nothing to update. Provide payload and/or query string",
1092 HTTPStatus
.BAD_REQUEST
)
1093 if item
in ("nsd_content", "package_content", "nst_content") and method
== "PUT":
1094 completed
= self
.engine
.upload_content(engine_session
, engine_topic
, _id
, indata
, kwargs
,
1095 cherrypy
.request
.headers
)
1097 cherrypy
.response
.headers
["Transaction-Id"] = id
1099 op_id
= self
.engine
.edit_item(engine_session
, engine_topic
, _id
, indata
, kwargs
)
1102 cherrypy
.response
.status
= HTTPStatus
.ACCEPTED
.value
1103 outdata
= {"op_id": op_id
}
1105 cherrypy
.response
.status
= HTTPStatus
.NO_CONTENT
.value
1108 raise NbiException("Method {} not allowed".format(method
), HTTPStatus
.METHOD_NOT_ALLOWED
)
1110 # if Role information changes, it is needed to reload the information of roles
1111 if topic
== "roles" and method
!= "GET":
1112 self
.authenticator
.load_operation_to_allowed_roles()
1113 return self
._format
_out
(outdata
, token_info
, _format
)
1114 except Exception as e
:
1115 if isinstance(e
, (NbiException
, EngineException
, DbException
, FsException
, MsgException
, AuthException
,
1116 ValidationError
, AuthconnException
)):
1117 http_code_value
= cherrypy
.response
.status
= e
.http_code
.value
1118 http_code_name
= e
.http_code
.name
1119 cherrypy
.log("Exception {}".format(e
))
1121 http_code_value
= cherrypy
.response
.status
= HTTPStatus
.BAD_REQUEST
.value
# INTERNAL_SERVER_ERROR
1122 cherrypy
.log("CRITICAL: Exception {}".format(e
), traceback
=True)
1123 http_code_name
= HTTPStatus
.BAD_REQUEST
.name
1124 if hasattr(outdata
, "close"): # is an open file
1128 for rollback_item
in rollback
:
1130 if rollback_item
.get("operation") == "set":
1131 self
.engine
.db
.set_one(rollback_item
["topic"], {"_id": rollback_item
["_id"]},
1132 rollback_item
["content"], fail_on_empty
=False)
1134 self
.engine
.db
.del_one(rollback_item
["topic"], {"_id": rollback_item
["_id"]},
1135 fail_on_empty
=False)
1136 except Exception as e2
:
1137 rollback_error_text
= "Rollback Exception {}: {}".format(rollback_item
, e2
)
1138 cherrypy
.log(rollback_error_text
)
1139 error_text
+= ". " + rollback_error_text
1140 # if isinstance(e, MsgException):
1141 # error_text = "{} has been '{}' but other modules cannot be informed because an error on bus".format(
1142 # engine_topic[:-1], method, error_text)
1144 "code": http_code_name
,
1145 "status": http_code_value
,
1146 "detail": error_text
,
1148 return self
._format
_out
(problem_details
, token_info
)
1149 # raise cherrypy.HTTPError(e.http_code.value, str(e))
1152 self
._format
_login
(token_info
)
1153 if method
in ("PUT", "PATCH", "POST") and isinstance(outdata
, dict):
1154 for logging_id
in ("id", "op_id", "nsilcmop_id", "nslcmop_id"):
1155 if outdata
.get(logging_id
):
1156 cherrypy
.request
.login
+= ";{}={}".format(logging_id
, outdata
[logging_id
][:36])
1159 def _start_service():
1161 Callback function called when cherrypy.engine starts
1162 Override configuration with env variables
1163 Set database, storage, message configuration
1164 Init database with admin/admin user password
1167 global subscription_thread
1168 cherrypy
.log
.error("Starting osm_nbi")
1169 # update general cherrypy configuration
1172 engine_config
= cherrypy
.tree
.apps
['/osm'].config
1173 for k
, v
in environ
.items():
1174 if not k
.startswith("OSMNBI_"):
1176 k1
, _
, k2
= k
[7:].lower().partition("_")
1180 # update static configuration
1181 if k
== 'OSMNBI_STATIC_DIR':
1182 engine_config
["/static"]['tools.staticdir.dir'] = v
1183 engine_config
["/static"]['tools.staticdir.on'] = True
1184 elif k
== 'OSMNBI_SOCKET_PORT' or k
== 'OSMNBI_SERVER_PORT':
1185 update_dict
['server.socket_port'] = int(v
)
1186 elif k
== 'OSMNBI_SOCKET_HOST' or k
== 'OSMNBI_SERVER_HOST':
1187 update_dict
['server.socket_host'] = v
1188 elif k1
in ("server", "test", "auth", "log"):
1189 update_dict
[k1
+ '.' + k2
] = v
1190 elif k1
in ("message", "database", "storage", "authentication"):
1191 # k2 = k2.replace('_', '.')
1192 if k2
in ("port", "db_port"):
1193 engine_config
[k1
][k2
] = int(v
)
1195 engine_config
[k1
][k2
] = v
1197 except ValueError as e
:
1198 cherrypy
.log
.error("Ignoring environ '{}': " + str(e
))
1199 except Exception as e
:
1200 cherrypy
.log
.warn("skipping environ '{}' on exception '{}'".format(k
, e
))
1203 cherrypy
.config
.update(update_dict
)
1204 engine_config
["global"].update(update_dict
)
1207 log_format_simple
= "%(asctime)s %(levelname)s %(name)s %(filename)s:%(lineno)s %(message)s"
1208 log_formatter_simple
= logging
.Formatter(log_format_simple
, datefmt
='%Y-%m-%dT%H:%M:%S')
1209 logger_server
= logging
.getLogger("cherrypy.error")
1210 logger_access
= logging
.getLogger("cherrypy.access")
1211 logger_cherry
= logging
.getLogger("cherrypy")
1212 logger_nbi
= logging
.getLogger("nbi")
1214 if "log.file" in engine_config
["global"]:
1215 file_handler
= logging
.handlers
.RotatingFileHandler(engine_config
["global"]["log.file"],
1216 maxBytes
=100e6
, backupCount
=9, delay
=0)
1217 file_handler
.setFormatter(log_formatter_simple
)
1218 logger_cherry
.addHandler(file_handler
)
1219 logger_nbi
.addHandler(file_handler
)
1220 # log always to standard output
1221 for format_
, logger
in {"nbi.server %(filename)s:%(lineno)s": logger_server
,
1222 "nbi.access %(filename)s:%(lineno)s": logger_access
,
1223 "%(name)s %(filename)s:%(lineno)s": logger_nbi
1225 log_format_cherry
= "%(asctime)s %(levelname)s {} %(message)s".format(format_
)
1226 log_formatter_cherry
= logging
.Formatter(log_format_cherry
, datefmt
='%Y-%m-%dT%H:%M:%S')
1227 str_handler
= logging
.StreamHandler()
1228 str_handler
.setFormatter(log_formatter_cherry
)
1229 logger
.addHandler(str_handler
)
1231 if engine_config
["global"].get("log.level"):
1232 logger_cherry
.setLevel(engine_config
["global"]["log.level"])
1233 logger_nbi
.setLevel(engine_config
["global"]["log.level"])
1235 # logging other modules
1236 for k1
, logname
in {"message": "nbi.msg", "database": "nbi.db", "storage": "nbi.fs"}.items():
1237 engine_config
[k1
]["logger_name"] = logname
1238 logger_module
= logging
.getLogger(logname
)
1239 if "logfile" in engine_config
[k1
]:
1240 file_handler
= logging
.handlers
.RotatingFileHandler(engine_config
[k1
]["logfile"],
1241 maxBytes
=100e6
, backupCount
=9, delay
=0)
1242 file_handler
.setFormatter(log_formatter_simple
)
1243 logger_module
.addHandler(file_handler
)
1244 if "loglevel" in engine_config
[k1
]:
1245 logger_module
.setLevel(engine_config
[k1
]["loglevel"])
1246 # TODO add more entries, e.g.: storage
1247 cherrypy
.tree
.apps
['/osm'].root
.engine
.start(engine_config
)
1248 cherrypy
.tree
.apps
['/osm'].root
.authenticator
.start(engine_config
)
1249 cherrypy
.tree
.apps
['/osm'].root
.engine
.init_db(target_version
=database_version
)
1250 cherrypy
.tree
.apps
['/osm'].root
.authenticator
.init_db(target_version
=auth_database_version
)
1252 # start subscriptions thread:
1253 subscription_thread
= SubscriptionThread(config
=engine_config
, engine
=nbi_server
.engine
)
1254 subscription_thread
.start()
1255 # Do not capture except SubscriptionException
1257 # load and print version. Ignore possible errors, e.g. file not found
1259 backend
= engine_config
["authentication"]["backend"]
1261 cherrypy
.log
.error("Starting OSM NBI Version '{}' with '{}' authentication backend"
1262 .format(nbi_version
+ " " + nbi_version_date
, backend
))
1267 def _stop_service():
1269 Callback function called when cherrypy.engine stops
1270 TODO: Ending database connections.
1272 global subscription_thread
1273 if subscription_thread
:
1274 subscription_thread
.terminate()
1275 subscription_thread
= None
1276 cherrypy
.tree
.apps
['/osm'].root
.engine
.stop()
1277 cherrypy
.log
.error("Stopping osm_nbi")
1280 def nbi(config_file
):
1284 # #'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
1285 # 'tools.sessions.on': True,
1286 # 'tools.response_headers.on': True,
1287 # # 'tools.response_headers.headers': [('Content-Type', 'text/plain')],
1290 # cherrypy.Server.ssl_module = 'builtin'
1291 # cherrypy.Server.ssl_certificate = "http/cert.pem"
1292 # cherrypy.Server.ssl_private_key = "http/privkey.pem"
1293 # cherrypy.Server.thread_pool = 10
1294 # cherrypy.config.update({'Server.socket_port': config["port"], 'Server.socket_host': config["host"]})
1296 # cherrypy.config.update({'tools.auth_basic.on': True,
1297 # 'tools.auth_basic.realm': 'localhost',
1298 # 'tools.auth_basic.checkpassword': validate_password})
1299 nbi_server
= Server()
1300 cherrypy
.engine
.subscribe('start', _start_service
)
1301 cherrypy
.engine
.subscribe('stop', _stop_service
)
1302 cherrypy
.quickstart(nbi_server
, '/osm', config_file
)
1306 print("""Usage: {} [options]
1307 -c|--config [configuration_file]: loads the configuration file (default: ./nbi.cfg)
1308 -h|--help: shows this help
1309 """.format(sys
.argv
[0]))
1310 # --log-socket-host HOST: send logs to this host")
1311 # --log-socket-port PORT: send logs using this port (default: 9022)")
1314 if __name__
== '__main__':
1316 # load parameters and configuration
1317 opts
, args
= getopt
.getopt(sys
.argv
[1:], "hvc:", ["config=", "help"])
1318 # TODO add "log-socket-host=", "log-socket-port=", "log-file="
1321 if o
in ("-h", "--help"):
1324 elif o
in ("-c", "--config"):
1326 # elif o == "--log-socket-port":
1327 # log_socket_port = a
1328 # elif o == "--log-socket-host":
1329 # log_socket_host = a
1330 # elif o == "--log-file":
1333 assert False, "Unhandled option"
1335 if not path
.isfile(config_file
):
1336 print("configuration file '{}' that not exist".format(config_file
), file=sys
.stderr
)
1339 for config_file
in (__file__
[:__file__
.rfind(".")] + ".cfg", "./nbi.cfg", "/etc/osm/nbi.cfg"):
1340 if path
.isfile(config_file
):
1343 print("No configuration file 'nbi.cfg' found neither at local folder nor at /etc/osm/", file=sys
.stderr
)
1346 except getopt
.GetoptError
as e
:
1347 print(str(e
), file=sys
.stderr
)