| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 1 | #!/usr/bin/python3 |
| 2 | # -*- coding: utf-8 -*- |
| 3 | |
| 4 | import cherrypy |
| 5 | import time |
| 6 | import json |
| 7 | import yaml |
| 8 | import html_out as html |
| 9 | import logging |
| tierno | f5298be | 2018-05-16 14:43:57 +0200 | [diff] [blame] | 10 | import logging.handlers |
| 11 | import getopt |
| 12 | import sys |
| Eduardo Sousa | 2f98821 | 2018-07-26 01:04:11 +0100 | [diff] [blame] | 13 | |
| Eduardo Sousa | 819d34c | 2018-07-31 01:20:02 +0100 | [diff] [blame] | 14 | from authconn import AuthException |
| Eduardo Sousa | 2f98821 | 2018-07-26 01:04:11 +0100 | [diff] [blame] | 15 | from auth import Authenticator |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 16 | from engine import Engine, EngineException |
| tierno | a8d6363 | 2018-05-10 13:12:32 +0200 | [diff] [blame] | 17 | from osm_common.dbbase import DbException |
| 18 | from osm_common.fsbase import FsException |
| 19 | from osm_common.msgbase import MsgException |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 20 | from http import HTTPStatus |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 21 | from codecs import getreader |
| tierno | f5298be | 2018-05-16 14:43:57 +0200 | [diff] [blame] | 22 | from os import environ, path |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 23 | |
| 24 | __author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>" |
| tierno | dfe0957 | 2018-04-24 10:41:10 +0200 | [diff] [blame] | 25 | |
| 26 | # TODO consider to remove and provide version using the static version file |
| 27 | __version__ = "0.1.3" |
| tierno | 55945e7 | 2018-04-06 16:40:27 +0200 | [diff] [blame] | 28 | version_date = "Apr 2018" |
| tierno | 4a946e4 | 2018-04-12 17:48:49 +0200 | [diff] [blame] | 29 | database_version = '1.0' |
| Eduardo Sousa | 819d34c | 2018-07-31 01:20:02 +0100 | [diff] [blame] | 30 | auth_database_version = '1.0' |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 31 | |
| 32 | """ |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 33 | North Bound Interface (O: OSM specific; 5,X: SOL005 not implemented yet; O5: SOL005 implemented) |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 34 | URL: /osm GET POST PUT DELETE PATCH |
| garciadeblas | 9750c5a | 2018-10-15 16:20:35 +0200 | [diff] [blame] | 35 | /nsd/v1 |
| tierno | 2236d20 | 2018-05-16 19:05:16 +0200 | [diff] [blame] | 36 | /ns_descriptors_content O O |
| 37 | /<nsdInfoId> O O O O |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 38 | /ns_descriptors O5 O5 |
| 39 | /<nsdInfoId> O5 O5 5 |
| 40 | /nsd_content O5 O5 |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 41 | /nsd O |
| 42 | /artifacts[/<artifactPath>] O |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 43 | /pnf_descriptors 5 5 |
| 44 | /<pnfdInfoId> 5 5 5 |
| 45 | /pnfd_content 5 5 |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 46 | /subscriptions 5 5 |
| 47 | /<subscriptionId> 5 X |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 48 | |
| 49 | /vnfpkgm/v1 |
| tierno | 55945e7 | 2018-04-06 16:40:27 +0200 | [diff] [blame] | 50 | /vnf_packages_content O O |
| tierno | 2236d20 | 2018-05-16 19:05:16 +0200 | [diff] [blame] | 51 | /<vnfPkgId> O O |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 52 | /vnf_packages O5 O5 |
| 53 | /<vnfPkgId> O5 O5 5 |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 54 | /package_content O5 O5 |
| 55 | /upload_from_uri X |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 56 | /vnfd O5 |
| 57 | /artifacts[/<artifactPath>] O5 |
| 58 | /subscriptions X X |
| 59 | /<subscriptionId> X X |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 60 | |
| 61 | /nslcm/v1 |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 62 | /ns_instances_content O O |
| tierno | 2236d20 | 2018-05-16 19:05:16 +0200 | [diff] [blame] | 63 | /<nsInstanceId> O O |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 64 | /ns_instances 5 5 |
| tierno | 9569244 | 2018-05-24 18:05:28 +0200 | [diff] [blame] | 65 | /<nsInstanceId> O5 O5 |
| tierno | 65acb4d | 2018-04-06 16:42:40 +0200 | [diff] [blame] | 66 | instantiate O5 |
| 67 | terminate O5 |
| 68 | action O |
| 69 | scale O5 |
| 70 | heal 5 |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 71 | /ns_lcm_op_occs 5 5 |
| 72 | /<nsLcmOpOccId> 5 5 5 |
| 73 | TO BE COMPLETED 5 5 |
| tierno | f759d82 | 2018-06-11 18:54:54 +0200 | [diff] [blame] | 74 | /vnf_instances (also vnfrs for compatibility) O |
| 75 | /<vnfInstanceId> O |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 76 | /subscriptions 5 5 |
| 77 | /<subscriptionId> 5 X |
| garciadeblas | 9750c5a | 2018-10-15 16:20:35 +0200 | [diff] [blame] | 78 | |
| tierno | cb83c94 | 2018-09-24 17:28:13 +0200 | [diff] [blame] | 79 | /pdu/v1 |
| 80 | /pdu_descriptor O O |
| 81 | /<id> O O O O |
| garciadeblas | 9750c5a | 2018-10-15 16:20:35 +0200 | [diff] [blame] | 82 | |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 83 | /admin/v1 |
| 84 | /tokens O O |
| tierno | 2236d20 | 2018-05-16 19:05:16 +0200 | [diff] [blame] | 85 | /<id> O O |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 86 | /users O O |
| tierno | cd54a4a | 2018-09-12 16:40:35 +0200 | [diff] [blame] | 87 | /<id> O O O O |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 88 | /projects O O |
| tierno | 2236d20 | 2018-05-16 19:05:16 +0200 | [diff] [blame] | 89 | /<id> O O |
| tierno | 09c073e | 2018-04-26 13:36:48 +0200 | [diff] [blame] | 90 | /vims_accounts (also vims for compatibility) O O |
| tierno | 2236d20 | 2018-05-16 19:05:16 +0200 | [diff] [blame] | 91 | /<id> O O O |
| tierno | 0f98af5 | 2018-03-19 10:28:22 +0100 | [diff] [blame] | 92 | /sdns O O |
| tierno | 2236d20 | 2018-05-16 19:05:16 +0200 | [diff] [blame] | 93 | /<id> O O O |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 94 | |
| garciadeblas | 9750c5a | 2018-10-15 16:20:35 +0200 | [diff] [blame] | 95 | /nst/v1 O O |
| 96 | /netslice_templates_content O O |
| 97 | /<nstInfoId> O O O O |
| 98 | /netslice_templates O O |
| 99 | /<nstInfoId> O O O |
| 100 | /nst_content O O |
| 101 | /nst O |
| 102 | /artifacts[/<artifactPath>] O |
| 103 | /subscriptions X X |
| 104 | /<subscriptionId> X X |
| 105 | |
| 106 | /nsilcm/v1 |
| 107 | /netslice_instances_content O O |
| 108 | /<SliceInstanceId> O O |
| 109 | /netslice_instances O O |
| 110 | /<SliceInstanceId> O O |
| 111 | instantiate O |
| 112 | terminate O |
| 113 | action O |
| 114 | /nsi_lcm_op_occs O O |
| 115 | /<nsiLcmOpOccId> O O O |
| 116 | /subscriptions X X |
| 117 | /<subscriptionId> X X |
| 118 | |
| tierno | 2236d20 | 2018-05-16 19:05:16 +0200 | [diff] [blame] | 119 | query string: |
| 120 | Follows SOL005 section 4.3.2 It contains extra METHOD to override http method, FORCE to force. |
| 121 | For filtering inside array, it must select the element of the array, or add ANYINDEX to apply the filtering over any |
| 122 | item of the array, that is, pass if any item of the array pass the filter. |
| 123 | It allows both ne and neq for not equal |
| 124 | TODO: 4.3.3 Attribute selectors |
| 125 | all_fields, fields=x,y,.., exclude_default, exclude_fields=x,y,... |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 126 | (none) … same as “exclude_default” |
| 127 | all_fields … all attributes. |
| tierno | 2236d20 | 2018-05-16 19:05:16 +0200 | [diff] [blame] | 128 | fields=<list> … all attributes except all complex attributes with minimum cardinality of zero that are not |
| 129 | conditionally mandatory, and that are not provided in <list>. |
| 130 | exclude_fields=<list> … all attributes except those complex attributes with a minimum cardinality of zero that |
| 131 | are not conditionally mandatory, and that are provided in <list>. |
| 132 | exclude_default … all attributes except those complex attributes with a minimum cardinality of zero that are not |
| 133 | conditionally mandatory, and that are part of the "default exclude set" defined in the present specification for |
| 134 | the particular resource |
| 135 | exclude_default and include=<list> … all attributes except those complex attributes with a minimum cardinality |
| 136 | of zero that are not conditionally mandatory and that are part of the "default exclude set" defined in the |
| 137 | present specification for the particular resource, but that are not part of <list> |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 138 | Header field name Reference Example Descriptions |
| 139 | Accept IETF RFC 7231 [19] application/json Content-Types that are acceptable for the response. |
| 140 | This header field shall be present if the response is expected to have a non-empty message body. |
| 141 | Content-Type IETF RFC 7231 [19] application/json The MIME type of the body of the request. |
| 142 | This header field shall be present if the request has a non-empty message body. |
| tierno | 2236d20 | 2018-05-16 19:05:16 +0200 | [diff] [blame] | 143 | Authorization IETF RFC 7235 [22] Bearer mF_9.B5f-4.1JqM The authorization token for the request. |
| 144 | Details are specified in clause 4.5.3. |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 145 | Range IETF RFC 7233 [21] 1000-2000 Requested range of bytes from a file |
| 146 | Header field name Reference Example Descriptions |
| 147 | Content-Type IETF RFC 7231 [19] application/json The MIME type of the body of the response. |
| 148 | This header field shall be present if the response has a non-empty message body. |
| tierno | 2236d20 | 2018-05-16 19:05:16 +0200 | [diff] [blame] | 149 | Location IETF RFC 7231 [19] http://www.example.com/vnflcm/v1/vnf_instances/123 Used in redirection, or when a |
| 150 | new resource has been created. |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 151 | This header field shall be present if the response status code is 201 or 3xx. |
| tierno | 2236d20 | 2018-05-16 19:05:16 +0200 | [diff] [blame] | 152 | In the present document this header field is also used if the response status code is 202 and a new resource was |
| 153 | created. |
| 154 | WWW-Authenticate IETF RFC 7235 [22] Bearer realm="example" Challenge if the corresponding HTTP request has not |
| 155 | provided authorization, or error details if the corresponding HTTP request has provided an invalid authorization |
| 156 | token. |
| 157 | Accept-Ranges IETF RFC 7233 [21] bytes Used by the Server to signal whether or not it supports ranges for |
| 158 | certain resources. |
| 159 | Content-Range IETF RFC 7233 [21] bytes 21010-47021/ 47022 Signals the byte range that is contained in the |
| 160 | response, and the total length of the file. |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 161 | Retry-After IETF RFC 7231 [19] Fri, 31 Dec 1999 23:59:59 GMT |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 162 | """ |
| 163 | |
| 164 | |
| 165 | class NbiException(Exception): |
| 166 | |
| 167 | def __init__(self, message, http_code=HTTPStatus.METHOD_NOT_ALLOWED): |
| 168 | Exception.__init__(self, message) |
| 169 | self.http_code = http_code |
| 170 | |
| 171 | |
| 172 | class Server(object): |
| 173 | instance = 0 |
| 174 | # to decode bytes to str |
| 175 | reader = getreader("utf-8") |
| 176 | |
| 177 | def __init__(self): |
| 178 | self.instance += 1 |
| 179 | self.engine = Engine() |
| Eduardo Sousa | d1b525d | 2018-10-04 04:24:18 +0100 | [diff] [blame] | 180 | self.authenticator = Authenticator() |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 181 | self.valid_methods = { # contains allowed URL and methods |
| 182 | "admin": { |
| 183 | "v1": { |
| tierno | 0f98af5 | 2018-03-19 10:28:22 +0100 | [diff] [blame] | 184 | "tokens": {"METHODS": ("GET", "POST", "DELETE"), |
| tierno | 2236d20 | 2018-05-16 19:05:16 +0200 | [diff] [blame] | 185 | "<ID>": {"METHODS": ("GET", "DELETE")} |
| 186 | }, |
| tierno | 0f98af5 | 2018-03-19 10:28:22 +0100 | [diff] [blame] | 187 | "users": {"METHODS": ("GET", "POST"), |
| tierno | cd54a4a | 2018-09-12 16:40:35 +0200 | [diff] [blame] | 188 | "<ID>": {"METHODS": ("GET", "POST", "DELETE", "PATCH", "PUT")} |
| tierno | 2236d20 | 2018-05-16 19:05:16 +0200 | [diff] [blame] | 189 | }, |
| tierno | 0f98af5 | 2018-03-19 10:28:22 +0100 | [diff] [blame] | 190 | "projects": {"METHODS": ("GET", "POST"), |
| tierno | 2236d20 | 2018-05-16 19:05:16 +0200 | [diff] [blame] | 191 | "<ID>": {"METHODS": ("GET", "DELETE")} |
| 192 | }, |
| tierno | 0f98af5 | 2018-03-19 10:28:22 +0100 | [diff] [blame] | 193 | "vims": {"METHODS": ("GET", "POST"), |
| tierno | 7ae1011 | 2018-05-18 14:36:02 +0200 | [diff] [blame] | 194 | "<ID>": {"METHODS": ("GET", "DELETE", "PATCH", "PUT")} |
| tierno | 2236d20 | 2018-05-16 19:05:16 +0200 | [diff] [blame] | 195 | }, |
| tierno | 09c073e | 2018-04-26 13:36:48 +0200 | [diff] [blame] | 196 | "vim_accounts": {"METHODS": ("GET", "POST"), |
| tierno | 7ae1011 | 2018-05-18 14:36:02 +0200 | [diff] [blame] | 197 | "<ID>": {"METHODS": ("GET", "DELETE", "PATCH", "PUT")} |
| tierno | 2236d20 | 2018-05-16 19:05:16 +0200 | [diff] [blame] | 198 | }, |
| tierno | 0f98af5 | 2018-03-19 10:28:22 +0100 | [diff] [blame] | 199 | "sdns": {"METHODS": ("GET", "POST"), |
| tierno | 7ae1011 | 2018-05-18 14:36:02 +0200 | [diff] [blame] | 200 | "<ID>": {"METHODS": ("GET", "DELETE", "PATCH", "PUT")} |
| tierno | 2236d20 | 2018-05-16 19:05:16 +0200 | [diff] [blame] | 201 | }, |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 202 | } |
| 203 | }, |
| tierno | cb83c94 | 2018-09-24 17:28:13 +0200 | [diff] [blame] | 204 | "pdu": { |
| 205 | "v1": { |
| 206 | "pdu_descriptors": {"METHODS": ("GET", "POST"), |
| 207 | "<ID>": {"METHODS": ("GET", "POST", "DELETE", "PATCH", "PUT")} |
| 208 | }, |
| 209 | } |
| 210 | }, |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 211 | "nsd": { |
| 212 | "v1": { |
| tierno | 2236d20 | 2018-05-16 19:05:16 +0200 | [diff] [blame] | 213 | "ns_descriptors_content": {"METHODS": ("GET", "POST"), |
| 214 | "<ID>": {"METHODS": ("GET", "PUT", "DELETE")} |
| 215 | }, |
| 216 | "ns_descriptors": {"METHODS": ("GET", "POST"), |
| 217 | "<ID>": {"METHODS": ("GET", "DELETE"), "TODO": "PATCH", |
| 218 | "nsd_content": {"METHODS": ("GET", "PUT")}, |
| 219 | "nsd": {"METHODS": "GET"}, # descriptor inside package |
| 220 | "artifacts": {"*": {"METHODS": "GET"}} |
| 221 | } |
| 222 | }, |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 223 | "pnf_descriptors": {"TODO": ("GET", "POST"), |
| tierno | 2236d20 | 2018-05-16 19:05:16 +0200 | [diff] [blame] | 224 | "<ID>": {"TODO": ("GET", "DELETE", "PATCH"), |
| 225 | "pnfd_content": {"TODO": ("GET", "PUT")} |
| 226 | } |
| 227 | }, |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 228 | "subscriptions": {"TODO": ("GET", "POST"), |
| tierno | 2236d20 | 2018-05-16 19:05:16 +0200 | [diff] [blame] | 229 | "<ID>": {"TODO": ("GET", "DELETE")} |
| 230 | }, |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 231 | } |
| 232 | }, |
| 233 | "vnfpkgm": { |
| 234 | "v1": { |
| tierno | 2236d20 | 2018-05-16 19:05:16 +0200 | [diff] [blame] | 235 | "vnf_packages_content": {"METHODS": ("GET", "POST"), |
| 236 | "<ID>": {"METHODS": ("GET", "PUT", "DELETE")} |
| 237 | }, |
| 238 | "vnf_packages": {"METHODS": ("GET", "POST"), |
| tierno | aae4dc4 | 2018-06-11 18:55:50 +0200 | [diff] [blame] | 239 | "<ID>": {"METHODS": ("GET", "DELETE", "PATCH"), # GET: vnfPkgInfo |
| tierno | 2236d20 | 2018-05-16 19:05:16 +0200 | [diff] [blame] | 240 | "package_content": {"METHODS": ("GET", "PUT"), # package |
| 241 | "upload_from_uri": {"TODO": "POST"} |
| 242 | }, |
| 243 | "vnfd": {"METHODS": "GET"}, # descriptor inside package |
| 244 | "artifacts": {"*": {"METHODS": "GET"}} |
| 245 | } |
| 246 | }, |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 247 | "subscriptions": {"TODO": ("GET", "POST"), |
| tierno | 2236d20 | 2018-05-16 19:05:16 +0200 | [diff] [blame] | 248 | "<ID>": {"TODO": ("GET", "DELETE")} |
| 249 | }, |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 250 | } |
| 251 | }, |
| 252 | "nslcm": { |
| 253 | "v1": { |
| 254 | "ns_instances_content": {"METHODS": ("GET", "POST"), |
| tierno | 2236d20 | 2018-05-16 19:05:16 +0200 | [diff] [blame] | 255 | "<ID>": {"METHODS": ("GET", "DELETE")} |
| 256 | }, |
| tierno | 65acb4d | 2018-04-06 16:42:40 +0200 | [diff] [blame] | 257 | "ns_instances": {"METHODS": ("GET", "POST"), |
| tierno | 9569244 | 2018-05-24 18:05:28 +0200 | [diff] [blame] | 258 | "<ID>": {"METHODS": ("GET", "DELETE"), |
| tierno | f759d82 | 2018-06-11 18:54:54 +0200 | [diff] [blame] | 259 | "scale": {"METHODS": "POST"}, |
| tierno | 2236d20 | 2018-05-16 19:05:16 +0200 | [diff] [blame] | 260 | "terminate": {"METHODS": "POST"}, |
| 261 | "instantiate": {"METHODS": "POST"}, |
| 262 | "action": {"METHODS": "POST"}, |
| 263 | } |
| 264 | }, |
| tierno | 65acb4d | 2018-04-06 16:42:40 +0200 | [diff] [blame] | 265 | "ns_lcm_op_occs": {"METHODS": "GET", |
| tierno | 2236d20 | 2018-05-16 19:05:16 +0200 | [diff] [blame] | 266 | "<ID>": {"METHODS": "GET"}, |
| 267 | }, |
| tierno | 0ffaa99 | 2018-05-09 13:21:56 +0200 | [diff] [blame] | 268 | "vnfrs": {"METHODS": ("GET"), |
| tierno | 2236d20 | 2018-05-16 19:05:16 +0200 | [diff] [blame] | 269 | "<ID>": {"METHODS": ("GET")} |
| 270 | }, |
| tierno | f759d82 | 2018-06-11 18:54:54 +0200 | [diff] [blame] | 271 | "vnf_instances": {"METHODS": ("GET"), |
| 272 | "<ID>": {"METHODS": ("GET")} |
| 273 | }, |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 274 | } |
| 275 | }, |
| garciadeblas | 9750c5a | 2018-10-15 16:20:35 +0200 | [diff] [blame] | 276 | "nst": { |
| 277 | "v1": { |
| 278 | "netslice_templates_content": {"METHODS": ("GET", "POST"), |
| 279 | "<ID>": {"METHODS": ("GET", "PUT", "DELETE")} |
| 280 | }, |
| 281 | "netslice_templates": {"METHODS": ("GET", "POST"), |
| 282 | "<ID>": {"METHODS": ("GET", "DELETE"), "TODO": "PATCH", |
| 283 | "nst_content": {"METHODS": ("GET", "PUT")}, |
| 284 | "nst": {"METHODS": "GET"}, # descriptor inside package |
| 285 | "artifacts": {"*": {"METHODS": "GET"}} |
| 286 | } |
| 287 | }, |
| 288 | "subscriptions": {"TODO": ("GET", "POST"), |
| 289 | "<ID>": {"TODO": ("GET", "DELETE")} |
| 290 | }, |
| 291 | } |
| 292 | }, |
| 293 | "nsilcm": { |
| 294 | "v1": { |
| 295 | "netslice_instances_content": {"METHODS": ("GET", "POST"), |
| 296 | "<ID>": {"METHODS": ("GET", "DELETE")} |
| 297 | }, |
| 298 | "netslice_instances": {"METHODS": ("GET", "POST"), |
| 299 | "<ID>": {"METHODS": ("GET", "DELETE"), |
| 300 | "terminate": {"METHODS": "POST"}, |
| 301 | "instantiate": {"METHODS": "POST"}, |
| 302 | "action": {"METHODS": "POST"}, |
| 303 | } |
| 304 | }, |
| 305 | "nsi_lcm_op_occs": {"METHODS": "GET", |
| 306 | "<ID>": {"METHODS": "GET"}, |
| 307 | }, |
| 308 | } |
| 309 | }, |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 310 | } |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 311 | |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 312 | def _format_in(self, kwargs): |
| 313 | try: |
| 314 | indata = None |
| 315 | if cherrypy.request.body.length: |
| 316 | error_text = "Invalid input format " |
| 317 | |
| 318 | if "Content-Type" in cherrypy.request.headers: |
| 319 | if "application/json" in cherrypy.request.headers["Content-Type"]: |
| 320 | error_text = "Invalid json format " |
| 321 | indata = json.load(self.reader(cherrypy.request.body)) |
| gcalvino | de4adfe | 2018-10-30 11:46:09 +0100 | [diff] [blame] | 322 | cherrypy.request.headers.pop("Content-File-MD5", None) |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 323 | elif "application/yaml" in cherrypy.request.headers["Content-Type"]: |
| 324 | error_text = "Invalid yaml format " |
| 325 | indata = yaml.load(cherrypy.request.body) |
| gcalvino | de4adfe | 2018-10-30 11:46:09 +0100 | [diff] [blame] | 326 | cherrypy.request.headers.pop("Content-File-MD5", None) |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 327 | elif "application/binary" in cherrypy.request.headers["Content-Type"] or \ |
| 328 | "application/gzip" in cherrypy.request.headers["Content-Type"] or \ |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 329 | "application/zip" in cherrypy.request.headers["Content-Type"] or \ |
| 330 | "text/plain" in cherrypy.request.headers["Content-Type"]: |
| 331 | indata = cherrypy.request.body # .read() |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 332 | elif "multipart/form-data" in cherrypy.request.headers["Content-Type"]: |
| 333 | if "descriptor_file" in kwargs: |
| 334 | filecontent = kwargs.pop("descriptor_file") |
| 335 | if not filecontent.file: |
| 336 | raise NbiException("empty file or content", HTTPStatus.BAD_REQUEST) |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 337 | indata = filecontent.file # .read() |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 338 | if filecontent.content_type.value: |
| 339 | cherrypy.request.headers["Content-Type"] = filecontent.content_type.value |
| 340 | else: |
| 341 | # raise cherrypy.HTTPError(HTTPStatus.Not_Acceptable, |
| 342 | # "Only 'Content-Type' of type 'application/json' or |
| 343 | # 'application/yaml' for input format are available") |
| 344 | error_text = "Invalid yaml format " |
| 345 | indata = yaml.load(cherrypy.request.body) |
| gcalvino | de4adfe | 2018-10-30 11:46:09 +0100 | [diff] [blame] | 346 | cherrypy.request.headers.pop("Content-File-MD5", None) |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 347 | else: |
| 348 | error_text = "Invalid yaml format " |
| 349 | indata = yaml.load(cherrypy.request.body) |
| gcalvino | de4adfe | 2018-10-30 11:46:09 +0100 | [diff] [blame] | 350 | cherrypy.request.headers.pop("Content-File-MD5", None) |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 351 | if not indata: |
| 352 | indata = {} |
| 353 | |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 354 | format_yaml = False |
| 355 | if cherrypy.request.headers.get("Query-String-Format") == "yaml": |
| 356 | format_yaml = True |
| 357 | |
| 358 | for k, v in kwargs.items(): |
| 359 | if isinstance(v, str): |
| 360 | if v == "": |
| 361 | kwargs[k] = None |
| 362 | elif format_yaml: |
| 363 | try: |
| 364 | kwargs[k] = yaml.load(v) |
| tierno | e128118 | 2018-05-22 12:24:36 +0200 | [diff] [blame] | 365 | except Exception: |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 366 | pass |
| 367 | elif k.endswith(".gt") or k.endswith(".lt") or k.endswith(".gte") or k.endswith(".lte"): |
| 368 | try: |
| 369 | kwargs[k] = int(v) |
| tierno | e128118 | 2018-05-22 12:24:36 +0200 | [diff] [blame] | 370 | except Exception: |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 371 | try: |
| 372 | kwargs[k] = float(v) |
| tierno | e128118 | 2018-05-22 12:24:36 +0200 | [diff] [blame] | 373 | except Exception: |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 374 | pass |
| 375 | elif v.find(",") > 0: |
| 376 | kwargs[k] = v.split(",") |
| 377 | elif isinstance(v, (list, tuple)): |
| 378 | for index in range(0, len(v)): |
| 379 | if v[index] == "": |
| 380 | v[index] = None |
| 381 | elif format_yaml: |
| 382 | try: |
| 383 | v[index] = yaml.load(v[index]) |
| tierno | e128118 | 2018-05-22 12:24:36 +0200 | [diff] [blame] | 384 | except Exception: |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 385 | pass |
| 386 | |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 387 | return indata |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 388 | except (ValueError, yaml.YAMLError) as exc: |
| 389 | raise NbiException(error_text + str(exc), HTTPStatus.BAD_REQUEST) |
| 390 | except KeyError as exc: |
| 391 | raise NbiException("Query string error: " + str(exc), HTTPStatus.BAD_REQUEST) |
| tierno | b92094f | 2018-05-11 13:44:22 +0200 | [diff] [blame] | 392 | except Exception as exc: |
| 393 | raise NbiException(error_text + str(exc), HTTPStatus.BAD_REQUEST) |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 394 | |
| 395 | @staticmethod |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 396 | def _format_out(data, session=None, _format=None): |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 397 | """ |
| 398 | return string of dictionary data according to requested json, yaml, xml. By default json |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 399 | :param data: response to be sent. Can be a dict, text or file |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 400 | :param session: |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 401 | :param _format: The format to be set as Content-Type ir data is a file |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 402 | :return: None |
| 403 | """ |
| tierno | 0f98af5 | 2018-03-19 10:28:22 +0100 | [diff] [blame] | 404 | accept = cherrypy.request.headers.get("Accept") |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 405 | if data is None: |
| tierno | 0f98af5 | 2018-03-19 10:28:22 +0100 | [diff] [blame] | 406 | if accept and "text/html" in accept: |
| 407 | return html.format(data, cherrypy.request, cherrypy.response, session) |
| tierno | 09c073e | 2018-04-26 13:36:48 +0200 | [diff] [blame] | 408 | # cherrypy.response.status = HTTPStatus.NO_CONTENT.value |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 409 | return |
| 410 | elif hasattr(data, "read"): # file object |
| 411 | if _format: |
| 412 | cherrypy.response.headers["Content-Type"] = _format |
| 413 | elif "b" in data.mode: # binariy asssumig zip |
| 414 | cherrypy.response.headers["Content-Type"] = 'application/zip' |
| 415 | else: |
| 416 | cherrypy.response.headers["Content-Type"] = 'text/plain' |
| 417 | # TODO check that cherrypy close file. If not implement pending things to close per thread next |
| 418 | return data |
| tierno | 0f98af5 | 2018-03-19 10:28:22 +0100 | [diff] [blame] | 419 | if accept: |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 420 | if "application/json" in accept: |
| 421 | cherrypy.response.headers["Content-Type"] = 'application/json; charset=utf-8' |
| 422 | a = json.dumps(data, indent=4) + "\n" |
| 423 | return a.encode("utf8") |
| 424 | elif "text/html" in accept: |
| 425 | return html.format(data, cherrypy.request, cherrypy.response, session) |
| 426 | |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 427 | elif "application/yaml" in accept or "*/*" in accept or "text/plain" in accept: |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 428 | pass |
| 429 | else: |
| 430 | raise cherrypy.HTTPError(HTTPStatus.NOT_ACCEPTABLE.value, |
| 431 | "Only 'Accept' of type 'application/json' or 'application/yaml' " |
| 432 | "for output format are available") |
| 433 | cherrypy.response.headers["Content-Type"] = 'application/yaml' |
| 434 | return yaml.safe_dump(data, explicit_start=True, indent=4, default_flow_style=False, tags=False, |
| 435 | encoding='utf-8', allow_unicode=True) # , canonical=True, default_style='"' |
| 436 | |
| 437 | @cherrypy.expose |
| 438 | def index(self, *args, **kwargs): |
| 439 | session = None |
| 440 | try: |
| 441 | if cherrypy.request.method == "GET": |
| Eduardo Sousa | 2f98821 | 2018-07-26 01:04:11 +0100 | [diff] [blame] | 442 | session = self.authenticator.authorize() |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 443 | outdata = "Index page" |
| 444 | else: |
| 445 | raise cherrypy.HTTPError(HTTPStatus.METHOD_NOT_ALLOWED.value, |
| tierno | 2236d20 | 2018-05-16 19:05:16 +0200 | [diff] [blame] | 446 | "Method {} not allowed for tokens".format(cherrypy.request.method)) |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 447 | |
| 448 | return self._format_out(outdata, session) |
| 449 | |
| Eduardo Sousa | 819d34c | 2018-07-31 01:20:02 +0100 | [diff] [blame] | 450 | except (EngineException, AuthException) as e: |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 451 | cherrypy.log("index Exception {}".format(e)) |
| 452 | cherrypy.response.status = e.http_code.value |
| 453 | return self._format_out("Welcome to OSM!", session) |
| 454 | |
| 455 | @cherrypy.expose |
| tierno | 55945e7 | 2018-04-06 16:40:27 +0200 | [diff] [blame] | 456 | def version(self, *args, **kwargs): |
| tierno | dfe0957 | 2018-04-24 10:41:10 +0200 | [diff] [blame] | 457 | # TODO consider to remove and provide version using the static version file |
| tierno | 55945e7 | 2018-04-06 16:40:27 +0200 | [diff] [blame] | 458 | global __version__, version_date |
| 459 | try: |
| 460 | if cherrypy.request.method != "GET": |
| 461 | raise NbiException("Only method GET is allowed", HTTPStatus.METHOD_NOT_ALLOWED) |
| 462 | elif args or kwargs: |
| 463 | raise NbiException("Invalid URL or query string for version", HTTPStatus.METHOD_NOT_ALLOWED) |
| 464 | return __version__ + " " + version_date |
| 465 | except NbiException as e: |
| 466 | cherrypy.response.status = e.http_code.value |
| 467 | problem_details = { |
| 468 | "code": e.http_code.name, |
| 469 | "status": e.http_code.value, |
| 470 | "detail": str(e), |
| 471 | } |
| 472 | return self._format_out(problem_details, None) |
| 473 | |
| 474 | @cherrypy.expose |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 475 | def token(self, method, token_id=None, kwargs=None): |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 476 | session = None |
| 477 | # self.engine.load_dbase(cherrypy.request.app.config) |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 478 | indata = self._format_in(kwargs) |
| 479 | if not isinstance(indata, dict): |
| 480 | raise NbiException("Expected application/yaml or application/json Content-Type", HTTPStatus.BAD_REQUEST) |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 481 | try: |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 482 | if method == "GET": |
| Eduardo Sousa | 2f98821 | 2018-07-26 01:04:11 +0100 | [diff] [blame] | 483 | session = self.authenticator.authorize() |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 484 | if token_id: |
| Eduardo Sousa | 2f98821 | 2018-07-26 01:04:11 +0100 | [diff] [blame] | 485 | outdata = self.authenticator.get_token(session, token_id) |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 486 | else: |
| Eduardo Sousa | 2f98821 | 2018-07-26 01:04:11 +0100 | [diff] [blame] | 487 | outdata = self.authenticator.get_token_list(session) |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 488 | elif method == "POST": |
| 489 | try: |
| Eduardo Sousa | 2f98821 | 2018-07-26 01:04:11 +0100 | [diff] [blame] | 490 | session = self.authenticator.authorize() |
| tierno | e128118 | 2018-05-22 12:24:36 +0200 | [diff] [blame] | 491 | except Exception: |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 492 | session = None |
| 493 | if kwargs: |
| 494 | indata.update(kwargs) |
| Eduardo Sousa | 2f98821 | 2018-07-26 01:04:11 +0100 | [diff] [blame] | 495 | outdata = self.authenticator.new_token(session, indata, cherrypy.request.remote) |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 496 | session = outdata |
| 497 | cherrypy.session['Authorization'] = outdata["_id"] |
| tierno | 0f98af5 | 2018-03-19 10:28:22 +0100 | [diff] [blame] | 498 | self._set_location_header("admin", "v1", "tokens", outdata["_id"]) |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 499 | # cherrypy.response.cookie["Authorization"] = outdata["id"] |
| 500 | # cherrypy.response.cookie["Authorization"]['expires'] = 3600 |
| 501 | elif method == "DELETE": |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 502 | if not token_id and "id" in kwargs: |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 503 | token_id = kwargs["id"] |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 504 | elif not token_id: |
| Eduardo Sousa | 2f98821 | 2018-07-26 01:04:11 +0100 | [diff] [blame] | 505 | session = self.authenticator.authorize() |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 506 | token_id = session["_id"] |
| Eduardo Sousa | 2f98821 | 2018-07-26 01:04:11 +0100 | [diff] [blame] | 507 | outdata = self.authenticator.del_token(token_id) |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 508 | session = None |
| 509 | cherrypy.session['Authorization'] = "logout" |
| 510 | # cherrypy.response.cookie["Authorization"] = token_id |
| 511 | # cherrypy.response.cookie["Authorization"]['expires'] = 0 |
| 512 | else: |
| 513 | raise NbiException("Method {} not allowed for token".format(method), HTTPStatus.METHOD_NOT_ALLOWED) |
| 514 | return self._format_out(outdata, session) |
| Eduardo Sousa | 819d34c | 2018-07-31 01:20:02 +0100 | [diff] [blame] | 515 | except (NbiException, EngineException, DbException, AuthException) as e: |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 516 | cherrypy.log("tokens Exception {}".format(e)) |
| 517 | cherrypy.response.status = e.http_code.value |
| 518 | problem_details = { |
| 519 | "code": e.http_code.name, |
| 520 | "status": e.http_code.value, |
| 521 | "detail": str(e), |
| 522 | } |
| 523 | return self._format_out(problem_details, session) |
| 524 | |
| 525 | @cherrypy.expose |
| 526 | def test(self, *args, **kwargs): |
| 527 | thread_info = None |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 528 | if args and args[0] == "help": |
| 529 | return "<html><pre>\ninit\nfile/<name> download file\ndb-clear/table\nprune\nlogin\nlogin2\n"\ |
| tierno | e128118 | 2018-05-22 12:24:36 +0200 | [diff] [blame] | 530 | "sleep/<time>\nmessage/topic\n</pre></html>" |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 531 | |
| 532 | elif args and args[0] == "init": |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 533 | try: |
| 534 | # self.engine.load_dbase(cherrypy.request.app.config) |
| 535 | self.engine.create_admin() |
| 536 | return "Done. User 'admin', password 'admin' created" |
| 537 | except Exception: |
| 538 | cherrypy.response.status = HTTPStatus.FORBIDDEN.value |
| 539 | return self._format_out("Database already initialized") |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 540 | elif args and args[0] == "file": |
| 541 | return cherrypy.lib.static.serve_file(cherrypy.tree.apps['/osm'].config["storage"]["path"] + "/" + args[1], |
| 542 | "text/plain", "attachment") |
| 543 | elif args and args[0] == "file2": |
| 544 | f_path = cherrypy.tree.apps['/osm'].config["storage"]["path"] + "/" + args[1] |
| 545 | f = open(f_path, "r") |
| 546 | cherrypy.response.headers["Content-type"] = "text/plain" |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 547 | return f |
| tierno | 55945e7 | 2018-04-06 16:40:27 +0200 | [diff] [blame] | 548 | |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 549 | elif len(args) == 2 and args[0] == "db-clear": |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 550 | return self.engine.db.del_list(args[1], kwargs) |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 551 | elif args and args[0] == "prune": |
| 552 | return self.engine.prune() |
| 553 | elif args and args[0] == "login": |
| 554 | if not cherrypy.request.headers.get("Authorization"): |
| 555 | cherrypy.response.headers["WWW-Authenticate"] = 'Basic realm="Access to OSM site", charset="UTF-8"' |
| 556 | cherrypy.response.status = HTTPStatus.UNAUTHORIZED.value |
| 557 | elif args and args[0] == "login2": |
| 558 | if not cherrypy.request.headers.get("Authorization"): |
| 559 | cherrypy.response.headers["WWW-Authenticate"] = 'Bearer realm="Access to OSM site"' |
| 560 | cherrypy.response.status = HTTPStatus.UNAUTHORIZED.value |
| 561 | elif args and args[0] == "sleep": |
| 562 | sleep_time = 5 |
| 563 | try: |
| 564 | sleep_time = int(args[1]) |
| 565 | except Exception: |
| 566 | cherrypy.response.status = HTTPStatus.FORBIDDEN.value |
| 567 | return self._format_out("Database already initialized") |
| 568 | thread_info = cherrypy.thread_data |
| 569 | print(thread_info) |
| 570 | time.sleep(sleep_time) |
| 571 | # thread_info |
| 572 | elif len(args) >= 2 and args[0] == "message": |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 573 | main_topic = args[1] |
| 574 | return_text = "<html><pre>{} ->\n".format(main_topic) |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 575 | try: |
| tierno | 55945e7 | 2018-04-06 16:40:27 +0200 | [diff] [blame] | 576 | if cherrypy.request.method == 'POST': |
| 577 | to_send = yaml.load(cherrypy.request.body) |
| 578 | for k, v in to_send.items(): |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 579 | self.engine.msg.write(main_topic, k, v) |
| tierno | 55945e7 | 2018-04-06 16:40:27 +0200 | [diff] [blame] | 580 | return_text += " {}: {}\n".format(k, v) |
| 581 | elif cherrypy.request.method == 'GET': |
| 582 | for k, v in kwargs.items(): |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 583 | self.engine.msg.write(main_topic, k, yaml.load(v)) |
| tierno | 55945e7 | 2018-04-06 16:40:27 +0200 | [diff] [blame] | 584 | return_text += " {}: {}\n".format(k, yaml.load(v)) |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 585 | except Exception as e: |
| tierno | 55945e7 | 2018-04-06 16:40:27 +0200 | [diff] [blame] | 586 | return_text += "Error: " + str(e) |
| 587 | return_text += "</pre></html>\n" |
| 588 | return return_text |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 589 | |
| 590 | return_text = ( |
| 591 | "<html><pre>\nheaders:\n args: {}\n".format(args) + |
| 592 | " kwargs: {}\n".format(kwargs) + |
| 593 | " headers: {}\n".format(cherrypy.request.headers) + |
| 594 | " path_info: {}\n".format(cherrypy.request.path_info) + |
| 595 | " query_string: {}\n".format(cherrypy.request.query_string) + |
| 596 | " session: {}\n".format(cherrypy.session) + |
| 597 | " cookie: {}\n".format(cherrypy.request.cookie) + |
| 598 | " method: {}\n".format(cherrypy.request.method) + |
| 599 | " session: {}\n".format(cherrypy.session.get('fieldname')) + |
| 600 | " body:\n") |
| 601 | return_text += " length: {}\n".format(cherrypy.request.body.length) |
| 602 | if cherrypy.request.body.length: |
| 603 | return_text += " content: {}\n".format( |
| 604 | str(cherrypy.request.body.read(int(cherrypy.request.headers.get('Content-Length', 0))))) |
| 605 | if thread_info: |
| 606 | return_text += "thread: {}\n".format(thread_info) |
| 607 | return_text += "</pre></html>" |
| 608 | return return_text |
| 609 | |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 610 | def _check_valid_url_method(self, method, *args): |
| 611 | if len(args) < 3: |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 612 | raise NbiException("URL must contain at least 'main_topic/version/topic'", HTTPStatus.METHOD_NOT_ALLOWED) |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 613 | |
| 614 | reference = self.valid_methods |
| 615 | for arg in args: |
| 616 | if arg is None: |
| 617 | break |
| 618 | if not isinstance(reference, dict): |
| 619 | raise NbiException("URL contains unexpected extra items '{}'".format(arg), |
| 620 | HTTPStatus.METHOD_NOT_ALLOWED) |
| 621 | |
| 622 | if arg in reference: |
| 623 | reference = reference[arg] |
| 624 | elif "<ID>" in reference: |
| 625 | reference = reference["<ID>"] |
| 626 | elif "*" in reference: |
| 627 | reference = reference["*"] |
| 628 | break |
| 629 | else: |
| 630 | raise NbiException("Unexpected URL item {}".format(arg), HTTPStatus.METHOD_NOT_ALLOWED) |
| 631 | if "TODO" in reference and method in reference["TODO"]: |
| 632 | raise NbiException("Method {} not supported yet for this URL".format(method), HTTPStatus.NOT_IMPLEMENTED) |
| tierno | 2236d20 | 2018-05-16 19:05:16 +0200 | [diff] [blame] | 633 | elif "METHODS" in reference and method not in reference["METHODS"]: |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 634 | raise NbiException("Method {} not supported for this URL".format(method), HTTPStatus.METHOD_NOT_ALLOWED) |
| 635 | return |
| 636 | |
| 637 | @staticmethod |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 638 | def _set_location_header(main_topic, version, topic, id): |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 639 | """ |
| 640 | Insert response header Location with the URL of created item base on URL params |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 641 | :param main_topic: |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 642 | :param version: |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 643 | :param topic: |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 644 | :param id: |
| 645 | :return: None |
| 646 | """ |
| 647 | # Use cherrypy.request.base for absoluted path and make use of request.header HOST just in case behind aNAT |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 648 | cherrypy.response.headers["Location"] = "/osm/{}/{}/{}/{}".format(main_topic, version, topic, id) |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 649 | return |
| 650 | |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 651 | @cherrypy.expose |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 652 | def default(self, main_topic=None, version=None, topic=None, _id=None, item=None, *args, **kwargs): |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 653 | session = None |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 654 | outdata = None |
| 655 | _format = None |
| tierno | 0f98af5 | 2018-03-19 10:28:22 +0100 | [diff] [blame] | 656 | method = "DONE" |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 657 | engine_topic = None |
| tierno | db9dc58 | 2018-06-20 17:27:29 +0200 | [diff] [blame] | 658 | rollback = [] |
| 659 | session = None |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 660 | try: |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 661 | if not main_topic or not version or not topic: |
| 662 | raise NbiException("URL must contain at least 'main_topic/version/topic'", |
| 663 | HTTPStatus.METHOD_NOT_ALLOWED) |
| Felipe Vicens | b57758d | 2018-10-16 16:00:20 +0200 | [diff] [blame] | 664 | if main_topic not in ("admin", "vnfpkgm", "nsd", "nslcm", "nst", "nsilcm"): |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 665 | raise NbiException("URL main_topic '{}' not supported".format(main_topic), |
| 666 | HTTPStatus.METHOD_NOT_ALLOWED) |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 667 | if version != 'v1': |
| 668 | raise NbiException("URL version '{}' not supported".format(version), HTTPStatus.METHOD_NOT_ALLOWED) |
| 669 | |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 670 | if kwargs and "METHOD" in kwargs and kwargs["METHOD"] in ("PUT", "POST", "DELETE", "GET", "PATCH"): |
| 671 | method = kwargs.pop("METHOD") |
| 672 | else: |
| 673 | method = cherrypy.request.method |
| tierno | b92094f | 2018-05-11 13:44:22 +0200 | [diff] [blame] | 674 | if kwargs and "FORCE" in kwargs: |
| 675 | force = kwargs.pop("FORCE") |
| 676 | else: |
| 677 | force = False |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 678 | self._check_valid_url_method(method, main_topic, version, topic, _id, item, *args) |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 679 | if main_topic == "admin" and topic == "tokens": |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 680 | return self.token(method, _id, kwargs) |
| 681 | |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 682 | # self.engine.load_dbase(cherrypy.request.app.config) |
| Eduardo Sousa | 2f98821 | 2018-07-26 01:04:11 +0100 | [diff] [blame] | 683 | session = self.authenticator.authorize() |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 684 | indata = self._format_in(kwargs) |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 685 | engine_topic = topic |
| 686 | if topic == "subscriptions": |
| 687 | engine_topic = main_topic + "_" + topic |
| 688 | if item: |
| 689 | engine_topic = item |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 690 | |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 691 | if main_topic == "nsd": |
| 692 | engine_topic = "nsds" |
| 693 | elif main_topic == "vnfpkgm": |
| 694 | engine_topic = "vnfds" |
| 695 | elif main_topic == "nslcm": |
| 696 | engine_topic = "nsrs" |
| 697 | if topic == "ns_lcm_op_occs": |
| 698 | engine_topic = "nslcmops" |
| 699 | if topic == "vnfrs" or topic == "vnf_instances": |
| 700 | engine_topic = "vnfrs" |
| garciadeblas | 9750c5a | 2018-10-15 16:20:35 +0200 | [diff] [blame] | 701 | elif main_topic == "nst": |
| 702 | engine_topic = "nsts" |
| 703 | elif main_topic == "nsilcm": |
| 704 | engine_topic = "nsis" |
| 705 | if topic == "nsi_lcm_op_occs": |
| Felipe Vicens | b57758d | 2018-10-16 16:00:20 +0200 | [diff] [blame] | 706 | engine_topic = "nsilcmops" |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 707 | elif main_topic == "pdu": |
| 708 | engine_topic = "pdus" |
| 709 | if engine_topic == "vims": # TODO this is for backward compatibility, it will remove in the future |
| 710 | engine_topic = "vim_accounts" |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 711 | |
| 712 | if method == "GET": |
| Felipe Vicens | 07f3172 | 2018-10-29 15:16:44 +0100 | [diff] [blame] | 713 | if item in ("nsd_content", "package_content", "artifacts", "vnfd", "nsd", "nst", "nst_content"): |
| garciadeblas | 9750c5a | 2018-10-15 16:20:35 +0200 | [diff] [blame] | 714 | if item in ("vnfd", "nsd", "nst"): |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 715 | path = "$DESCRIPTOR" |
| 716 | elif args: |
| 717 | path = args |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 718 | elif item == "artifacts": |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 719 | path = () |
| 720 | else: |
| 721 | path = None |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 722 | file, _format = self.engine.get_file(session, engine_topic, _id, path, |
| tierno | 2236d20 | 2018-05-16 19:05:16 +0200 | [diff] [blame] | 723 | cherrypy.request.headers.get("Accept")) |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 724 | outdata = file |
| 725 | elif not _id: |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 726 | outdata = self.engine.get_item_list(session, engine_topic, kwargs) |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 727 | else: |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 728 | outdata = self.engine.get_item(session, engine_topic, _id) |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 729 | elif method == "POST": |
| garciadeblas | 9750c5a | 2018-10-15 16:20:35 +0200 | [diff] [blame] | 730 | if topic in ("ns_descriptors_content", "vnf_packages_content", "netslice_templates_content"): |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 731 | _id = cherrypy.request.headers.get("Transaction-Id") |
| 732 | if not _id: |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 733 | _id = self.engine.new_item(rollback, session, engine_topic, {}, None, cherrypy.request.headers, |
| tierno | b92094f | 2018-05-11 13:44:22 +0200 | [diff] [blame] | 734 | force=force) |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 735 | completed = self.engine.upload_content(session, engine_topic, _id, indata, kwargs, |
| 736 | cherrypy.request.headers, force=force) |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 737 | if completed: |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 738 | self._set_location_header(main_topic, version, topic, _id) |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 739 | else: |
| 740 | cherrypy.response.headers["Transaction-Id"] = _id |
| 741 | outdata = {"id": _id} |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 742 | elif topic == "ns_instances_content": |
| 743 | # creates NSR |
| 744 | _id = self.engine.new_item(rollback, session, engine_topic, indata, kwargs, force=force) |
| 745 | # creates nslcmop |
| 746 | indata["lcmOperationType"] = "instantiate" |
| 747 | indata["nsInstanceId"] = _id |
| 748 | self.engine.new_item(rollback, session, "nslcmops", indata, None) |
| 749 | self._set_location_header(main_topic, version, topic, _id) |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 750 | outdata = {"id": _id} |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 751 | elif topic == "ns_instances" and item: |
| 752 | indata["lcmOperationType"] = item |
| 753 | indata["nsInstanceId"] = _id |
| 754 | _id = self.engine.new_item(rollback, session, "nslcmops", indata, kwargs) |
| 755 | self._set_location_header(main_topic, version, "ns_lcm_op_occs", _id) |
| tierno | 65acb4d | 2018-04-06 16:42:40 +0200 | [diff] [blame] | 756 | outdata = {"id": _id} |
| 757 | cherrypy.response.status = HTTPStatus.ACCEPTED.value |
| garciadeblas | 9750c5a | 2018-10-15 16:20:35 +0200 | [diff] [blame] | 758 | elif topic == "netslice_instances_content": |
| Felipe Vicens | 07f3172 | 2018-10-29 15:16:44 +0100 | [diff] [blame] | 759 | # creates NetSlice_Instance_record (NSIR) |
| garciadeblas | 9750c5a | 2018-10-15 16:20:35 +0200 | [diff] [blame] | 760 | _id = self.engine.new_item(rollback, session, engine_topic, indata, kwargs, force=force) |
| Felipe Vicens | 07f3172 | 2018-10-29 15:16:44 +0100 | [diff] [blame] | 761 | self._set_location_header(main_topic, version, topic, _id) |
| garciadeblas | 9750c5a | 2018-10-15 16:20:35 +0200 | [diff] [blame] | 762 | indata["lcmOperationType"] = "instantiate" |
| 763 | indata["nsiInstanceId"] = _id |
| Felipe Vicens | 07f3172 | 2018-10-29 15:16:44 +0100 | [diff] [blame] | 764 | self.engine.new_item(rollback, session, "nsilcmops", indata, kwargs) |
| garciadeblas | 9750c5a | 2018-10-15 16:20:35 +0200 | [diff] [blame] | 765 | outdata = {"id": _id} |
| Felipe Vicens | 07f3172 | 2018-10-29 15:16:44 +0100 | [diff] [blame] | 766 | |
| garciadeblas | 9750c5a | 2018-10-15 16:20:35 +0200 | [diff] [blame] | 767 | elif topic == "netslice_instances" and item: |
| 768 | indata["lcmOperationType"] = item |
| 769 | indata["nsiInstanceId"] = _id |
| 770 | _id = self.engine.new_item(rollback, session, "nsilcmops", indata, kwargs) |
| 771 | self._set_location_header(main_topic, version, "nsi_lcm_op_occs", _id) |
| 772 | outdata = {"id": _id} |
| 773 | cherrypy.response.status = HTTPStatus.ACCEPTED.value |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 774 | else: |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 775 | _id = self.engine.new_item(rollback, session, engine_topic, indata, kwargs, |
| 776 | cherrypy.request.headers, force=force) |
| 777 | self._set_location_header(main_topic, version, topic, _id) |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 778 | outdata = {"id": _id} |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 779 | # TODO form NsdInfo when topic in ("ns_descriptors", "vnf_packages") |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 780 | cherrypy.response.status = HTTPStatus.CREATED.value |
| tierno | 09c073e | 2018-04-26 13:36:48 +0200 | [diff] [blame] | 781 | |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 782 | elif method == "DELETE": |
| 783 | if not _id: |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 784 | outdata = self.engine.del_item_list(session, engine_topic, kwargs) |
| tierno | 09c073e | 2018-04-26 13:36:48 +0200 | [diff] [blame] | 785 | cherrypy.response.status = HTTPStatus.OK.value |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 786 | else: # len(args) > 1 |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 787 | if topic == "ns_instances_content" and not force: |
| 788 | nslcmop_desc = { |
| 789 | "lcmOperationType": "terminate", |
| 790 | "nsInstanceId": _id, |
| 791 | "autoremove": True |
| 792 | } |
| 793 | opp_id = self.engine.new_item(rollback, session, "nslcmops", nslcmop_desc, None) |
| tierno | 3ace63c | 2018-05-03 17:51:43 +0200 | [diff] [blame] | 794 | outdata = {"_id": opp_id} |
| tierno | 09c073e | 2018-04-26 13:36:48 +0200 | [diff] [blame] | 795 | cherrypy.response.status = HTTPStatus.ACCEPTED.value |
| garciadeblas | 9750c5a | 2018-10-15 16:20:35 +0200 | [diff] [blame] | 796 | elif topic == "netslice_instances_content" and not force: |
| 797 | nsilcmop_desc = { |
| 798 | "lcmOperationType": "terminate", |
| 799 | "nsiInstanceId": _id, |
| 800 | "autoremove": True |
| 801 | } |
| 802 | opp_id = self.engine.new_item(rollback, session, "nsilcmops", nsilcmop_desc, None) |
| 803 | outdata = {"_id": opp_id} |
| 804 | cherrypy.response.status = HTTPStatus.ACCEPTED.value |
| tierno | 65acb4d | 2018-04-06 16:42:40 +0200 | [diff] [blame] | 805 | else: |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 806 | self.engine.del_item(session, engine_topic, _id, force) |
| tierno | 09c073e | 2018-04-26 13:36:48 +0200 | [diff] [blame] | 807 | cherrypy.response.status = HTTPStatus.NO_CONTENT.value |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 808 | if engine_topic in ("vim_accounts", "sdns"): |
| tierno | 09c073e | 2018-04-26 13:36:48 +0200 | [diff] [blame] | 809 | cherrypy.response.status = HTTPStatus.ACCEPTED.value |
| 810 | |
| tierno | 7ae1011 | 2018-05-18 14:36:02 +0200 | [diff] [blame] | 811 | elif method in ("PUT", "PATCH"): |
| tierno | cd54a4a | 2018-09-12 16:40:35 +0200 | [diff] [blame] | 812 | outdata = None |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 813 | if not indata and not kwargs: |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 814 | raise NbiException("Nothing to update. Provide payload and/or query string", |
| 815 | HTTPStatus.BAD_REQUEST) |
| garciadeblas | 9750c5a | 2018-10-15 16:20:35 +0200 | [diff] [blame] | 816 | if item in ("nsd_content", "package_content", "nst_content") and method == "PUT": |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 817 | completed = self.engine.upload_content(session, engine_topic, _id, indata, kwargs, |
| 818 | cherrypy.request.headers, force=force) |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 819 | if not completed: |
| 820 | cherrypy.response.headers["Transaction-Id"] = id |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 821 | else: |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 822 | self.engine.edit_item(session, engine_topic, _id, indata, kwargs, force=force) |
| tierno | cd54a4a | 2018-09-12 16:40:35 +0200 | [diff] [blame] | 823 | cherrypy.response.status = HTTPStatus.NO_CONTENT.value |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 824 | else: |
| 825 | raise NbiException("Method {} not allowed".format(method), HTTPStatus.METHOD_NOT_ALLOWED) |
| tierno | f27c79b | 2018-03-12 17:08:42 +0100 | [diff] [blame] | 826 | return self._format_out(outdata, session, _format) |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 827 | except Exception as e: |
| 828 | if isinstance(e, (NbiException, EngineException, DbException, FsException, MsgException, AuthException)): |
| 829 | http_code_value = cherrypy.response.status = e.http_code.value |
| 830 | http_code_name = e.http_code.name |
| 831 | cherrypy.log("Exception {}".format(e)) |
| 832 | else: |
| 833 | http_code_value = cherrypy.response.status = HTTPStatus.BAD_REQUEST.value # INTERNAL_SERVER_ERROR |
| 834 | cherrypy.log("CRITICAL: Exception {}".format(e)) |
| 835 | http_code_name = HTTPStatus.BAD_REQUEST.name |
| tierno | 3ace63c | 2018-05-03 17:51:43 +0200 | [diff] [blame] | 836 | if hasattr(outdata, "close"): # is an open file |
| 837 | outdata.close() |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 838 | error_text = str(e) |
| 839 | rollback.reverse() |
| tierno | db9dc58 | 2018-06-20 17:27:29 +0200 | [diff] [blame] | 840 | for rollback_item in rollback: |
| tierno | 3ace63c | 2018-05-03 17:51:43 +0200 | [diff] [blame] | 841 | try: |
| tierno | cc10343 | 2018-10-19 14:10:35 +0200 | [diff] [blame] | 842 | if rollback_item.get("operation") == "set": |
| 843 | self.engine.db.set_one(rollback_item["topic"], {"_id": rollback_item["_id"]}, |
| 844 | rollback_item["content"], fail_on_empty=False) |
| 845 | else: |
| 846 | self.engine.del_item(**rollback_item, session=session, force=True) |
| tierno | 3ace63c | 2018-05-03 17:51:43 +0200 | [diff] [blame] | 847 | except Exception as e2: |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 848 | rollback_error_text = "Rollback Exception {}: {}".format(rollback_item, e2) |
| 849 | cherrypy.log(rollback_error_text) |
| 850 | error_text += ". " + rollback_error_text |
| 851 | # if isinstance(e, MsgException): |
| 852 | # error_text = "{} has been '{}' but other modules cannot be informed because an error on bus".format( |
| 853 | # engine_topic[:-1], method, error_text) |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 854 | problem_details = { |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 855 | "code": http_code_name, |
| 856 | "status": http_code_value, |
| 857 | "detail": error_text, |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 858 | } |
| 859 | return self._format_out(problem_details, session) |
| 860 | # raise cherrypy.HTTPError(e.http_code.value, str(e)) |
| 861 | |
| 862 | |
| 863 | # def validate_password(realm, username, password): |
| 864 | # cherrypy.log("realm "+ str(realm)) |
| 865 | # if username == "admin" and password == "admin": |
| 866 | # return True |
| 867 | # return False |
| 868 | |
| 869 | |
| 870 | def _start_service(): |
| 871 | """ |
| 872 | Callback function called when cherrypy.engine starts |
| 873 | Override configuration with env variables |
| 874 | Set database, storage, message configuration |
| 875 | Init database with admin/admin user password |
| 876 | """ |
| 877 | cherrypy.log.error("Starting osm_nbi") |
| 878 | # update general cherrypy configuration |
| 879 | update_dict = {} |
| 880 | |
| 881 | engine_config = cherrypy.tree.apps['/osm'].config |
| 882 | for k, v in environ.items(): |
| 883 | if not k.startswith("OSMNBI_"): |
| 884 | continue |
| tierno | e128118 | 2018-05-22 12:24:36 +0200 | [diff] [blame] | 885 | k1, _, k2 = k[7:].lower().partition("_") |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 886 | if not k2: |
| 887 | continue |
| 888 | try: |
| 889 | # update static configuration |
| 890 | if k == 'OSMNBI_STATIC_DIR': |
| 891 | engine_config["/static"]['tools.staticdir.dir'] = v |
| 892 | engine_config["/static"]['tools.staticdir.on'] = True |
| 893 | elif k == 'OSMNBI_SOCKET_PORT' or k == 'OSMNBI_SERVER_PORT': |
| 894 | update_dict['server.socket_port'] = int(v) |
| 895 | elif k == 'OSMNBI_SOCKET_HOST' or k == 'OSMNBI_SERVER_HOST': |
| 896 | update_dict['server.socket_host'] = v |
| tierno | f5298be | 2018-05-16 14:43:57 +0200 | [diff] [blame] | 897 | elif k1 in ("server", "test", "auth", "log"): |
| 898 | update_dict[k1 + '.' + k2] = v |
| Eduardo Sousa | 819d34c | 2018-07-31 01:20:02 +0100 | [diff] [blame] | 899 | elif k1 in ("message", "database", "storage", "authentication"): |
| tierno | f5298be | 2018-05-16 14:43:57 +0200 | [diff] [blame] | 900 | # k2 = k2.replace('_', '.') |
| Eduardo Sousa | 819d34c | 2018-07-31 01:20:02 +0100 | [diff] [blame] | 901 | if k2 in ("port", "db_port"): |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 902 | engine_config[k1][k2] = int(v) |
| 903 | else: |
| 904 | engine_config[k1][k2] = v |
| Eduardo Sousa | 819d34c | 2018-07-31 01:20:02 +0100 | [diff] [blame] | 905 | |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 906 | except ValueError as e: |
| 907 | cherrypy.log.error("Ignoring environ '{}': " + str(e)) |
| 908 | except Exception as e: |
| 909 | cherrypy.log.warn("skipping environ '{}' on exception '{}'".format(k, e)) |
| 910 | |
| 911 | if update_dict: |
| 912 | cherrypy.config.update(update_dict) |
| tierno | f5298be | 2018-05-16 14:43:57 +0200 | [diff] [blame] | 913 | engine_config["global"].update(update_dict) |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 914 | |
| 915 | # logging cherrypy |
| 916 | log_format_simple = "%(asctime)s %(levelname)s %(name)s %(filename)s:%(lineno)s %(message)s" |
| 917 | log_formatter_simple = logging.Formatter(log_format_simple, datefmt='%Y-%m-%dT%H:%M:%S') |
| 918 | logger_server = logging.getLogger("cherrypy.error") |
| 919 | logger_access = logging.getLogger("cherrypy.access") |
| 920 | logger_cherry = logging.getLogger("cherrypy") |
| 921 | logger_nbi = logging.getLogger("nbi") |
| 922 | |
| tierno | f5298be | 2018-05-16 14:43:57 +0200 | [diff] [blame] | 923 | if "log.file" in engine_config["global"]: |
| 924 | file_handler = logging.handlers.RotatingFileHandler(engine_config["global"]["log.file"], |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 925 | maxBytes=100e6, backupCount=9, delay=0) |
| 926 | file_handler.setFormatter(log_formatter_simple) |
| 927 | logger_cherry.addHandler(file_handler) |
| 928 | logger_nbi.addHandler(file_handler) |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 929 | # log always to standard output |
| 930 | for format_, logger in {"nbi.server %(filename)s:%(lineno)s": logger_server, |
| 931 | "nbi.access %(filename)s:%(lineno)s": logger_access, |
| 932 | "%(name)s %(filename)s:%(lineno)s": logger_nbi |
| 933 | }.items(): |
| 934 | log_format_cherry = "%(asctime)s %(levelname)s {} %(message)s".format(format_) |
| 935 | log_formatter_cherry = logging.Formatter(log_format_cherry, datefmt='%Y-%m-%dT%H:%M:%S') |
| 936 | str_handler = logging.StreamHandler() |
| 937 | str_handler.setFormatter(log_formatter_cherry) |
| 938 | logger.addHandler(str_handler) |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 939 | |
| tierno | f5298be | 2018-05-16 14:43:57 +0200 | [diff] [blame] | 940 | if engine_config["global"].get("log.level"): |
| 941 | logger_cherry.setLevel(engine_config["global"]["log.level"]) |
| 942 | logger_nbi.setLevel(engine_config["global"]["log.level"]) |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 943 | |
| 944 | # logging other modules |
| 945 | for k1, logname in {"message": "nbi.msg", "database": "nbi.db", "storage": "nbi.fs"}.items(): |
| 946 | engine_config[k1]["logger_name"] = logname |
| 947 | logger_module = logging.getLogger(logname) |
| 948 | if "logfile" in engine_config[k1]: |
| 949 | file_handler = logging.handlers.RotatingFileHandler(engine_config[k1]["logfile"], |
| tierno | 2236d20 | 2018-05-16 19:05:16 +0200 | [diff] [blame] | 950 | maxBytes=100e6, backupCount=9, delay=0) |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 951 | file_handler.setFormatter(log_formatter_simple) |
| 952 | logger_module.addHandler(file_handler) |
| 953 | if "loglevel" in engine_config[k1]: |
| 954 | logger_module.setLevel(engine_config[k1]["loglevel"]) |
| 955 | # TODO add more entries, e.g.: storage |
| 956 | cherrypy.tree.apps['/osm'].root.engine.start(engine_config) |
| Eduardo Sousa | 819d34c | 2018-07-31 01:20:02 +0100 | [diff] [blame] | 957 | cherrypy.tree.apps['/osm'].root.authenticator.start(engine_config) |
| tierno | d985a8d | 2018-10-19 14:12:28 +0200 | [diff] [blame] | 958 | cherrypy.tree.apps['/osm'].root.engine.init_db(target_version=database_version) |
| 959 | cherrypy.tree.apps['/osm'].root.authenticator.init_db(target_version=auth_database_version) |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 960 | # getenv('OSMOPENMANO_TENANT', None) |
| 961 | |
| 962 | |
| 963 | def _stop_service(): |
| 964 | """ |
| 965 | Callback function called when cherrypy.engine stops |
| 966 | TODO: Ending database connections. |
| 967 | """ |
| 968 | cherrypy.tree.apps['/osm'].root.engine.stop() |
| 969 | cherrypy.log.error("Stopping osm_nbi") |
| 970 | |
| tierno | 2236d20 | 2018-05-16 19:05:16 +0200 | [diff] [blame] | 971 | |
| tierno | f5298be | 2018-05-16 14:43:57 +0200 | [diff] [blame] | 972 | def nbi(config_file): |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 973 | # conf = { |
| 974 | # '/': { |
| 975 | # #'request.dispatch': cherrypy.dispatch.MethodDispatcher(), |
| 976 | # 'tools.sessions.on': True, |
| 977 | # 'tools.response_headers.on': True, |
| 978 | # # 'tools.response_headers.headers': [('Content-Type', 'text/plain')], |
| 979 | # } |
| 980 | # } |
| 981 | # cherrypy.Server.ssl_module = 'builtin' |
| 982 | # cherrypy.Server.ssl_certificate = "http/cert.pem" |
| 983 | # cherrypy.Server.ssl_private_key = "http/privkey.pem" |
| 984 | # cherrypy.Server.thread_pool = 10 |
| 985 | # cherrypy.config.update({'Server.socket_port': config["port"], 'Server.socket_host': config["host"]}) |
| 986 | |
| 987 | # cherrypy.config.update({'tools.auth_basic.on': True, |
| 988 | # 'tools.auth_basic.realm': 'localhost', |
| 989 | # 'tools.auth_basic.checkpassword': validate_password}) |
| 990 | cherrypy.engine.subscribe('start', _start_service) |
| 991 | cherrypy.engine.subscribe('stop', _stop_service) |
| tierno | f5298be | 2018-05-16 14:43:57 +0200 | [diff] [blame] | 992 | cherrypy.quickstart(Server(), '/osm', config_file) |
| 993 | |
| 994 | |
| 995 | def usage(): |
| 996 | print("""Usage: {} [options] |
| 997 | -c|--config [configuration_file]: loads the configuration file (default: ./nbi.cfg) |
| 998 | -h|--help: shows this help |
| 999 | """.format(sys.argv[0])) |
| tierno | 2236d20 | 2018-05-16 19:05:16 +0200 | [diff] [blame] | 1000 | # --log-socket-host HOST: send logs to this host") |
| 1001 | # --log-socket-port PORT: send logs using this port (default: 9022)") |
| tierno | c94c3df | 2018-02-09 15:38:54 +0100 | [diff] [blame] | 1002 | |
| 1003 | |
| 1004 | if __name__ == '__main__': |
| tierno | f5298be | 2018-05-16 14:43:57 +0200 | [diff] [blame] | 1005 | try: |
| 1006 | # load parameters and configuration |
| 1007 | opts, args = getopt.getopt(sys.argv[1:], "hvc:", ["config=", "help"]) |
| 1008 | # TODO add "log-socket-host=", "log-socket-port=", "log-file=" |
| 1009 | config_file = None |
| 1010 | for o, a in opts: |
| 1011 | if o in ("-h", "--help"): |
| 1012 | usage() |
| 1013 | sys.exit() |
| 1014 | elif o in ("-c", "--config"): |
| 1015 | config_file = a |
| 1016 | # elif o == "--log-socket-port": |
| 1017 | # log_socket_port = a |
| 1018 | # elif o == "--log-socket-host": |
| 1019 | # log_socket_host = a |
| 1020 | # elif o == "--log-file": |
| 1021 | # log_file = a |
| 1022 | else: |
| 1023 | assert False, "Unhandled option" |
| 1024 | if config_file: |
| 1025 | if not path.isfile(config_file): |
| 1026 | print("configuration file '{}' that not exist".format(config_file), file=sys.stderr) |
| 1027 | exit(1) |
| 1028 | else: |
| 1029 | for config_file in (__file__[:__file__.rfind(".")] + ".cfg", "./nbi.cfg", "/etc/osm/nbi.cfg"): |
| 1030 | if path.isfile(config_file): |
| 1031 | break |
| 1032 | else: |
| 1033 | print("No configuration file 'nbi.cfg' found neither at local folder nor at /etc/osm/", file=sys.stderr) |
| 1034 | exit(1) |
| 1035 | nbi(config_file) |
| 1036 | except getopt.GetoptError as e: |
| 1037 | print(str(e), file=sys.stderr) |
| 1038 | # usage() |
| 1039 | exit(1) |