blob: 376c087ee894ef10f162e51fe9d577eebf40ffe3 [file] [log] [blame]
tierno1d213f42020-04-24 14:02:51 +00001#!/usr/bin/python3
2# -*- coding: utf-8 -*-
3
4##
5# Copyright 2020 Telefonica Investigacion y Desarrollo, S.A.U.
6#
7# Licensed under the Apache License, Version 2.0 (the "License");
8# you may not use this file except in compliance with the License.
9# You may obtain a copy of the License at
10#
11# http://www.apache.org/licenses/LICENSE-2.0
12#
13# Unless required by applicable law or agreed to in writing, software
14# distributed under the License is distributed on an "AS IS" BASIS,
15# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
16# implied.
17# See the License for the specific language governing permissions and
18# limitations under the License.
19##
20
sousaedu049cbb12022-01-05 11:39:35 +000021
22from codecs import getreader
23import getopt
24from http import HTTPStatus
tierno1d213f42020-04-24 14:02:51 +000025import json
tierno1d213f42020-04-24 14:02:51 +000026import logging
27import logging.handlers
sousaedu049cbb12022-01-05 11:39:35 +000028from os import environ, path
tierno1d213f42020-04-24 14:02:51 +000029import sys
sousaedu049cbb12022-01-05 11:39:35 +000030import time
tierno1d213f42020-04-24 14:02:51 +000031
sousaedu049cbb12022-01-05 11:39:35 +000032import cherrypy
tierno1d213f42020-04-24 14:02:51 +000033from osm_common.dbbase import DbException
34from osm_common.fsbase import FsException
35from osm_common.msgbase import MsgException
tierno1d213f42020-04-24 14:02:51 +000036from osm_ng_ro import version as ro_version, version_date as ro_version_date
sousaedu049cbb12022-01-05 11:39:35 +000037import osm_ng_ro.html_out as html
38from osm_ng_ro.ns import Ns, NsException
39from osm_ng_ro.validation import ValidationError
40from osm_ng_ro.vim_admin import VimAdminThread
41import yaml
42
tierno1d213f42020-04-24 14:02:51 +000043
44__author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
sousaedu80135b92021-02-17 15:05:18 +010045__version__ = "0.1." # file version, not NBI version
tierno1d213f42020-04-24 14:02:51 +000046version_date = "May 2020"
47
sousaedu80135b92021-02-17 15:05:18 +010048database_version = "1.2"
49auth_database_version = "1.0"
50ro_server = None # instance of Server class
51vim_admin_thread = None # instance of VimAdminThread class
tierno70eeb182020-10-19 16:38:00 +000052
tierno1d213f42020-04-24 14:02:51 +000053# vim_threads = None # instance of VimThread class
54
55"""
56RO North Bound Interface
57URL: /ro GET POST PUT DELETE PATCH
58 /ns/v1/deploy O
59 /<nsrs_id> O O O
60 /<action_id> O
61 /cancel O
62
63"""
64
65valid_query_string = ("ADMIN", "SET_PROJECT", "FORCE", "PUBLIC")
66# ^ Contains possible administrative query string words:
67# ADMIN=True(by default)|Project|Project-list: See all elements, or elements of a project
68# (not owned by my session project).
69# PUBLIC=True(by default)|False: See/hide public elements. Set/Unset a topic to be public
70# FORCE=True(by default)|False: Force edition/deletion operations
71# SET_PROJECT=Project|Project-list: Add/Delete the topic to the projects portfolio
72
73valid_url_methods = {
74 # contains allowed URL and methods, and the role_permission name
75 "admin": {
76 "v1": {
77 "tokens": {
78 "METHODS": ("POST",),
79 "ROLE_PERMISSION": "tokens:",
sousaedu80135b92021-02-17 15:05:18 +010080 "<ID>": {"METHODS": ("DELETE",), "ROLE_PERMISSION": "tokens:id:"},
tierno1d213f42020-04-24 14:02:51 +000081 },
82 }
83 },
84 "ns": {
85 "v1": {
k4.rahul78f474e2022-05-02 15:47:57 +000086 "rebuild": {
87 "METHODS": ("POST",),
88 "ROLE_PERMISSION": "rebuild:",
89 "<ID>": {
90 "METHODS": ("POST",),
91 "ROLE_PERMISSION": "rebuild:id:",
92 },
93 },
94 "start": {
95 "METHODS": ("POST",),
96 "ROLE_PERMISSION": "start:",
97 "<ID>": {
98 "METHODS": ("POST",),
99 "ROLE_PERMISSION": "start:id:",
100 },
101 },
102 "stop": {
103 "METHODS": ("POST",),
104 "ROLE_PERMISSION": "stop:",
105 "<ID>": {
106 "METHODS": ("POST",),
107 "ROLE_PERMISSION": "stop:id:",
108 },
109 },
tierno1d213f42020-04-24 14:02:51 +0000110 "deploy": {
111 "METHODS": ("GET",),
112 "ROLE_PERMISSION": "deploy:",
113 "<ID>": {
114 "METHODS": ("GET", "POST", "DELETE"),
115 "ROLE_PERMISSION": "deploy:id:",
116 "<ID>": {
117 "METHODS": ("GET",),
118 "ROLE_PERMISSION": "deploy:id:id:",
119 "cancel": {
120 "METHODS": ("POST",),
121 "ROLE_PERMISSION": "deploy:id:id:cancel",
sousaedu80135b92021-02-17 15:05:18 +0100122 },
123 },
124 },
tierno1d213f42020-04-24 14:02:51 +0000125 },
palaciosj8f2060b2022-02-24 12:05:59 +0000126 "recreate": {
127 "<ID>": {
128 "METHODS": ("POST"),
129 "ROLE_PERMISSION": "recreate:id:",
130 "<ID>": {
131 "METHODS": ("GET",),
132 "ROLE_PERMISSION": "recreate:id:id:",
133 },
134 },
135 },
elumalai8658c2c2022-04-28 19:09:31 +0530136 "migrate": {
137 "<ID>": {
138 "METHODS": ("POST"),
139 "ROLE_PERMISSION": "migrate:id:",
140 "<ID>": {
141 "METHODS": ("GET",),
142 "ROLE_PERMISSION": "migrate:id:id:",
143 },
144 },
145 },
sritharan29a4c1a2022-05-05 12:15:04 +0000146 "verticalscale": {
147 "<ID>": {
148 "METHODS": ("POST"),
149 "ROLE_PERMISSION": "verticalscale:id:",
150 "<ID>": {
151 "METHODS": ("GET",),
152 "ROLE_PERMISSION": "verticalscale:id:id:",
153 },
154 },
155 },
tierno1d213f42020-04-24 14:02:51 +0000156 }
157 },
158}
159
160
161class RoException(Exception):
tierno1d213f42020-04-24 14:02:51 +0000162 def __init__(self, message, http_code=HTTPStatus.METHOD_NOT_ALLOWED):
163 Exception.__init__(self, message)
164 self.http_code = http_code
165
166
167class AuthException(RoException):
168 pass
169
170
171class Authenticator:
tierno1d213f42020-04-24 14:02:51 +0000172 def __init__(self, valid_url_methods, valid_query_string):
173 self.valid_url_methods = valid_url_methods
174 self.valid_query_string = valid_query_string
175
176 def authorize(self, *args, **kwargs):
177 return {"token": "ok", "id": "ok"}
sousaedu80135b92021-02-17 15:05:18 +0100178
tierno1d213f42020-04-24 14:02:51 +0000179 def new_token(self, token_info, indata, remote):
sousaedu80135b92021-02-17 15:05:18 +0100180 return {"token": "ok", "id": "ok", "remote": remote}
tierno1d213f42020-04-24 14:02:51 +0000181
182 def del_token(self, token_id):
183 pass
184
185 def start(self, engine_config):
186 pass
187
188
189class Server(object):
190 instance = 0
191 # to decode bytes to str
192 reader = getreader("utf-8")
193
194 def __init__(self):
195 self.instance += 1
196 self.authenticator = Authenticator(valid_url_methods, valid_query_string)
197 self.ns = Ns()
198 self.map_operation = {
199 "token:post": self.new_token,
200 "token:id:delete": self.del_token,
201 "deploy:get": self.ns.get_deploy,
202 "deploy:id:get": self.ns.get_actions,
203 "deploy:id:post": self.ns.deploy,
204 "deploy:id:delete": self.ns.delete,
205 "deploy:id:id:get": self.ns.status,
206 "deploy:id:id:cancel:post": self.ns.cancel,
k4.rahul78f474e2022-05-02 15:47:57 +0000207 "rebuild:id:post": self.ns.rebuild_start_stop,
208 "start:id:post": self.ns.rebuild_start_stop,
209 "stop:id:post": self.ns.rebuild_start_stop,
palaciosj8f2060b2022-02-24 12:05:59 +0000210 "recreate:id:post": self.ns.recreate,
211 "recreate:id:id:get": self.ns.recreate_status,
elumalai8658c2c2022-04-28 19:09:31 +0530212 "migrate:id:post": self.ns.migrate,
sritharan29a4c1a2022-05-05 12:15:04 +0000213 "verticalscale:id:post": self.ns.verticalscale,
tierno1d213f42020-04-24 14:02:51 +0000214 }
215
216 def _format_in(self, kwargs):
217 try:
218 indata = None
sousaedu80135b92021-02-17 15:05:18 +0100219
tierno1d213f42020-04-24 14:02:51 +0000220 if cherrypy.request.body.length:
221 error_text = "Invalid input format "
222
223 if "Content-Type" in cherrypy.request.headers:
224 if "application/json" in cherrypy.request.headers["Content-Type"]:
225 error_text = "Invalid json format "
226 indata = json.load(self.reader(cherrypy.request.body))
227 cherrypy.request.headers.pop("Content-File-MD5", None)
228 elif "application/yaml" in cherrypy.request.headers["Content-Type"]:
229 error_text = "Invalid yaml format "
sousaedu80135b92021-02-17 15:05:18 +0100230 indata = yaml.load(
231 cherrypy.request.body, Loader=yaml.SafeLoader
232 )
tierno1d213f42020-04-24 14:02:51 +0000233 cherrypy.request.headers.pop("Content-File-MD5", None)
sousaedu80135b92021-02-17 15:05:18 +0100234 elif (
235 "application/binary" in cherrypy.request.headers["Content-Type"]
236 or "application/gzip"
237 in cherrypy.request.headers["Content-Type"]
238 or "application/zip" in cherrypy.request.headers["Content-Type"]
239 or "text/plain" in cherrypy.request.headers["Content-Type"]
240 ):
tierno1d213f42020-04-24 14:02:51 +0000241 indata = cherrypy.request.body # .read()
sousaedu80135b92021-02-17 15:05:18 +0100242 elif (
243 "multipart/form-data"
244 in cherrypy.request.headers["Content-Type"]
245 ):
tierno1d213f42020-04-24 14:02:51 +0000246 if "descriptor_file" in kwargs:
247 filecontent = kwargs.pop("descriptor_file")
sousaedu80135b92021-02-17 15:05:18 +0100248
tierno1d213f42020-04-24 14:02:51 +0000249 if not filecontent.file:
sousaedu80135b92021-02-17 15:05:18 +0100250 raise RoException(
251 "empty file or content", HTTPStatus.BAD_REQUEST
252 )
253
tierno1d213f42020-04-24 14:02:51 +0000254 indata = filecontent.file # .read()
sousaedu80135b92021-02-17 15:05:18 +0100255
tierno1d213f42020-04-24 14:02:51 +0000256 if filecontent.content_type.value:
sousaedu80135b92021-02-17 15:05:18 +0100257 cherrypy.request.headers[
258 "Content-Type"
259 ] = filecontent.content_type.value
tierno1d213f42020-04-24 14:02:51 +0000260 else:
261 # raise cherrypy.HTTPError(HTTPStatus.Not_Acceptable,
262 # "Only 'Content-Type' of type 'application/json' or
263 # 'application/yaml' for input format are available")
264 error_text = "Invalid yaml format "
sousaedu80135b92021-02-17 15:05:18 +0100265 indata = yaml.load(
266 cherrypy.request.body, Loader=yaml.SafeLoader
267 )
tierno1d213f42020-04-24 14:02:51 +0000268 cherrypy.request.headers.pop("Content-File-MD5", None)
269 else:
270 error_text = "Invalid yaml format "
271 indata = yaml.load(cherrypy.request.body, Loader=yaml.SafeLoader)
272 cherrypy.request.headers.pop("Content-File-MD5", None)
sousaedu80135b92021-02-17 15:05:18 +0100273
tierno1d213f42020-04-24 14:02:51 +0000274 if not indata:
275 indata = {}
276
277 format_yaml = False
278 if cherrypy.request.headers.get("Query-String-Format") == "yaml":
279 format_yaml = True
280
281 for k, v in kwargs.items():
282 if isinstance(v, str):
283 if v == "":
284 kwargs[k] = None
285 elif format_yaml:
286 try:
287 kwargs[k] = yaml.load(v, Loader=yaml.SafeLoader)
288 except Exception:
289 pass
sousaedu80135b92021-02-17 15:05:18 +0100290 elif (
291 k.endswith(".gt")
292 or k.endswith(".lt")
293 or k.endswith(".gte")
294 or k.endswith(".lte")
295 ):
tierno1d213f42020-04-24 14:02:51 +0000296 try:
297 kwargs[k] = int(v)
298 except Exception:
299 try:
300 kwargs[k] = float(v)
301 except Exception:
302 pass
303 elif v.find(",") > 0:
304 kwargs[k] = v.split(",")
305 elif isinstance(v, (list, tuple)):
306 for index in range(0, len(v)):
307 if v[index] == "":
308 v[index] = None
309 elif format_yaml:
310 try:
311 v[index] = yaml.load(v[index], Loader=yaml.SafeLoader)
312 except Exception:
313 pass
314
315 return indata
316 except (ValueError, yaml.YAMLError) as exc:
317 raise RoException(error_text + str(exc), HTTPStatus.BAD_REQUEST)
318 except KeyError as exc:
319 raise RoException("Query string error: " + str(exc), HTTPStatus.BAD_REQUEST)
320 except Exception as exc:
321 raise RoException(error_text + str(exc), HTTPStatus.BAD_REQUEST)
322
323 @staticmethod
324 def _format_out(data, token_info=None, _format=None):
325 """
326 return string of dictionary data according to requested json, yaml, xml. By default json
327 :param data: response to be sent. Can be a dict, text or file
328 :param token_info: Contains among other username and project
329 :param _format: The format to be set as Content-Type if data is a file
330 :return: None
331 """
332 accept = cherrypy.request.headers.get("Accept")
sousaedu80135b92021-02-17 15:05:18 +0100333
tierno1d213f42020-04-24 14:02:51 +0000334 if data is None:
335 if accept and "text/html" in accept:
sousaedu80135b92021-02-17 15:05:18 +0100336 return html.format(
337 data, cherrypy.request, cherrypy.response, token_info
338 )
339
tierno1d213f42020-04-24 14:02:51 +0000340 # cherrypy.response.status = HTTPStatus.NO_CONTENT.value
341 return
342 elif hasattr(data, "read"): # file object
343 if _format:
344 cherrypy.response.headers["Content-Type"] = _format
345 elif "b" in data.mode: # binariy asssumig zip
sousaedu80135b92021-02-17 15:05:18 +0100346 cherrypy.response.headers["Content-Type"] = "application/zip"
tierno1d213f42020-04-24 14:02:51 +0000347 else:
sousaedu80135b92021-02-17 15:05:18 +0100348 cherrypy.response.headers["Content-Type"] = "text/plain"
349
tierno1d213f42020-04-24 14:02:51 +0000350 # TODO check that cherrypy close file. If not implement pending things to close per thread next
351 return data
sousaedu80135b92021-02-17 15:05:18 +0100352
tierno1d213f42020-04-24 14:02:51 +0000353 if accept:
354 if "application/json" in accept:
sousaedu80135b92021-02-17 15:05:18 +0100355 cherrypy.response.headers[
356 "Content-Type"
357 ] = "application/json; charset=utf-8"
tierno1d213f42020-04-24 14:02:51 +0000358 a = json.dumps(data, indent=4) + "\n"
sousaedu80135b92021-02-17 15:05:18 +0100359
tierno1d213f42020-04-24 14:02:51 +0000360 return a.encode("utf8")
361 elif "text/html" in accept:
sousaedu80135b92021-02-17 15:05:18 +0100362 return html.format(
363 data, cherrypy.request, cherrypy.response, token_info
364 )
365 elif (
366 "application/yaml" in accept
367 or "*/*" in accept
368 or "text/plain" in accept
369 ):
tierno1d213f42020-04-24 14:02:51 +0000370 pass
371 # if there is not any valid accept, raise an error. But if response is already an error, format in yaml
372 elif cherrypy.response.status >= 400:
sousaedu80135b92021-02-17 15:05:18 +0100373 raise cherrypy.HTTPError(
374 HTTPStatus.NOT_ACCEPTABLE.value,
375 "Only 'Accept' of type 'application/json' or 'application/yaml' "
376 "for output format are available",
377 )
378
379 cherrypy.response.headers["Content-Type"] = "application/yaml"
380
381 return yaml.safe_dump(
382 data,
383 explicit_start=True,
384 indent=4,
385 default_flow_style=False,
386 tags=False,
387 encoding="utf-8",
388 allow_unicode=True,
389 ) # , canonical=True, default_style='"'
tierno1d213f42020-04-24 14:02:51 +0000390
391 @cherrypy.expose
392 def index(self, *args, **kwargs):
393 token_info = None
sousaedu80135b92021-02-17 15:05:18 +0100394
tierno1d213f42020-04-24 14:02:51 +0000395 try:
396 if cherrypy.request.method == "GET":
397 token_info = self.authenticator.authorize()
sousaedu80135b92021-02-17 15:05:18 +0100398 outdata = token_info # Home page
tierno1d213f42020-04-24 14:02:51 +0000399 else:
sousaedu80135b92021-02-17 15:05:18 +0100400 raise cherrypy.HTTPError(
401 HTTPStatus.METHOD_NOT_ALLOWED.value,
402 "Method {} not allowed for tokens".format(cherrypy.request.method),
403 )
tierno1d213f42020-04-24 14:02:51 +0000404
405 return self._format_out(outdata, token_info)
tierno1d213f42020-04-24 14:02:51 +0000406 except (NsException, AuthException) as e:
407 # cherrypy.log("index Exception {}".format(e))
408 cherrypy.response.status = e.http_code.value
sousaedu80135b92021-02-17 15:05:18 +0100409
tierno1d213f42020-04-24 14:02:51 +0000410 return self._format_out("Welcome to OSM!", token_info)
411
412 @cherrypy.expose
413 def version(self, *args, **kwargs):
414 # TODO consider to remove and provide version using the static version file
415 try:
416 if cherrypy.request.method != "GET":
sousaedu80135b92021-02-17 15:05:18 +0100417 raise RoException(
418 "Only method GET is allowed",
419 HTTPStatus.METHOD_NOT_ALLOWED,
420 )
tierno1d213f42020-04-24 14:02:51 +0000421 elif args or kwargs:
sousaedu80135b92021-02-17 15:05:18 +0100422 raise RoException(
423 "Invalid URL or query string for version",
424 HTTPStatus.METHOD_NOT_ALLOWED,
425 )
426
tierno1d213f42020-04-24 14:02:51 +0000427 # TODO include version of other modules, pick up from some kafka admin message
428 osm_ng_ro_version = {"version": ro_version, "date": ro_version_date}
sousaedu80135b92021-02-17 15:05:18 +0100429
tierno1d213f42020-04-24 14:02:51 +0000430 return self._format_out(osm_ng_ro_version)
431 except RoException as e:
432 cherrypy.response.status = e.http_code.value
433 problem_details = {
434 "code": e.http_code.name,
435 "status": e.http_code.value,
436 "detail": str(e),
437 }
sousaedu80135b92021-02-17 15:05:18 +0100438
tierno1d213f42020-04-24 14:02:51 +0000439 return self._format_out(problem_details, None)
440
441 def new_token(self, engine_session, indata, *args, **kwargs):
442 token_info = None
443
444 try:
445 token_info = self.authenticator.authorize()
446 except Exception:
447 token_info = None
sousaedu80135b92021-02-17 15:05:18 +0100448
tierno1d213f42020-04-24 14:02:51 +0000449 if kwargs:
450 indata.update(kwargs)
sousaedu80135b92021-02-17 15:05:18 +0100451
tierno1d213f42020-04-24 14:02:51 +0000452 # This is needed to log the user when authentication fails
453 cherrypy.request.login = "{}".format(indata.get("username", "-"))
sousaedu80135b92021-02-17 15:05:18 +0100454 token_info = self.authenticator.new_token(
455 token_info, indata, cherrypy.request.remote
456 )
457 cherrypy.session["Authorization"] = token_info["id"]
tierno1d213f42020-04-24 14:02:51 +0000458 self._set_location_header("admin", "v1", "tokens", token_info["id"])
459 # for logging
460
461 # cherrypy.response.cookie["Authorization"] = outdata["id"]
462 # cherrypy.response.cookie["Authorization"]['expires'] = 3600
sousaedu80135b92021-02-17 15:05:18 +0100463
tierno1d213f42020-04-24 14:02:51 +0000464 return token_info, token_info["id"], True
465
466 def del_token(self, engine_session, indata, version, _id, *args, **kwargs):
467 token_id = _id
sousaedu80135b92021-02-17 15:05:18 +0100468
tierno1d213f42020-04-24 14:02:51 +0000469 if not token_id and "id" in kwargs:
470 token_id = kwargs["id"]
471 elif not token_id:
472 token_info = self.authenticator.authorize()
473 # for logging
474 token_id = token_info["id"]
sousaedu80135b92021-02-17 15:05:18 +0100475
tierno1d213f42020-04-24 14:02:51 +0000476 self.authenticator.del_token(token_id)
477 token_info = None
sousaedu80135b92021-02-17 15:05:18 +0100478 cherrypy.session["Authorization"] = "logout"
tierno1d213f42020-04-24 14:02:51 +0000479 # cherrypy.response.cookie["Authorization"] = token_id
480 # cherrypy.response.cookie["Authorization"]['expires'] = 0
sousaedu80135b92021-02-17 15:05:18 +0100481
tierno1d213f42020-04-24 14:02:51 +0000482 return None, None, True
sousaedu80135b92021-02-17 15:05:18 +0100483
tierno1d213f42020-04-24 14:02:51 +0000484 @cherrypy.expose
485 def test(self, *args, **kwargs):
sousaedu80135b92021-02-17 15:05:18 +0100486 if not cherrypy.config.get("server.enable_test") or (
487 isinstance(cherrypy.config["server.enable_test"], str)
488 and cherrypy.config["server.enable_test"].lower() == "false"
489 ):
tierno1d213f42020-04-24 14:02:51 +0000490 cherrypy.response.status = HTTPStatus.METHOD_NOT_ALLOWED.value
tierno1d213f42020-04-24 14:02:51 +0000491
sousaedu80135b92021-02-17 15:05:18 +0100492 return "test URL is disabled"
493
494 thread_info = None
495
496 if args and args[0] == "help":
497 return (
498 "<html><pre>\ninit\nfile/<name> download file\ndb-clear/table\nfs-clear[/folder]\nlogin\nlogin2\n"
499 "sleep/<time>\nmessage/topic\n</pre></html>"
500 )
tierno1d213f42020-04-24 14:02:51 +0000501 elif args and args[0] == "init":
502 try:
503 # self.ns.load_dbase(cherrypy.request.app.config)
504 self.ns.create_admin()
sousaedu80135b92021-02-17 15:05:18 +0100505
tierno1d213f42020-04-24 14:02:51 +0000506 return "Done. User 'admin', password 'admin' created"
507 except Exception:
508 cherrypy.response.status = HTTPStatus.FORBIDDEN.value
sousaedu80135b92021-02-17 15:05:18 +0100509
tierno1d213f42020-04-24 14:02:51 +0000510 return self._format_out("Database already initialized")
511 elif args and args[0] == "file":
sousaedu80135b92021-02-17 15:05:18 +0100512 return cherrypy.lib.static.serve_file(
513 cherrypy.tree.apps["/ro"].config["storage"]["path"] + "/" + args[1],
514 "text/plain",
515 "attachment",
516 )
tierno1d213f42020-04-24 14:02:51 +0000517 elif args and args[0] == "file2":
sousaedu80135b92021-02-17 15:05:18 +0100518 f_path = cherrypy.tree.apps["/ro"].config["storage"]["path"] + "/" + args[1]
tierno1d213f42020-04-24 14:02:51 +0000519 f = open(f_path, "r")
520 cherrypy.response.headers["Content-type"] = "text/plain"
521 return f
522
523 elif len(args) == 2 and args[0] == "db-clear":
524 deleted_info = self.ns.db.del_list(args[1], kwargs)
525 return "{} {} deleted\n".format(deleted_info["deleted"], args[1])
526 elif len(args) and args[0] == "fs-clear":
527 if len(args) >= 2:
528 folders = (args[1],)
529 else:
530 folders = self.ns.fs.dir_ls(".")
sousaedu80135b92021-02-17 15:05:18 +0100531
tierno1d213f42020-04-24 14:02:51 +0000532 for folder in folders:
533 self.ns.fs.file_delete(folder)
sousaedu80135b92021-02-17 15:05:18 +0100534
tierno1d213f42020-04-24 14:02:51 +0000535 return ",".join(folders) + " folders deleted\n"
536 elif args and args[0] == "login":
537 if not cherrypy.request.headers.get("Authorization"):
sousaedu80135b92021-02-17 15:05:18 +0100538 cherrypy.response.headers[
539 "WWW-Authenticate"
540 ] = 'Basic realm="Access to OSM site", charset="UTF-8"'
tierno1d213f42020-04-24 14:02:51 +0000541 cherrypy.response.status = HTTPStatus.UNAUTHORIZED.value
542 elif args and args[0] == "login2":
543 if not cherrypy.request.headers.get("Authorization"):
sousaedu80135b92021-02-17 15:05:18 +0100544 cherrypy.response.headers[
545 "WWW-Authenticate"
546 ] = 'Bearer realm="Access to OSM site"'
tierno1d213f42020-04-24 14:02:51 +0000547 cherrypy.response.status = HTTPStatus.UNAUTHORIZED.value
548 elif args and args[0] == "sleep":
549 sleep_time = 5
sousaedu80135b92021-02-17 15:05:18 +0100550
tierno1d213f42020-04-24 14:02:51 +0000551 try:
552 sleep_time = int(args[1])
553 except Exception:
554 cherrypy.response.status = HTTPStatus.FORBIDDEN.value
555 return self._format_out("Database already initialized")
sousaedu80135b92021-02-17 15:05:18 +0100556
tierno1d213f42020-04-24 14:02:51 +0000557 thread_info = cherrypy.thread_data
558 print(thread_info)
559 time.sleep(sleep_time)
560 # thread_info
561 elif len(args) >= 2 and args[0] == "message":
562 main_topic = args[1]
563 return_text = "<html><pre>{} ->\n".format(main_topic)
sousaedu80135b92021-02-17 15:05:18 +0100564
tierno1d213f42020-04-24 14:02:51 +0000565 try:
sousaedu80135b92021-02-17 15:05:18 +0100566 if cherrypy.request.method == "POST":
tierno1d213f42020-04-24 14:02:51 +0000567 to_send = yaml.load(cherrypy.request.body, Loader=yaml.SafeLoader)
568 for k, v in to_send.items():
569 self.ns.msg.write(main_topic, k, v)
570 return_text += " {}: {}\n".format(k, v)
sousaedu80135b92021-02-17 15:05:18 +0100571 elif cherrypy.request.method == "GET":
tierno1d213f42020-04-24 14:02:51 +0000572 for k, v in kwargs.items():
sousaedu80135b92021-02-17 15:05:18 +0100573 self.ns.msg.write(
574 main_topic, k, yaml.load(v, Loader=yaml.SafeLoader)
575 )
576 return_text += " {}: {}\n".format(
577 k, yaml.load(v, Loader=yaml.SafeLoader)
578 )
tierno1d213f42020-04-24 14:02:51 +0000579 except Exception as e:
580 return_text += "Error: " + str(e)
sousaedu80135b92021-02-17 15:05:18 +0100581
tierno1d213f42020-04-24 14:02:51 +0000582 return_text += "</pre></html>\n"
sousaedu80135b92021-02-17 15:05:18 +0100583
tierno1d213f42020-04-24 14:02:51 +0000584 return return_text
585
586 return_text = (
sousaedu80135b92021-02-17 15:05:18 +0100587 "<html><pre>\nheaders:\n args: {}\n".format(args)
588 + " kwargs: {}\n".format(kwargs)
589 + " headers: {}\n".format(cherrypy.request.headers)
590 + " path_info: {}\n".format(cherrypy.request.path_info)
591 + " query_string: {}\n".format(cherrypy.request.query_string)
592 + " session: {}\n".format(cherrypy.session)
593 + " cookie: {}\n".format(cherrypy.request.cookie)
594 + " method: {}\n".format(cherrypy.request.method)
595 + " session: {}\n".format(cherrypy.session.get("fieldname"))
596 + " body:\n"
597 )
tierno1d213f42020-04-24 14:02:51 +0000598 return_text += " length: {}\n".format(cherrypy.request.body.length)
sousaedu80135b92021-02-17 15:05:18 +0100599
tierno1d213f42020-04-24 14:02:51 +0000600 if cherrypy.request.body.length:
601 return_text += " content: {}\n".format(
sousaedu80135b92021-02-17 15:05:18 +0100602 str(
603 cherrypy.request.body.read(
604 int(cherrypy.request.headers.get("Content-Length", 0))
605 )
606 )
607 )
608
tierno1d213f42020-04-24 14:02:51 +0000609 if thread_info:
610 return_text += "thread: {}\n".format(thread_info)
sousaedu80135b92021-02-17 15:05:18 +0100611
tierno1d213f42020-04-24 14:02:51 +0000612 return_text += "</pre></html>"
sousaedu80135b92021-02-17 15:05:18 +0100613
tierno1d213f42020-04-24 14:02:51 +0000614 return return_text
615
616 @staticmethod
617 def _check_valid_url_method(method, *args):
618 if len(args) < 3:
sousaedu80135b92021-02-17 15:05:18 +0100619 raise RoException(
620 "URL must contain at least 'main_topic/version/topic'",
621 HTTPStatus.METHOD_NOT_ALLOWED,
622 )
tierno1d213f42020-04-24 14:02:51 +0000623
624 reference = valid_url_methods
625 for arg in args:
626 if arg is None:
627 break
sousaedu80135b92021-02-17 15:05:18 +0100628
tierno1d213f42020-04-24 14:02:51 +0000629 if not isinstance(reference, dict):
sousaedu80135b92021-02-17 15:05:18 +0100630 raise RoException(
631 "URL contains unexpected extra items '{}'".format(arg),
632 HTTPStatus.METHOD_NOT_ALLOWED,
633 )
tierno1d213f42020-04-24 14:02:51 +0000634
635 if arg in reference:
636 reference = reference[arg]
637 elif "<ID>" in reference:
638 reference = reference["<ID>"]
639 elif "*" in reference:
640 # reference = reference["*"]
641 break
642 else:
sousaedu80135b92021-02-17 15:05:18 +0100643 raise RoException(
644 "Unexpected URL item {}".format(arg),
645 HTTPStatus.METHOD_NOT_ALLOWED,
646 )
647
tierno1d213f42020-04-24 14:02:51 +0000648 if "TODO" in reference and method in reference["TODO"]:
sousaedu80135b92021-02-17 15:05:18 +0100649 raise RoException(
650 "Method {} not supported yet for this URL".format(method),
651 HTTPStatus.NOT_IMPLEMENTED,
652 )
tierno1d213f42020-04-24 14:02:51 +0000653 elif "METHODS" not in reference or method not in reference["METHODS"]:
sousaedu80135b92021-02-17 15:05:18 +0100654 raise RoException(
655 "Method {} not supported for this URL".format(method),
656 HTTPStatus.METHOD_NOT_ALLOWED,
657 )
658
tierno1d213f42020-04-24 14:02:51 +0000659 return reference["ROLE_PERMISSION"] + method.lower()
660
661 @staticmethod
662 def _set_location_header(main_topic, version, topic, id):
663 """
664 Insert response header Location with the URL of created item base on URL params
665 :param main_topic:
666 :param version:
667 :param topic:
668 :param id:
669 :return: None
670 """
671 # Use cherrypy.request.base for absoluted path and make use of request.header HOST just in case behind aNAT
sousaedu80135b92021-02-17 15:05:18 +0100672 cherrypy.response.headers["Location"] = "/ro/{}/{}/{}/{}".format(
673 main_topic, version, topic, id
674 )
675
tierno1d213f42020-04-24 14:02:51 +0000676 return
677
678 @cherrypy.expose
sousaedu80135b92021-02-17 15:05:18 +0100679 def default(
680 self,
681 main_topic=None,
682 version=None,
683 topic=None,
684 _id=None,
685 _id2=None,
686 *args,
687 **kwargs,
688 ):
tierno1d213f42020-04-24 14:02:51 +0000689 token_info = None
690 outdata = None
691 _format = None
692 method = "DONE"
693 rollback = []
694 engine_session = None
sousaedu80135b92021-02-17 15:05:18 +0100695
tierno1d213f42020-04-24 14:02:51 +0000696 try:
697 if not main_topic or not version or not topic:
sousaedu80135b92021-02-17 15:05:18 +0100698 raise RoException(
699 "URL must contain at least 'main_topic/version/topic'",
700 HTTPStatus.METHOD_NOT_ALLOWED,
701 )
tierno1d213f42020-04-24 14:02:51 +0000702
sousaedu80135b92021-02-17 15:05:18 +0100703 if main_topic not in (
704 "admin",
705 "ns",
706 ):
707 raise RoException(
708 "URL main_topic '{}' not supported".format(main_topic),
709 HTTPStatus.METHOD_NOT_ALLOWED,
710 )
711
712 if version != "v1":
713 raise RoException(
714 "URL version '{}' not supported".format(version),
715 HTTPStatus.METHOD_NOT_ALLOWED,
716 )
717
718 if (
719 kwargs
720 and "METHOD" in kwargs
721 and kwargs["METHOD"] in ("PUT", "POST", "DELETE", "GET", "PATCH")
722 ):
tierno1d213f42020-04-24 14:02:51 +0000723 method = kwargs.pop("METHOD")
724 else:
725 method = cherrypy.request.method
726
sousaedu80135b92021-02-17 15:05:18 +0100727 role_permission = self._check_valid_url_method(
728 method, main_topic, version, topic, _id, _id2, *args, **kwargs
729 )
tierno1d213f42020-04-24 14:02:51 +0000730 # skip token validation if requesting a token
731 indata = self._format_in(kwargs)
sousaedu80135b92021-02-17 15:05:18 +0100732
tierno1d213f42020-04-24 14:02:51 +0000733 if main_topic != "admin" or topic != "tokens":
734 token_info = self.authenticator.authorize(role_permission, _id)
sousaedu80135b92021-02-17 15:05:18 +0100735
tierno1d213f42020-04-24 14:02:51 +0000736 outdata, created_id, done = self.map_operation[role_permission](
sousaedu80135b92021-02-17 15:05:18 +0100737 engine_session, indata, version, _id, _id2, *args, *kwargs
738 )
739
tierno1d213f42020-04-24 14:02:51 +0000740 if created_id:
741 self._set_location_header(main_topic, version, topic, _id)
sousaedu80135b92021-02-17 15:05:18 +0100742
743 cherrypy.response.status = (
744 HTTPStatus.ACCEPTED.value
745 if not done
746 else HTTPStatus.OK.value
747 if outdata is not None
748 else HTTPStatus.NO_CONTENT.value
749 )
750
tierno1d213f42020-04-24 14:02:51 +0000751 return self._format_out(outdata, token_info, _format)
752 except Exception as e:
sousaedu80135b92021-02-17 15:05:18 +0100753 if isinstance(
754 e,
755 (
756 RoException,
757 NsException,
758 DbException,
759 FsException,
760 MsgException,
761 AuthException,
762 ValidationError,
763 ),
764 ):
tierno1d213f42020-04-24 14:02:51 +0000765 http_code_value = cherrypy.response.status = e.http_code.value
766 http_code_name = e.http_code.name
767 cherrypy.log("Exception {}".format(e))
768 else:
sousaedu80135b92021-02-17 15:05:18 +0100769 http_code_value = (
770 cherrypy.response.status
771 ) = HTTPStatus.BAD_REQUEST.value # INTERNAL_SERVER_ERROR
tierno1d213f42020-04-24 14:02:51 +0000772 cherrypy.log("CRITICAL: Exception {}".format(e), traceback=True)
773 http_code_name = HTTPStatus.BAD_REQUEST.name
sousaedu80135b92021-02-17 15:05:18 +0100774
tierno1d213f42020-04-24 14:02:51 +0000775 if hasattr(outdata, "close"): # is an open file
776 outdata.close()
sousaedu80135b92021-02-17 15:05:18 +0100777
tierno1d213f42020-04-24 14:02:51 +0000778 error_text = str(e)
779 rollback.reverse()
sousaedu80135b92021-02-17 15:05:18 +0100780
tierno1d213f42020-04-24 14:02:51 +0000781 for rollback_item in rollback:
782 try:
783 if rollback_item.get("operation") == "set":
sousaedu80135b92021-02-17 15:05:18 +0100784 self.ns.db.set_one(
785 rollback_item["topic"],
786 {"_id": rollback_item["_id"]},
787 rollback_item["content"],
788 fail_on_empty=False,
789 )
tierno1d213f42020-04-24 14:02:51 +0000790 else:
sousaedu80135b92021-02-17 15:05:18 +0100791 self.ns.db.del_one(
792 rollback_item["topic"],
793 {"_id": rollback_item["_id"]},
794 fail_on_empty=False,
795 )
tierno1d213f42020-04-24 14:02:51 +0000796 except Exception as e2:
sousaedu80135b92021-02-17 15:05:18 +0100797 rollback_error_text = "Rollback Exception {}: {}".format(
798 rollback_item, e2
799 )
tierno1d213f42020-04-24 14:02:51 +0000800 cherrypy.log(rollback_error_text)
801 error_text += ". " + rollback_error_text
sousaedu80135b92021-02-17 15:05:18 +0100802
tierno1d213f42020-04-24 14:02:51 +0000803 # if isinstance(e, MsgException):
804 # error_text = "{} has been '{}' but other modules cannot be informed because an error on bus".format(
805 # engine_topic[:-1], method, error_text)
806 problem_details = {
807 "code": http_code_name,
808 "status": http_code_value,
809 "detail": error_text,
810 }
sousaedu80135b92021-02-17 15:05:18 +0100811
tierno1d213f42020-04-24 14:02:51 +0000812 return self._format_out(problem_details, token_info)
813 # raise cherrypy.HTTPError(e.http_code.value, str(e))
814 finally:
815 if token_info:
816 if method in ("PUT", "PATCH", "POST") and isinstance(outdata, dict):
817 for logging_id in ("id", "op_id", "nsilcmop_id", "nslcmop_id"):
818 if outdata.get(logging_id):
sousaedu80135b92021-02-17 15:05:18 +0100819 cherrypy.request.login += ";{}={}".format(
820 logging_id, outdata[logging_id][:36]
821 )
tierno1d213f42020-04-24 14:02:51 +0000822
823
824def _start_service():
825 """
826 Callback function called when cherrypy.engine starts
827 Override configuration with env variables
828 Set database, storage, message configuration
829 Init database with admin/admin user password
830 """
tierno70eeb182020-10-19 16:38:00 +0000831 global ro_server, vim_admin_thread
tierno1d213f42020-04-24 14:02:51 +0000832 # global vim_threads
833 cherrypy.log.error("Starting osm_ng_ro")
834 # update general cherrypy configuration
835 update_dict = {}
sousaedu80135b92021-02-17 15:05:18 +0100836 engine_config = cherrypy.tree.apps["/ro"].config
tierno1d213f42020-04-24 14:02:51 +0000837
tierno1d213f42020-04-24 14:02:51 +0000838 for k, v in environ.items():
839 if not k.startswith("OSMRO_"):
840 continue
sousaedu80135b92021-02-17 15:05:18 +0100841
tierno1d213f42020-04-24 14:02:51 +0000842 k1, _, k2 = k[6:].lower().partition("_")
sousaedu80135b92021-02-17 15:05:18 +0100843
tierno1d213f42020-04-24 14:02:51 +0000844 if not k2:
845 continue
sousaedu80135b92021-02-17 15:05:18 +0100846
tierno1d213f42020-04-24 14:02:51 +0000847 try:
848 if k1 in ("server", "test", "auth", "log"):
849 # update [global] configuration
sousaedu80135b92021-02-17 15:05:18 +0100850 update_dict[k1 + "." + k2] = yaml.safe_load(v)
tierno1d213f42020-04-24 14:02:51 +0000851 elif k1 == "static":
852 # update [/static] configuration
853 engine_config["/static"]["tools.staticdir." + k2] = yaml.safe_load(v)
854 elif k1 == "tools":
855 # update [/] configuration
sousaedu80135b92021-02-17 15:05:18 +0100856 engine_config["/"]["tools." + k2.replace("_", ".")] = yaml.safe_load(v)
aticig1ac189e2022-06-30 19:29:04 +0300857 elif k1 in ("message", "database", "storage", "authentication", "period"):
tierno70eeb182020-10-19 16:38:00 +0000858 engine_config[k1][k2] = yaml.safe_load(v)
tierno1d213f42020-04-24 14:02:51 +0000859
860 except Exception as e:
861 raise RoException("Cannot load env '{}': {}".format(k, e))
862
863 if update_dict:
864 cherrypy.config.update(update_dict)
865 engine_config["global"].update(update_dict)
866
867 # logging cherrypy
sousaedu80135b92021-02-17 15:05:18 +0100868 log_format_simple = (
869 "%(asctime)s %(levelname)s %(name)s %(filename)s:%(lineno)s %(message)s"
870 )
871 log_formatter_simple = logging.Formatter(
872 log_format_simple, datefmt="%Y-%m-%dT%H:%M:%S"
873 )
tierno1d213f42020-04-24 14:02:51 +0000874 logger_server = logging.getLogger("cherrypy.error")
875 logger_access = logging.getLogger("cherrypy.access")
876 logger_cherry = logging.getLogger("cherrypy")
sousaedue493e9b2021-02-09 15:30:01 +0100877 logger = logging.getLogger("ro")
tierno1d213f42020-04-24 14:02:51 +0000878
879 if "log.file" in engine_config["global"]:
sousaedu80135b92021-02-17 15:05:18 +0100880 file_handler = logging.handlers.RotatingFileHandler(
881 engine_config["global"]["log.file"], maxBytes=100e6, backupCount=9, delay=0
882 )
tierno1d213f42020-04-24 14:02:51 +0000883 file_handler.setFormatter(log_formatter_simple)
884 logger_cherry.addHandler(file_handler)
sousaedue493e9b2021-02-09 15:30:01 +0100885 logger.addHandler(file_handler)
sousaedu80135b92021-02-17 15:05:18 +0100886
tierno1d213f42020-04-24 14:02:51 +0000887 # log always to standard output
sousaedu80135b92021-02-17 15:05:18 +0100888 for format_, logger in {
889 "ro.server %(filename)s:%(lineno)s": logger_server,
890 "ro.access %(filename)s:%(lineno)s": logger_access,
891 "%(name)s %(filename)s:%(lineno)s": logger,
892 }.items():
tierno1d213f42020-04-24 14:02:51 +0000893 log_format_cherry = "%(asctime)s %(levelname)s {} %(message)s".format(format_)
sousaedu80135b92021-02-17 15:05:18 +0100894 log_formatter_cherry = logging.Formatter(
895 log_format_cherry, datefmt="%Y-%m-%dT%H:%M:%S"
896 )
tierno1d213f42020-04-24 14:02:51 +0000897 str_handler = logging.StreamHandler()
898 str_handler.setFormatter(log_formatter_cherry)
899 logger.addHandler(str_handler)
900
901 if engine_config["global"].get("log.level"):
902 logger_cherry.setLevel(engine_config["global"]["log.level"])
sousaedue493e9b2021-02-09 15:30:01 +0100903 logger.setLevel(engine_config["global"]["log.level"])
sousaedu80135b92021-02-17 15:05:18 +0100904
tierno1d213f42020-04-24 14:02:51 +0000905 # logging other modules
sousaedu80135b92021-02-17 15:05:18 +0100906 for k1, logname in {
907 "message": "ro.msg",
908 "database": "ro.db",
909 "storage": "ro.fs",
910 }.items():
tierno1d213f42020-04-24 14:02:51 +0000911 engine_config[k1]["logger_name"] = logname
912 logger_module = logging.getLogger(logname)
sousaedu80135b92021-02-17 15:05:18 +0100913
tierno1d213f42020-04-24 14:02:51 +0000914 if "logfile" in engine_config[k1]:
sousaedu80135b92021-02-17 15:05:18 +0100915 file_handler = logging.handlers.RotatingFileHandler(
916 engine_config[k1]["logfile"], maxBytes=100e6, backupCount=9, delay=0
917 )
tierno1d213f42020-04-24 14:02:51 +0000918 file_handler.setFormatter(log_formatter_simple)
919 logger_module.addHandler(file_handler)
sousaedu80135b92021-02-17 15:05:18 +0100920
tierno1d213f42020-04-24 14:02:51 +0000921 if "loglevel" in engine_config[k1]:
922 logger_module.setLevel(engine_config[k1]["loglevel"])
923 # TODO add more entries, e.g.: storage
924
925 engine_config["assignment"] = {}
926 # ^ each VIM, SDNc will be assigned one worker id. Ns class will add items and VimThread will auto-assign
sousaedu80135b92021-02-17 15:05:18 +0100927 cherrypy.tree.apps["/ro"].root.ns.start(engine_config)
928 cherrypy.tree.apps["/ro"].root.authenticator.start(engine_config)
929 cherrypy.tree.apps["/ro"].root.ns.init_db(target_version=database_version)
tierno1d213f42020-04-24 14:02:51 +0000930
931 # # start subscriptions thread:
tierno70eeb182020-10-19 16:38:00 +0000932 vim_admin_thread = VimAdminThread(config=engine_config, engine=ro_server.ns)
933 vim_admin_thread.start()
tierno1d213f42020-04-24 14:02:51 +0000934 # # Do not capture except SubscriptionException
935
tierno70eeb182020-10-19 16:38:00 +0000936 # backend = engine_config["authentication"]["backend"]
937 # cherrypy.log.error("Starting OSM NBI Version '{} {}' with '{}' authentication backend"
938 # .format(ro_version, ro_version_date, backend))
tierno1d213f42020-04-24 14:02:51 +0000939
940
941def _stop_service():
942 """
943 Callback function called when cherrypy.engine stops
944 TODO: Ending database connections.
945 """
tierno70eeb182020-10-19 16:38:00 +0000946 global vim_admin_thread
sousaedu80135b92021-02-17 15:05:18 +0100947
tierno70eeb182020-10-19 16:38:00 +0000948 # terminate vim_admin_thread
949 if vim_admin_thread:
950 vim_admin_thread.terminate()
sousaedu80135b92021-02-17 15:05:18 +0100951
tierno70eeb182020-10-19 16:38:00 +0000952 vim_admin_thread = None
sousaedu80135b92021-02-17 15:05:18 +0100953 cherrypy.tree.apps["/ro"].root.ns.stop()
tierno1d213f42020-04-24 14:02:51 +0000954 cherrypy.log.error("Stopping osm_ng_ro")
955
956
957def ro_main(config_file):
958 global ro_server
sousaedu80135b92021-02-17 15:05:18 +0100959
tierno1d213f42020-04-24 14:02:51 +0000960 ro_server = Server()
sousaedu80135b92021-02-17 15:05:18 +0100961 cherrypy.engine.subscribe("start", _start_service)
962 cherrypy.engine.subscribe("stop", _stop_service)
963 cherrypy.quickstart(ro_server, "/ro", config_file)
tierno1d213f42020-04-24 14:02:51 +0000964
965
966def usage():
sousaedu80135b92021-02-17 15:05:18 +0100967 print(
968 """Usage: {} [options]
tierno1d213f42020-04-24 14:02:51 +0000969 -c|--config [configuration_file]: loads the configuration file (default: ./ro.cfg)
970 -h|--help: shows this help
sousaedu80135b92021-02-17 15:05:18 +0100971 """.format(
972 sys.argv[0]
973 )
974 )
tierno1d213f42020-04-24 14:02:51 +0000975 # --log-socket-host HOST: send logs to this host")
976 # --log-socket-port PORT: send logs using this port (default: 9022)")
977
978
sousaedu80135b92021-02-17 15:05:18 +0100979if __name__ == "__main__":
tierno1d213f42020-04-24 14:02:51 +0000980 try:
981 # load parameters and configuration
982 opts, args = getopt.getopt(sys.argv[1:], "hvc:", ["config=", "help"])
983 # TODO add "log-socket-host=", "log-socket-port=", "log-file="
984 config_file = None
sousaedu80135b92021-02-17 15:05:18 +0100985
tierno1d213f42020-04-24 14:02:51 +0000986 for o, a in opts:
987 if o in ("-h", "--help"):
988 usage()
989 sys.exit()
990 elif o in ("-c", "--config"):
991 config_file = a
992 else:
993 assert False, "Unhandled option"
sousaedu80135b92021-02-17 15:05:18 +0100994
tierno1d213f42020-04-24 14:02:51 +0000995 if config_file:
996 if not path.isfile(config_file):
sousaedu80135b92021-02-17 15:05:18 +0100997 print(
998 "configuration file '{}' that not exist".format(config_file),
999 file=sys.stderr,
1000 )
tierno1d213f42020-04-24 14:02:51 +00001001 exit(1)
1002 else:
sousaedu80135b92021-02-17 15:05:18 +01001003 for config_file in (
1004 path.dirname(__file__) + "/ro.cfg",
1005 "./ro.cfg",
1006 "/etc/osm/ro.cfg",
1007 ):
tierno1d213f42020-04-24 14:02:51 +00001008 if path.isfile(config_file):
1009 break
1010 else:
sousaedu80135b92021-02-17 15:05:18 +01001011 print(
1012 "No configuration file 'ro.cfg' found neither at local folder nor at /etc/osm/",
1013 file=sys.stderr,
1014 )
tierno1d213f42020-04-24 14:02:51 +00001015 exit(1)
sousaedu80135b92021-02-17 15:05:18 +01001016
tierno1d213f42020-04-24 14:02:51 +00001017 ro_main(config_file)
tierno70eeb182020-10-19 16:38:00 +00001018 except KeyboardInterrupt:
1019 print("KeyboardInterrupt. Finishing", file=sys.stderr)
tierno1d213f42020-04-24 14:02:51 +00001020 except getopt.GetoptError as e:
1021 print(str(e), file=sys.stderr)
1022 # usage()
1023 exit(1)