From: Peter Szilagyi Date: Fri, 14 Jun 2019 09:45:14 +0000 (+0000) Subject: Add version v0.2.0 X-Git-Url: https://gerrit.o-ran-sc.org/r/gitweb?a=commitdiff_plain;h=refs%2Fchanges%2F41%2F341%2F1;p=ric-plt%2Frtmgr.git Add version v0.2.0 * Introduced http rest functionality * A way to get intial xapp data from xapp manager while booting the routing manager * A way to create a sinple webhook registration in the xapp-manager to listen on updates abpout changes in xapps * Changes in swagger API definition * UTs for SBI, SDL and RPE modules * New message types according to RMR Change-Id: If9d11062e14f2a9ef898e98906d6c2b7787958c9 Signed-off-by: Peter Szilagyi --- diff --git a/README.md b/README.md index 2cc2000..4ad7bef 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,11 @@ ## Introduction __Routing Manager__ is a basic platform service of RIC. It is responsible for distributing routing policies among the other platform components and xApps. -The implemented logic periodically queries the xApp Manager component for xApps' list. Stores the data then processes it to create routing policies and distributes them to all xApps. +The routing manager has two ways to get the xapp details from xapp manager - httpGetter or httpRESTful. +In case of httpGetter, the implemented logic periodically queries the xApp Manager component for xApps' list. +Where in httpRESTful, starts a http server and creates a webhook subscription in xapp manager to update about changes in xapps and waits changed data to arrive on the REST http server. +Either ways, the xapp data received is stored and then processed to create routing policies and distributes them to all xApps. + The architecture consists of the following five well defined functions: * NorthBound Interface (__NBI__): Maintains the communication channels towards RIC manager components * Routing Policy Engine (__RPE__): Provides the logic to calculate routing policies @@ -27,7 +31,7 @@ The architecture consists of the following five well defined functions: Current implementation provides support for the followings: * NBI: * __httpGet__: simple HTTP GET interface. Expects an URL where it gets the xApps' list in JSON format - * (WIP) __httRESTful__: provides REST API endpoints towards RIC manager components + * __httRESTful__: provides REST API endpoints towards RIC manager components. Expects REST port and url where the HTTP service will be started to listen on. * RPE: * __rmr__: creates routing policies formatted for RIC RMR * SDL: @@ -35,7 +39,7 @@ Current implementation provides support for the followings: * (backlog) __sdl__: Shared Data Library to Redis database * SBI: * __nngpub__: distributes RPE created policies via NNG Pub channel - * (WIP) __nngpipe__: distributes RPE created policies via NNG Pipeline channel + * __nngpipe__: distributes RPE created policies via NNG Pipeline channel ## Release notes Check the separated `RELNOTES` file. @@ -71,6 +75,8 @@ Issue the `kubectl create -f {manifest.yaml}` command in the following order 2. `manifests/rtmgr/rtmgr-dep.yaml`: instantiates the `rtmgr` deployment in the `example` namespace 3. `manifests/rtmgr/rtmgr-svc.yaml`: creates the `rtmgr` service in `example` namespace +**NOTE:** The above manifest files will deploy routing manager with NBI as httpRESTful which would not succeed unless there is an xapp manager running at the defined xm-url. The solution is either to deploy a real XAPP manager before deploying routing-manager or start the mock xmgr as mentioned in [Testing](#testing-and-troubleshoting). + ### Testing and Troubleshoting Routing Manager's behaviour can be tested using the mocked xApp Manager, traffic generator xApp and receiver xApp. @@ -80,6 +86,9 @@ Routing Manager's behaviour can be tested using the mocked xApp Manager, traffic 4. Enter the `./test/docker/xmgr.build` folder and issue `docker build .`. Tag the recently created docker image and push it to the common registry. 5. Modify the docker image version in each kuberbetes manifest files under `./test/kubernetes/` folder accordingly then issue the `kubectl create -f {manifest.yaml}` on each file. 6. [Compile](#compiling-code) and [Install routing manager](#installing-routing-manager) + 7. Once the routing manager is started, it retrievs the initial xapp list from `xmgr` via HTTPGet additonaly it starts to listen on http://rtmgr:8888/v1/handles/xapp-handle endpoint and ready to receive xapp list updates. + 8. Edit the provided `test/data/xapp.json` file accordingly and issue the following curl command to update `rtmgr's` xapp list. + ``` curl --header "Content-Type: application/json" --request POST --data '@./test/data/xapps.json' http://10.244.2.104:8888/v1/handles/xapp-handle ``` #### Command line arguments Routing manager binary can be called with `-h` flag when it displays the available command line arguments and it's default value. @@ -93,7 +102,9 @@ Usage of ./rtmgr: -loglevel string INFO | WARN | ERROR | DEBUG (default "INFO") -nbi string - Northbound interface module to be used. Valid values are: 'httpGetter' (default "httpGetter") + Northbound interface module to be used. Valid values are: 'httpGetter | httpRESTful' (default "httpGetter") + -nbi-if string + Base HTTP URL where routing manager will be listening on (default "http://localhost:8888") -rpe string Route Policy Engine to be used. Valid values are: 'rmrpush | rmrpub' (default "rmrpush") -sbi string @@ -109,10 +120,10 @@ Usage of ./rtmgr: For troubleshooting purpose the default logging level can be increased to `DEBUG`. ## Upcoming changes -[] Add RESTful NBI based on swagger api definition - [] Add unit tests +[] Generate http related swagger code automatically during the build process + ## License This project is licensed under the Apache License, Version 2.0 - see the [LICENSE](LICENSE) diff --git a/RELNOTES b/RELNOTES index 7d797df..543efe2 100644 --- a/RELNOTES +++ b/RELNOTES @@ -1,3 +1,13 @@ +### v0.2.0 +* Introduced http rest functionality +* A way to get intial xapp data from xapp manager while booting the routing manager +* A way to create a sinple webhook registration in the xapp-manager to listen on updates abpout changes in xapps + +### v0.1.1 +* Changes in swagger API definition +* UTs for SBI, SDL and RPE modules +* New message types according to RMR + ### v0.1.0 * Introduces NNGPush SBI module * Bugfixes in argument handling @@ -17,4 +27,4 @@ ### v0.0.1 * Initial version of Routing Manager for CI/CD pipeline * Dummy solution: still has no real routing capability -* Container is based on the _**tx**_ version of [admin xApp] which already implements [RMR library] \ No newline at end of file +* Container is based on the _**tx**_ version of [admin xApp] which already implements [RMR library] diff --git a/api/appmgr_rest_api.json b/api/appmgr_rest_api.json new file mode 100644 index 0000000..66250ae --- /dev/null +++ b/api/appmgr_rest_api.json @@ -0,0 +1,548 @@ +{ + "swagger": "2.0", + "info": { + "description": "This is a draft API for RIC appmgr", + "version": "0.0.11", + "title": "RIC appmgr", + "license": { + "name": "Apache 2.0", + "url": "http://www.apache.org/licenses/LICENSE-2.0.html" + } + }, + "host": "hostname", + "basePath": "/ric/v1", + "schemes": [ + "https", + "http" + ], + "paths": { + "/health": { + "get": { + "summary": "Health check of xApp Manager", + "operationId": "getHealth", + "responses": { + "200": { + "description": "Status of xApp Manager is ok" + } + } + } + }, + "/xapps": { + "post": { + "summary": "Deploy a xapp", + "operationId": "deployXapp", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "parameters": [ + { + "name": "xAppInfo", + "in": "body", + "description": "xApp information", + "schema": { + "type": "object", + "required": [ + "xAppName" + ], + "properties": { + "xAppName": { + "type":"string", + "description":"Name of the xApp", + "example": "xapp-dummy" + } + } + } + } + ], + "responses": { + "201": { + "description": "xApp successfully created", + "schema": { + "$ref": "#/definitions/Xapp" + } + }, + "400": { + "description": "Invalid input" + }, + "500": { + "description": "Internal error" + } + } + }, + "get": { + "summary": "Returns the status of all xapps", + "operationId": "getAllXapps", + "produces": [ + "application/json" + ], + "responses": { + "200": { + "description": "successful query of xApps", + "schema": { + "$ref": "#/definitions/AllXapps" + } + }, + "500": { + "description": "Internal error" + } + } + } + }, + "/xapps/{xAppName}": { + "get": { + "summary": "Returns the status of a given xapp", + "operationId": "getXappByName", + "produces": [ + "application/json" + ], + "parameters": [ + { + "name": "xAppName", + "in": "path", + "description": "Name of xApp", + "required": true, + "type": "string" + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "$ref": "#/definitions/Xapp" + } + }, + "400": { + "description": "Invalid ID supplied" + }, + "404": { + "description": "Xapp not found" + }, + "500": { + "description": "Internal error" + } + } + }, + "delete": { + "summary": "Undeploy an existing xapp", + "operationId": "undeployXapp", + "parameters": [ + { + "name": "xAppName", + "in": "path", + "description": "Xapp to be undeployed", + "required": true, + "type": "string" + } + ], + "responses": { + "204": { + "description": "Successful deletion of xApp" + }, + "400": { + "description": "Invalid xApp name supplied" + }, + "500": { + "description": "Internal error" + } + } + } + }, + "/xapps/{xAppName}/instances/{xAppInstanceName}": { + "get": { + "summary": "Returns the status of a given xapp", + "operationId": "getXappInstanceByName", + "produces": [ + "application/json" + ], + "parameters": [ + { + "name": "xAppName", + "in": "path", + "description": "Name of xApp", + "required": true, + "type": "string" + }, + { + "name": "xAppInstanceName", + "in": "path", + "description": "Name of xApp instance to get information", + "required": true, + "type": "string" + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "$ref": "#/definitions/XappInstance" + } + }, + "400": { + "description": "Invalid name supplied" + }, + "404": { + "description": "Xapp not found" + }, + "500": { + "description": "Internal error" + } + } + } + }, + "/subscriptions": { + "post": { + "summary": "Subscribe event", + "operationId": "addSubscription", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "parameters": [ + { + "name": "subscriptionRequest", + "in": "body", + "description": "New subscription", + "required": true, + "schema": { + "$ref": "#/definitions/subscriptionRequest" + } + } + ], + "responses": { + "200": { + "description": "Subscription successful", + "schema": { + "$ref": "#/definitions/subscriptionResponse" + } + }, + "400": { + "description": "Invalid input" + } + } + }, + "get": { + "summary": "Returns all subscriptions", + "operationId": "getSubscriptions", + "produces": [ + "application/json" + ], + "responses": { + "200": { + "description": "successful query of subscriptions", + "schema": { + "$ref": "#/definitions/allSubscriptions" + } + } + } + } + }, + "/subscriptions/{subscriptionId}": { + "get": { + "summary": "Returns the information of subscription", + "operationId": "getSubscriptionById", + "produces": [ + "application/json" + ], + "parameters": [ + { + "name": "subscriptionId", + "in": "path", + "description": "ID of subscription", + "required": true, + "type": "integer" + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "$ref": "#/definitions/subscription" + } + }, + "400": { + "description": "Invalid ID supplied" + }, + "404": { + "description": "Subscription not found" + } + } + }, + "put": { + "summary": "Modify event subscription", + "operationId": "modifySubscription", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "parameters": [ + { + "name": "subscriptionId", + "in": "path", + "description": "ID of subscription", + "required": true, + "type": "integer" + }, + { + "in": "body", + "name": "subscriptionRequest", + "description": "Modified subscription", + "required": true, + "schema": { + "$ref": "#/definitions/subscriptionRequest" + } + } + ], + "responses": { + "200": { + "description": "Subscription modification successful", + "schema": { + "$ref": "#/definitions/subscriptionResponse" + } + }, + "400": { + "description": "Invalid input" + } + } + }, + "delete": { + "summary": "Unsubscribe event", + "description": "", + "operationId": "deleteSubscription", + "parameters": [ + { + "name": "subscriptionId", + "in": "path", + "description": "ID of subscription", + "required": true, + "type": "integer" + } + ], + "responses": { + "204": { + "description": "Successful deletion of subscription" + }, + "400": { + "description": "Invalid subscription supplied" + } + } + } + } + }, + "definitions": { + "AllXapps": { + "type": "array", + "items": { + "$ref": "#/definitions/Xapp" + } + }, + "Xapp": { + "type": "object", + "required": [ + "name" + ], + "properties": { + "name": { + "type": "string", + "example": "xapp-dummy" + }, + "status": { + "type": "string", + "description": "xapp status in the RIC", + "enum": [ + "unknown", + "deployed", + "deleted", + "superseded", + "failed", + "deleting" + ] + }, + "version": { + "type": "string", + "example": "1.2.3" + }, + "instances": { + "type": "array", + "items": { + "$ref": "#/definitions/XappInstance" + } + } + } + }, + "XappInstance": { + "type": "object", + "required": [ + "name" + ], + "properties": { + "name": { + "type": "string", + "example": "xapp-dummy-6cd577d9-4v255" + }, + "status": { + "type": "string", + "description": "xapp instance status", + "enum": [ + "pending", + "running", + "succeeded", + "failed", + "unknown", + "completed", + "crashLoopBackOff" + ] + }, + "ip": { + "type": "string", + "example": "192.168.0.1" + }, + "port": { + "type": "integer", + "example": 32300 + }, + "txMessages" : { + "type": "array", + "items": { + "type" : "string", + "example" : "ControlIndication" + } + }, + "rxMessages" : { + "type": "array", + "items": { + "type" : "string", + "example" : "LoadIndication" + } + } + } + }, + "subscriptionRequest": { + "type": "object", + "required": [ + "targetUrl", + "eventType", + "maxRetries", + "retryTimer" + ], + "properties": { + "targetUrl": { + "type": "string", + "example": "http://localhost:11111/apps/webhook/" + }, + "eventType": { + "type": "string", + "description": "Event which is subscribed", + "enum": [ + "created", + "deleted", + "all" + ] + }, + "maxRetries": { + "type": "integer", + "description": "Maximum number of retries", + "example": 11 + }, + "retryTimer": { + "type": "integer", + "description": "Time in seconds to wait before next retry", + "example": 22 + } + } + }, + "subscriptionResponse": { + "type": "object", + "properties": { + "id": { + "type": "string", + "example": "1ILBltYYzEGzWRrVPZKmuUmhwcc" + }, + "version": { + "type": "integer", + "example": 2 + }, + "eventType": { + "type": "string", + "description": "Event which is subscribed", + "enum": [ + "created", + "deleted", + "updated", + "all" + ] + } + } + }, + "allSubscriptions": { + "type": "array", + "items": { + "$ref": "#/definitions/subscription" + } + }, + "subscription": { + "type": "object", + "properties": { + "id": { + "type": "string", + "example": "1ILBltYYzEGzWRrVPZKmuUmhwcc" + }, + "targetUrl": { + "type": "string", + "example": "http://localhost:11111/apps/webhook/" + }, + "eventType": { + "type": "string", + "description": "Event which is subscribed", + "enum": [ + "created", + "deleted", + "updated", + "all" + ] + }, + "maxRetries": { + "type": "integer", + "description": "Maximum number of retries", + "example": 11 + }, + "retryTimer": { + "type": "integer", + "description": "Time in seconds to wait before next retry", + "example": 22 + } + } + }, + "subscriptionNotification": { + "type": "object", + "properties": { + "id": { + "type": "string", + "example": "1ILBltYYzEGzWRrVPZKmuUmhwcc" + }, + "version": { + "type": "integer", + "example": 2 + }, + "eventType": { + "type": "string", + "description": "Event to be notified", + "enum": [ + "created", + "deleted", + "updated" + ] + }, + "xApps": { + "$ref": "#/definitions/AllXapps" + } + } + } + } +} \ No newline at end of file diff --git a/api/routing_manager.yaml b/api/routing_manager.yaml index 11f09a3..cd422df 100644 --- a/api/routing_manager.yaml +++ b/api/routing_manager.yaml @@ -24,7 +24,7 @@ swagger: "2.0" info: title: Routing Manager description: "This is the Swagger/OpenAPI 2.0 definition of Routing Manager's Northbound API." - version: "0.2.2" + version: "0.3.0" license: name: "Apache 2.0" url: "http://www.apache.org/licenses/LICENSE-2.0.html" @@ -36,8 +36,6 @@ tags: # externalDocs: # description: "Find out more" # url: "http://127.0.0.1" -- name: "route" - description: "Available routes" - name: "health" description: "Health of the system" schemes: @@ -103,13 +101,13 @@ paths: description: "Invalid data" 201: description: "Callback received" - /routes: + /handles/xapp-subscription-handle: post: tags: - - "route" - summary: "Add new route" - description: "By performing a POST method on the routes resource, the API caller is able to create a new route." - operationId: "add_route" + - "handle" + summary: "API for updating about new xapp subscription" + description: "By performing a POST method on the xapp-subscription-handle resource, the API caller is able to update the Routing manager about the creation of new subscription by an Xapp instance." + operationId: "provide_xapp_subscription_handle" consumes: - "application/json" # - "application/yaml" @@ -118,138 +116,16 @@ paths: # - "application/yaml" parameters: - in: "body" - name: "route" - description: "Route object that needs to be created" + name: "xapp-subscription-data" + description: "xApp related subscription data" required: true schema: - $ref: "#/definitions/route" + $ref: "#/definitions/xapp-subscription-data" responses: 400: - description: "Invalid route" + description: "Invalid data" 201: - description: "Route created" - put: - tags: - - "route" - summary: "Update an existing route" - description: "By performing a PUT method on the routes resource, the API caller is able to update an already existing route." - operationId: "update_route" - consumes: - - "application/json" -# - "application/yaml" - produces: - - "application/json" -# - "application/yaml" - parameters: - - in: "body" - name: "route" - description: "Route object that needs to be updated or created" - required: true - schema: - $ref: "#/definitions/route" - responses: - 400: - description: "Invalid route ID supplied" - 404: - description: "Route not found" - 204: - description: "Route updated" - get: - tags: - - "route" - summary: "Retrieve the list of routes" - description: "By performing a GET method on the routes resource, the API caller is able to retrieve all routes" - operationId: "get_routes" - consumes: - - "application/json" -# - "application/yaml" - produces: - - "application/json" -# - "application/yaml" - responses: - 200: - description: "All the routes" - schema: - $ref: "#/definitions/routes" - - /routes/{route-id}: - get: - tags: - - "route" - summary: "Find route by ID" - description: "Returns a single route" - operationId: "get_route_by_id" - produces: - - "application/json" - parameters: - - name: "route-id" - in: "path" - description: "ID of route to return" - required: true - type: "integer" - format: "int64" - responses: - 200: - description: "successful operation" - schema: - $ref: "#/definitions/route" - 400: - description: "Invalid route ID supplied" - 404: - description: "Route not found" - put: - tags: - - "route" - summary: "Updates a route by explicitly referencing it by route-id" - description: "By performing a PUT method on a specific route referenced by the route-id the API caller is able to update that specific route" - operationId: "update-route-by-id" - consumes: - - "application/json" -# - "application/yaml" - produces: - - "application/json" -# - "application/yaml" - parameters: - - name: "route-id" - in: "path" - description: "ID of route that needs to be updated" - required: true - type: "integer" - format: "int64" - - name: "route" - in: "body" - description: "The updated route instance" - required: false - schema: - $ref: "#/definitions/route" - responses: - 400: - description: "Invalid route ID supplied" - 204: - description: "Route updated" - delete: - tags: - - "route" - summary: "Deletes a route" - description: "By performing a DELETE method on a specific route referenced by the route-id, the API caller is able to delete that specific route" - operationId: "delete_route_by_id" - produces: - - "application/json" -# - "application/yaml" - parameters: - - name: "route-id" - in: "path" - description: "ID of the route that needs to be deleted" - required: true - type: "integer" - format: "int64" - responses: - 400: - description: "Invalid route ID supplied" - 404: - description: "Route not found" - 204: - description: "Route deleted" + description: "Xapp Subscription data received" definitions: health-status: type: "object" @@ -259,59 +135,37 @@ definitions: enum: - healthy - unhealthy - routes: - type: "array" - items: - $ref: "#/definitions/route" - route: + xapp-callback-data: type: "object" - required: - - "id" # not so sure about that properties: id: type: "integer" format: "int64" - senders: - type: "array" - items: - "$ref": "#/definitions/xapp-instance" - message-type: + event: + type: "string" + data-version: type: "integer" format: "int64" - receiver-groups: - type: "array" - items: - "$ref": "#/definitions/xapp-group" - xapp-instance: + data: + type: "string" #This should be a JSON object, array of xapps + xapp-subscription-data: type: "object" required: - - "address" - - "port" + - "address" + - "port" + - "subscription_id" properties: address: - type: "string" # I know... - port: + type: "string" #This is the xapp instance hostname or ip address + port: #xapp instance port address type: "integer" format: "int32" minimum: 0 maximum: 65535 - xapp-group: - type: "array" - items: - "$ref": "#/definitions/xapp-instance" - xapp-callback-data: - type: "object" - properties: - id: - type: "integer" - format: "int64" - event: - type: "string" - data-version: + subscription_id: #subscription sequence number type: "integer" - format: "int64" - data: - type: "string" #This should be a JSON object, array of xapps + format: "int16" + externalDocs: description: "Routing Manager" url: "http://placeholder" diff --git a/build.sh b/build.sh index e8482e9..e2ded44 100755 --- a/build.sh +++ b/build.sh @@ -24,13 +24,13 @@ # echo 'Creating compiler container' -docker build --no-cache --tag=rtmgr_compiler:0.1 build/binary/ +docker build --no-cache --tag=rtmgr_compiler build/binary/ echo 'Running rtmgr compiler' -docker run --rm --name=rtmgr_compiler -v ${PWD}:/opt/ rtmgr_compiler:0.1 +docker run --rm -v ${PWD}:/go/src/routing-manager -w /go/src/routing-manager rtmgr_compiler echo 'Cleaning up compiler container' -docker rmi -f rtmgr_compiler:0.1 +docker rmi -f rtmgr_compiler echo 'rtmgr binary successfully built!' diff --git a/build/binary/Dockerfile b/build/binary/Dockerfile index 7930f00..107aecc 100644 --- a/build/binary/Dockerfile +++ b/build/binary/Dockerfile @@ -22,11 +22,14 @@ # FROM golang:1.11 -ENV GOPATH /opt +ENV GOPATH=/go -RUN apt-get update \ - && apt-get install golang-glide +# Install golang-glide +RUN apt-get update && apt-get install golang-glide +# Install go-swagger +RUN go get -u github.com/go-swagger/go-swagger/cmd/swagger COPY compile.sh / -ENTRYPOINT /compile.sh +ENTRYPOINT ["/compile.sh"] + diff --git a/build/binary/compile.sh b/build/binary/compile.sh index 35d8640..f49b9a0 100755 --- a/build/binary/compile.sh +++ b/build/binary/compile.sh @@ -22,10 +22,17 @@ # Abstract: Compiles the rtmgr source # Date: 19 March 2019 # -mkdir -p $GOPATH/bin -ln -s -f $GOPATH/pkg $GOPATH/src -cd $GOPATH/src glide install --strip-vendor -cd $GOPATH/cmd -go build rtmgr.go -mv $GOPATH/cmd/rtmgr $GOPATH/bin +p="UT" +if [ "$p" = "$1" ] +then + echo "Starting Unit Tests..." + mkdir -p $PWD/unit-test + go test ./pkg/sbi ./pkg/rpe ./pkg/nbi ./pkg/sdl -cover -race -coverprofile=$PWD/unit-test/c.out + go tool cover -html=$PWD/unit-test/c.out -o $PWD/unit-test/coverage.html +else + echo "Compiling..." + go build -o ./bin/rtmgr cmd/rtmgr.go +fi + + diff --git a/build/container/run_rtmgr.sh b/build/container/run_rtmgr.sh index f098eb5..76e477c 100755 --- a/build/container/run_rtmgr.sh +++ b/build/container/run_rtmgr.sh @@ -22,4 +22,4 @@ # Abstract: Runs the rtmgr executable with proper arguments # Date: 19 March 2019 # -exec ./rtmgr -xm-url=$XMURL -sbi=$SBI -sbi-if=$IP -filename=$RTFILE -rpe=$RPE -loglevel=INFO +exec ./rtmgr -xm-url=$XMURL -nbi=$NBI -nbi-if=$NBIURL -sbi=$SBI -sbi-if=$IP -filename=$RTFILE -rpe=$RPE -loglevel=INFO diff --git a/cmd/rtmgr.go b/cmd/rtmgr.go index 093da71..6a6c9a0 100644 --- a/cmd/rtmgr.go +++ b/cmd/rtmgr.go @@ -28,12 +28,14 @@ package main import ( "flag" - "nbi" "os" - "rpe" - "rtmgr" - "sbi" - "sdl" + "os/signal" + "routing-manager/pkg/nbi" + "routing-manager/pkg/rpe" + "routing-manager/pkg/rtmgr" + "routing-manager/pkg/sbi" + "routing-manager/pkg/sdl" + "syscall" "time" ) @@ -45,25 +47,26 @@ var ( ) func parseArgs() { - // TODO: arguments should be validated (filename; xm-url; sbi-if) + // TODO: arguments should be validated (filename; xm-url; sbi-if; rest-url; rest-port) args = make(map[string]*string) - args["nbi"] = flag.String("nbi", "httpGetter", "Northbound interface module to be used. Valid values are: 'httpGetter'") + args["nbi"] = flag.String("nbi", "httpGetter", "Northbound interface module to be used. Valid values are: 'httpGetter | httpRESTful'") args["sbi"] = flag.String("sbi", "nngpush", "Southbound interface module to be used. Valid values are: 'nngpush | nngpub'") args["rpe"] = flag.String("rpe", "rmrpush", "Route Policy Engine to be used. Valid values are: 'rmrpush | rmrpub'") args["sdl"] = flag.String("sdl", "file", "Datastore enginge to be used. Valid values are: 'file'") args["xm-url"] = flag.String("xm-url", "http://localhost:3000/xapps", "HTTP URL where xApp Manager exposes the entire xApp List") + args["nbi-if"] = flag.String("nbi-if", "http://localhost:8888", "Base HTTP URL where routing manager will be listening on") args["sbi-if"] = flag.String("sbi-if", "0.0.0.0", "IPv4 address of interface where Southbound socket to be opened") args["filename"] = flag.String("filename", "/db/rt.json", "Absolute path of file where the route information to be stored") args["loglevel"] = flag.String("loglevel", "INFO", "INFO | WARN | ERROR | DEBUG") flag.Parse() } -func initRtmgr() (*nbi.NbiEngineConfig, *sbi.SbiEngineConfig, *sdl.SdlEngineConfig, *rpe.RpeEngineConfig, error) { +func initRtmgr() (nbi.NbiEngine, sbi.SbiEngine, sdl.SdlEngine, rpe.RpeEngine, error) { var err error - var nbii *nbi.NbiEngineConfig - var sbii *sbi.SbiEngineConfig - var sdli *sdl.SdlEngineConfig - var rpei *rpe.RpeEngineConfig + var nbii nbi.NbiEngine + var sbii sbi.SbiEngine + var sdli sdl.SdlEngine + var rpei rpe.RpeEngine if nbii, err = nbi.GetNbi(*args["nbi"]); err == nil && nbii != nil { if sbii, err = sbi.GetSbi(*args["sbi"]); err == nil && sbii != nil { if sdli, err = sdl.GetSdl(*args["sdl"]); err == nil && sdli != nil { @@ -76,45 +79,81 @@ func initRtmgr() (*nbi.NbiEngineConfig, *sbi.SbiEngineConfig, *sdl.SdlEngineConf return nil, nil, nil, nil, err } -func serve(nbii *nbi.NbiEngineConfig, sbii *sbi.SbiEngineConfig, sdli *sdl.SdlEngineConfig, rpei *rpe.RpeEngineConfig) { - err := sbii.OpenSocket(*args["sbi-if"]) +func serveSBI(triggerSBI <-chan bool, sbiEngine sbi.SbiEngine, sdlEngine sdl.SdlEngine, rpeEngine rpe.RpeEngine) { + for { + if <-triggerSBI { + data, err := sdlEngine.ReadAll(*args["filename"]) + if err != nil || data == nil { + rtmgr.Logger.Error("cannot get data from sdl interface due to: " + err.Error()) + continue + } + sbiEngine.UpdateEndpoints(data) + policies := rpeEngine.GeneratePolicies(rtmgr.Eps) + err = sbiEngine.DistributeAll(policies) + if err != nil { + rtmgr.Logger.Error("routing rable cannot be published due to: " + err.Error()) + } + } + } +} + +func serve(nbiEngine nbi.NbiEngine, sbiEngine sbi.SbiEngine, sdlEngine sdl.SdlEngine, rpeEngine rpe.RpeEngine) { + + triggerSBI := make(chan bool) + + nbiErr := nbiEngine.Initialize(*args["xm-url"], *args["nbi-if"], *args["filename"], sdlEngine, triggerSBI) + if nbiErr != nil { + rtmgr.Logger.Error("fail to initialize nbi due to: " + nbiErr.Error()) + return + } + + err := sbiEngine.Initialize(*args["sbi-if"]) if err != nil { rtmgr.Logger.Info("fail to open pub socket due to: " + err.Error()) return } - defer sbii.CloseSocket() + defer nbiEngine.Terminate() + defer sbiEngine.Terminate() + + // This SBI Go routine is trtiggered by periodic main loop and when data is recieved on REST interface. + go serveSBI(triggerSBI, sbiEngine, sdlEngine, rpeEngine) + for { time.Sleep(INTERVAL * time.Second) - data, err := nbii.BatchFetch(*args["xm-url"]) - if err != nil { - rtmgr.Logger.Error("cannot get data from " + nbii.Engine.Name + " interface dute to: " + err.Error()) - } else { - sdli.WriteAll(*args["filename"], data) - } - data, err = sdli.ReadAll(*args["filename"]) - if err != nil || data == nil { - rtmgr.Logger.Error("cannot get data from " + sdli.Engine.Name + " interface dute to: " + err.Error()) - continue - } - sbi.UpdateEndpointList(data, sbii) - policies := rpei.GeneratePolicies(rtmgr.Eps) - err = sbii.DistributeAll(policies) - if err != nil { - rtmgr.Logger.Error("routing rable cannot be published due to: " + err.Error()) + if *args["nbi"] == "httpGetter" { + data, err := nbiEngine.(*nbi.HttpGetter).FetchAllXapps(*args["xm-url"]) + if err != nil { + rtmgr.Logger.Error("cannot fetch xapp data dute to: " + err.Error()) + } else if data != nil { + sdlEngine.WriteAll(*args["filename"], data) + } } + + triggerSBI <- true } } +func SetupCloseHandler() { + c := make(chan os.Signal, 2) + signal.Notify(c, os.Interrupt, syscall.SIGTERM) + go func() { + <-c + rtmgr.Logger.Info("\r- Ctrl+C pressed in Terminal") + os.Exit(0) + }() +} + func main() { parseArgs() rtmgr.SetLogLevel(*args["loglevel"]) - nbii, sbii, sdli, rpei, err := initRtmgr() + nbiEngine, sbiEngine, sdlEngine, rpeEngine, err := initRtmgr() if err != nil { rtmgr.Logger.Error(err.Error()) os.Exit(1) } + SetupCloseHandler() rtmgr.Logger.Info("Start " + SERVICENAME + " service") rtmgr.Eps = make(rtmgr.Endpoints) - serve(nbii, sbii, sdli, rpei) + serve(nbiEngine, sbiEngine, sdlEngine, rpeEngine) os.Exit(0) } diff --git a/pkg/glide.yaml b/glide.yaml similarity index 73% rename from pkg/glide.yaml rename to glide.yaml index c7dd74c..07af8a2 100644 --- a/pkg/glide.yaml +++ b/glide.yaml @@ -59,8 +59,37 @@ import: - transport/tlstcp - transport/ws - transport/wss +- package: github.com/go-openapi/errors + version: v0.19.0 +- package: github.com/go-openapi/loads + version: v0.19.0 +- package: github.com/go-openapi/runtime + version: v0.19.0 + subpackages: + - flagext + - middleware + - security +- package: github.com/go-openapi/spec + version: v0.19.0 +- package: github.com/go-openapi/strfmt + version: v0.19.0 +- package: github.com/go-openapi/swag + version: v0.19.0 +- package: github.com/go-openapi/validate + version: v0.19.0 +- package: github.com/jessevdk/go-flags + version: v1.4.0 +- package: github.com/jcelliott/lumber ignore: +- models - rtmgr +- restapi +- nbi +- sbi +- rpe +- sdl +- appmgr_model +- appmgr_client testImport: - package: github.com/smartystreets/goconvey subpackages: diff --git a/manifests/rtmgr/rtmgr-dep.yaml b/manifests/rtmgr/rtmgr-dep.yaml index 0a9982b..30d5552 100644 --- a/manifests/rtmgr/rtmgr-dep.yaml +++ b/manifests/rtmgr/rtmgr-dep.yaml @@ -37,7 +37,7 @@ spec: spec: containers: - name: rtmgr - image: cmaster:5000/rtmgr:0.1.0 + image: cmaster:5000/rtmgr:0.2.0 command: ["/run_rtmgr.sh"] env: - name: XMURL @@ -48,7 +48,16 @@ spec: value: "/db/rt.json" - name: RPE value: "rmrpush" + - name: RESTURL + value: "0.0.0.0" + - name: RESTPORT + value: "8888" - name: SBI value: "nngpush" + - name: NBI + value: "httpRESTful" + - name: NBIURL + value: "http://0.0.0.0:8888" ports: + - containerPort: 8888 - containerPort: 4560 diff --git a/pkg/appmgr_client/operations/add_subscription_parameters.go b/pkg/appmgr_client/operations/add_subscription_parameters.go new file mode 100644 index 0000000..37cad5b --- /dev/null +++ b/pkg/appmgr_client/operations/add_subscription_parameters.go @@ -0,0 +1,139 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + + strfmt "github.com/go-openapi/strfmt" + + appmgr_model "routing-manager/pkg/appmgr_model" +) + +// NewAddSubscriptionParams creates a new AddSubscriptionParams object +// with the default values initialized. +func NewAddSubscriptionParams() *AddSubscriptionParams { + var () + return &AddSubscriptionParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewAddSubscriptionParamsWithTimeout creates a new AddSubscriptionParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewAddSubscriptionParamsWithTimeout(timeout time.Duration) *AddSubscriptionParams { + var () + return &AddSubscriptionParams{ + + timeout: timeout, + } +} + +// NewAddSubscriptionParamsWithContext creates a new AddSubscriptionParams object +// with the default values initialized, and the ability to set a context for a request +func NewAddSubscriptionParamsWithContext(ctx context.Context) *AddSubscriptionParams { + var () + return &AddSubscriptionParams{ + + Context: ctx, + } +} + +// NewAddSubscriptionParamsWithHTTPClient creates a new AddSubscriptionParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewAddSubscriptionParamsWithHTTPClient(client *http.Client) *AddSubscriptionParams { + var () + return &AddSubscriptionParams{ + HTTPClient: client, + } +} + +/*AddSubscriptionParams contains all the parameters to send to the API endpoint +for the add subscription operation typically these are written to a http.Request +*/ +type AddSubscriptionParams struct { + + /*SubscriptionRequest + New subscription + + */ + SubscriptionRequest *appmgr_model.SubscriptionRequest + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the add subscription params +func (o *AddSubscriptionParams) WithTimeout(timeout time.Duration) *AddSubscriptionParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the add subscription params +func (o *AddSubscriptionParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the add subscription params +func (o *AddSubscriptionParams) WithContext(ctx context.Context) *AddSubscriptionParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the add subscription params +func (o *AddSubscriptionParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the add subscription params +func (o *AddSubscriptionParams) WithHTTPClient(client *http.Client) *AddSubscriptionParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the add subscription params +func (o *AddSubscriptionParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithSubscriptionRequest adds the subscriptionRequest to the add subscription params +func (o *AddSubscriptionParams) WithSubscriptionRequest(subscriptionRequest *appmgr_model.SubscriptionRequest) *AddSubscriptionParams { + o.SetSubscriptionRequest(subscriptionRequest) + return o +} + +// SetSubscriptionRequest adds the subscriptionRequest to the add subscription params +func (o *AddSubscriptionParams) SetSubscriptionRequest(subscriptionRequest *appmgr_model.SubscriptionRequest) { + o.SubscriptionRequest = subscriptionRequest +} + +// WriteToRequest writes these params to a swagger request +func (o *AddSubscriptionParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.SubscriptionRequest != nil { + if err := r.SetBodyParam(o.SubscriptionRequest); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/appmgr_client/operations/add_subscription_responses.go b/pkg/appmgr_client/operations/add_subscription_responses.go new file mode 100644 index 0000000..8dde3f5 --- /dev/null +++ b/pkg/appmgr_client/operations/add_subscription_responses.go @@ -0,0 +1,95 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + + strfmt "github.com/go-openapi/strfmt" + + appmgr_model "routing-manager/pkg/appmgr_model" +) + +// AddSubscriptionReader is a Reader for the AddSubscription structure. +type AddSubscriptionReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *AddSubscriptionReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + + case 200: + result := NewAddSubscriptionOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + + case 400: + result := NewAddSubscriptionBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("unknown error", response, response.Code()) + } +} + +// NewAddSubscriptionOK creates a AddSubscriptionOK with default headers values +func NewAddSubscriptionOK() *AddSubscriptionOK { + return &AddSubscriptionOK{} +} + +/*AddSubscriptionOK handles this case with default header values. + +Subscription successful +*/ +type AddSubscriptionOK struct { + Payload *appmgr_model.SubscriptionResponse +} + +func (o *AddSubscriptionOK) Error() string { + return fmt.Sprintf("[POST /subscriptions][%d] addSubscriptionOK %+v", 200, o.Payload) +} + +func (o *AddSubscriptionOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(appmgr_model.SubscriptionResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewAddSubscriptionBadRequest creates a AddSubscriptionBadRequest with default headers values +func NewAddSubscriptionBadRequest() *AddSubscriptionBadRequest { + return &AddSubscriptionBadRequest{} +} + +/*AddSubscriptionBadRequest handles this case with default header values. + +Invalid input +*/ +type AddSubscriptionBadRequest struct { +} + +func (o *AddSubscriptionBadRequest) Error() string { + return fmt.Sprintf("[POST /subscriptions][%d] addSubscriptionBadRequest ", 400) +} + +func (o *AddSubscriptionBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} diff --git a/pkg/appmgr_client/operations/delete_subscription_parameters.go b/pkg/appmgr_client/operations/delete_subscription_parameters.go new file mode 100644 index 0000000..7641bf6 --- /dev/null +++ b/pkg/appmgr_client/operations/delete_subscription_parameters.go @@ -0,0 +1,137 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/swag" + + strfmt "github.com/go-openapi/strfmt" +) + +// NewDeleteSubscriptionParams creates a new DeleteSubscriptionParams object +// with the default values initialized. +func NewDeleteSubscriptionParams() *DeleteSubscriptionParams { + var () + return &DeleteSubscriptionParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteSubscriptionParamsWithTimeout creates a new DeleteSubscriptionParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewDeleteSubscriptionParamsWithTimeout(timeout time.Duration) *DeleteSubscriptionParams { + var () + return &DeleteSubscriptionParams{ + + timeout: timeout, + } +} + +// NewDeleteSubscriptionParamsWithContext creates a new DeleteSubscriptionParams object +// with the default values initialized, and the ability to set a context for a request +func NewDeleteSubscriptionParamsWithContext(ctx context.Context) *DeleteSubscriptionParams { + var () + return &DeleteSubscriptionParams{ + + Context: ctx, + } +} + +// NewDeleteSubscriptionParamsWithHTTPClient creates a new DeleteSubscriptionParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewDeleteSubscriptionParamsWithHTTPClient(client *http.Client) *DeleteSubscriptionParams { + var () + return &DeleteSubscriptionParams{ + HTTPClient: client, + } +} + +/*DeleteSubscriptionParams contains all the parameters to send to the API endpoint +for the delete subscription operation typically these are written to a http.Request +*/ +type DeleteSubscriptionParams struct { + + /*SubscriptionID + ID of subscription + + */ + SubscriptionID int64 + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the delete subscription params +func (o *DeleteSubscriptionParams) WithTimeout(timeout time.Duration) *DeleteSubscriptionParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete subscription params +func (o *DeleteSubscriptionParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete subscription params +func (o *DeleteSubscriptionParams) WithContext(ctx context.Context) *DeleteSubscriptionParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete subscription params +func (o *DeleteSubscriptionParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete subscription params +func (o *DeleteSubscriptionParams) WithHTTPClient(client *http.Client) *DeleteSubscriptionParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete subscription params +func (o *DeleteSubscriptionParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithSubscriptionID adds the subscriptionID to the delete subscription params +func (o *DeleteSubscriptionParams) WithSubscriptionID(subscriptionID int64) *DeleteSubscriptionParams { + o.SetSubscriptionID(subscriptionID) + return o +} + +// SetSubscriptionID adds the subscriptionId to the delete subscription params +func (o *DeleteSubscriptionParams) SetSubscriptionID(subscriptionID int64) { + o.SubscriptionID = subscriptionID +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteSubscriptionParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param subscriptionId + if err := r.SetPathParam("subscriptionId", swag.FormatInt64(o.SubscriptionID)); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/appmgr_client/operations/delete_subscription_responses.go b/pkg/appmgr_client/operations/delete_subscription_responses.go new file mode 100644 index 0000000..6d9df3f --- /dev/null +++ b/pkg/appmgr_client/operations/delete_subscription_responses.go @@ -0,0 +1,84 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + + "github.com/go-openapi/runtime" + + strfmt "github.com/go-openapi/strfmt" +) + +// DeleteSubscriptionReader is a Reader for the DeleteSubscription structure. +type DeleteSubscriptionReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteSubscriptionReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + + case 204: + result := NewDeleteSubscriptionNoContent() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + + case 400: + result := NewDeleteSubscriptionBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("unknown error", response, response.Code()) + } +} + +// NewDeleteSubscriptionNoContent creates a DeleteSubscriptionNoContent with default headers values +func NewDeleteSubscriptionNoContent() *DeleteSubscriptionNoContent { + return &DeleteSubscriptionNoContent{} +} + +/*DeleteSubscriptionNoContent handles this case with default header values. + +Successful deletion of subscription +*/ +type DeleteSubscriptionNoContent struct { +} + +func (o *DeleteSubscriptionNoContent) Error() string { + return fmt.Sprintf("[DELETE /subscriptions/{subscriptionId}][%d] deleteSubscriptionNoContent ", 204) +} + +func (o *DeleteSubscriptionNoContent) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +// NewDeleteSubscriptionBadRequest creates a DeleteSubscriptionBadRequest with default headers values +func NewDeleteSubscriptionBadRequest() *DeleteSubscriptionBadRequest { + return &DeleteSubscriptionBadRequest{} +} + +/*DeleteSubscriptionBadRequest handles this case with default header values. + +Invalid subscription supplied +*/ +type DeleteSubscriptionBadRequest struct { +} + +func (o *DeleteSubscriptionBadRequest) Error() string { + return fmt.Sprintf("[DELETE /subscriptions/{subscriptionId}][%d] deleteSubscriptionBadRequest ", 400) +} + +func (o *DeleteSubscriptionBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} diff --git a/pkg/appmgr_client/operations/deploy_xapp_parameters.go b/pkg/appmgr_client/operations/deploy_xapp_parameters.go new file mode 100644 index 0000000..00c4430 --- /dev/null +++ b/pkg/appmgr_client/operations/deploy_xapp_parameters.go @@ -0,0 +1,135 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + + strfmt "github.com/go-openapi/strfmt" +) + +// NewDeployXappParams creates a new DeployXappParams object +// with the default values initialized. +func NewDeployXappParams() *DeployXappParams { + var () + return &DeployXappParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewDeployXappParamsWithTimeout creates a new DeployXappParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewDeployXappParamsWithTimeout(timeout time.Duration) *DeployXappParams { + var () + return &DeployXappParams{ + + timeout: timeout, + } +} + +// NewDeployXappParamsWithContext creates a new DeployXappParams object +// with the default values initialized, and the ability to set a context for a request +func NewDeployXappParamsWithContext(ctx context.Context) *DeployXappParams { + var () + return &DeployXappParams{ + + Context: ctx, + } +} + +// NewDeployXappParamsWithHTTPClient creates a new DeployXappParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewDeployXappParamsWithHTTPClient(client *http.Client) *DeployXappParams { + var () + return &DeployXappParams{ + HTTPClient: client, + } +} + +/*DeployXappParams contains all the parameters to send to the API endpoint +for the deploy xapp operation typically these are written to a http.Request +*/ +type DeployXappParams struct { + + /*XAppInfo + xApp information + + */ + XAppInfo DeployXappBody + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the deploy xapp params +func (o *DeployXappParams) WithTimeout(timeout time.Duration) *DeployXappParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the deploy xapp params +func (o *DeployXappParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the deploy xapp params +func (o *DeployXappParams) WithContext(ctx context.Context) *DeployXappParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the deploy xapp params +func (o *DeployXappParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the deploy xapp params +func (o *DeployXappParams) WithHTTPClient(client *http.Client) *DeployXappParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the deploy xapp params +func (o *DeployXappParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithXAppInfo adds the xAppInfo to the deploy xapp params +func (o *DeployXappParams) WithXAppInfo(xAppInfo DeployXappBody) *DeployXappParams { + o.SetXAppInfo(xAppInfo) + return o +} + +// SetXAppInfo adds the xAppInfo to the deploy xapp params +func (o *DeployXappParams) SetXAppInfo(xAppInfo DeployXappBody) { + o.XAppInfo = xAppInfo +} + +// WriteToRequest writes these params to a swagger request +func (o *DeployXappParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if err := r.SetBodyParam(o.XAppInfo); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/appmgr_client/operations/deploy_xapp_responses.go b/pkg/appmgr_client/operations/deploy_xapp_responses.go new file mode 100644 index 0000000..608da8a --- /dev/null +++ b/pkg/appmgr_client/operations/deploy_xapp_responses.go @@ -0,0 +1,177 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + strfmt "github.com/go-openapi/strfmt" + + appmgr_model "routing-manager/pkg/appmgr_model" +) + +// DeployXappReader is a Reader for the DeployXapp structure. +type DeployXappReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeployXappReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + + case 201: + result := NewDeployXappCreated() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + + case 400: + result := NewDeployXappBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + case 500: + result := NewDeployXappInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("unknown error", response, response.Code()) + } +} + +// NewDeployXappCreated creates a DeployXappCreated with default headers values +func NewDeployXappCreated() *DeployXappCreated { + return &DeployXappCreated{} +} + +/*DeployXappCreated handles this case with default header values. + +xApp successfully created +*/ +type DeployXappCreated struct { + Payload *appmgr_model.Xapp +} + +func (o *DeployXappCreated) Error() string { + return fmt.Sprintf("[POST /xapps][%d] deployXappCreated %+v", 201, o.Payload) +} + +func (o *DeployXappCreated) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(appmgr_model.Xapp) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeployXappBadRequest creates a DeployXappBadRequest with default headers values +func NewDeployXappBadRequest() *DeployXappBadRequest { + return &DeployXappBadRequest{} +} + +/*DeployXappBadRequest handles this case with default header values. + +Invalid input +*/ +type DeployXappBadRequest struct { +} + +func (o *DeployXappBadRequest) Error() string { + return fmt.Sprintf("[POST /xapps][%d] deployXappBadRequest ", 400) +} + +func (o *DeployXappBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +// NewDeployXappInternalServerError creates a DeployXappInternalServerError with default headers values +func NewDeployXappInternalServerError() *DeployXappInternalServerError { + return &DeployXappInternalServerError{} +} + +/*DeployXappInternalServerError handles this case with default header values. + +Internal error +*/ +type DeployXappInternalServerError struct { +} + +func (o *DeployXappInternalServerError) Error() string { + return fmt.Sprintf("[POST /xapps][%d] deployXappInternalServerError ", 500) +} + +func (o *DeployXappInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +/*DeployXappBody deploy xapp body +swagger:model DeployXappBody +*/ +type DeployXappBody struct { + + // Name of the xApp + // Required: true + XAppName *string `json:"xAppName"` +} + +// Validate validates this deploy xapp body +func (o *DeployXappBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateXAppName(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeployXappBody) validateXAppName(formats strfmt.Registry) error { + + if err := validate.Required("xAppInfo"+"."+"xAppName", "body", o.XAppName); err != nil { + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeployXappBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeployXappBody) UnmarshalBinary(b []byte) error { + var res DeployXappBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/pkg/appmgr_client/operations/get_all_xapps_parameters.go b/pkg/appmgr_client/operations/get_all_xapps_parameters.go new file mode 100644 index 0000000..ca53613 --- /dev/null +++ b/pkg/appmgr_client/operations/get_all_xapps_parameters.go @@ -0,0 +1,113 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + + strfmt "github.com/go-openapi/strfmt" +) + +// NewGetAllXappsParams creates a new GetAllXappsParams object +// with the default values initialized. +func NewGetAllXappsParams() *GetAllXappsParams { + + return &GetAllXappsParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewGetAllXappsParamsWithTimeout creates a new GetAllXappsParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewGetAllXappsParamsWithTimeout(timeout time.Duration) *GetAllXappsParams { + + return &GetAllXappsParams{ + + timeout: timeout, + } +} + +// NewGetAllXappsParamsWithContext creates a new GetAllXappsParams object +// with the default values initialized, and the ability to set a context for a request +func NewGetAllXappsParamsWithContext(ctx context.Context) *GetAllXappsParams { + + return &GetAllXappsParams{ + + Context: ctx, + } +} + +// NewGetAllXappsParamsWithHTTPClient creates a new GetAllXappsParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewGetAllXappsParamsWithHTTPClient(client *http.Client) *GetAllXappsParams { + + return &GetAllXappsParams{ + HTTPClient: client, + } +} + +/*GetAllXappsParams contains all the parameters to send to the API endpoint +for the get all xapps operation typically these are written to a http.Request +*/ +type GetAllXappsParams struct { + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the get all xapps params +func (o *GetAllXappsParams) WithTimeout(timeout time.Duration) *GetAllXappsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get all xapps params +func (o *GetAllXappsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get all xapps params +func (o *GetAllXappsParams) WithContext(ctx context.Context) *GetAllXappsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get all xapps params +func (o *GetAllXappsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get all xapps params +func (o *GetAllXappsParams) WithHTTPClient(client *http.Client) *GetAllXappsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get all xapps params +func (o *GetAllXappsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WriteToRequest writes these params to a swagger request +func (o *GetAllXappsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/appmgr_client/operations/get_all_xapps_responses.go b/pkg/appmgr_client/operations/get_all_xapps_responses.go new file mode 100644 index 0000000..a48c54d --- /dev/null +++ b/pkg/appmgr_client/operations/get_all_xapps_responses.go @@ -0,0 +1,93 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + + strfmt "github.com/go-openapi/strfmt" + + appmgr_model "routing-manager/pkg/appmgr_model" +) + +// GetAllXappsReader is a Reader for the GetAllXapps structure. +type GetAllXappsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetAllXappsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + + case 200: + result := NewGetAllXappsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + + case 500: + result := NewGetAllXappsInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("unknown error", response, response.Code()) + } +} + +// NewGetAllXappsOK creates a GetAllXappsOK with default headers values +func NewGetAllXappsOK() *GetAllXappsOK { + return &GetAllXappsOK{} +} + +/*GetAllXappsOK handles this case with default header values. + +successful query of xApps +*/ +type GetAllXappsOK struct { + Payload appmgr_model.AllXapps +} + +func (o *GetAllXappsOK) Error() string { + return fmt.Sprintf("[GET /xapps][%d] getAllXappsOK %+v", 200, o.Payload) +} + +func (o *GetAllXappsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetAllXappsInternalServerError creates a GetAllXappsInternalServerError with default headers values +func NewGetAllXappsInternalServerError() *GetAllXappsInternalServerError { + return &GetAllXappsInternalServerError{} +} + +/*GetAllXappsInternalServerError handles this case with default header values. + +Internal error +*/ +type GetAllXappsInternalServerError struct { +} + +func (o *GetAllXappsInternalServerError) Error() string { + return fmt.Sprintf("[GET /xapps][%d] getAllXappsInternalServerError ", 500) +} + +func (o *GetAllXappsInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} diff --git a/pkg/appmgr_client/operations/get_health_parameters.go b/pkg/appmgr_client/operations/get_health_parameters.go new file mode 100644 index 0000000..8bac055 --- /dev/null +++ b/pkg/appmgr_client/operations/get_health_parameters.go @@ -0,0 +1,113 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + + strfmt "github.com/go-openapi/strfmt" +) + +// NewGetHealthParams creates a new GetHealthParams object +// with the default values initialized. +func NewGetHealthParams() *GetHealthParams { + + return &GetHealthParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewGetHealthParamsWithTimeout creates a new GetHealthParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewGetHealthParamsWithTimeout(timeout time.Duration) *GetHealthParams { + + return &GetHealthParams{ + + timeout: timeout, + } +} + +// NewGetHealthParamsWithContext creates a new GetHealthParams object +// with the default values initialized, and the ability to set a context for a request +func NewGetHealthParamsWithContext(ctx context.Context) *GetHealthParams { + + return &GetHealthParams{ + + Context: ctx, + } +} + +// NewGetHealthParamsWithHTTPClient creates a new GetHealthParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewGetHealthParamsWithHTTPClient(client *http.Client) *GetHealthParams { + + return &GetHealthParams{ + HTTPClient: client, + } +} + +/*GetHealthParams contains all the parameters to send to the API endpoint +for the get health operation typically these are written to a http.Request +*/ +type GetHealthParams struct { + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the get health params +func (o *GetHealthParams) WithTimeout(timeout time.Duration) *GetHealthParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get health params +func (o *GetHealthParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get health params +func (o *GetHealthParams) WithContext(ctx context.Context) *GetHealthParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get health params +func (o *GetHealthParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get health params +func (o *GetHealthParams) WithHTTPClient(client *http.Client) *GetHealthParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get health params +func (o *GetHealthParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WriteToRequest writes these params to a swagger request +func (o *GetHealthParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/appmgr_client/operations/get_health_responses.go b/pkg/appmgr_client/operations/get_health_responses.go new file mode 100644 index 0000000..0107009 --- /dev/null +++ b/pkg/appmgr_client/operations/get_health_responses.go @@ -0,0 +1,56 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + + "github.com/go-openapi/runtime" + + strfmt "github.com/go-openapi/strfmt" +) + +// GetHealthReader is a Reader for the GetHealth structure. +type GetHealthReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetHealthReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + + case 200: + result := NewGetHealthOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + + default: + return nil, runtime.NewAPIError("unknown error", response, response.Code()) + } +} + +// NewGetHealthOK creates a GetHealthOK with default headers values +func NewGetHealthOK() *GetHealthOK { + return &GetHealthOK{} +} + +/*GetHealthOK handles this case with default header values. + +Status of xApp Manager is ok +*/ +type GetHealthOK struct { +} + +func (o *GetHealthOK) Error() string { + return fmt.Sprintf("[GET /health][%d] getHealthOK ", 200) +} + +func (o *GetHealthOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} diff --git a/pkg/appmgr_client/operations/get_subscription_by_id_parameters.go b/pkg/appmgr_client/operations/get_subscription_by_id_parameters.go new file mode 100644 index 0000000..49f9cc6 --- /dev/null +++ b/pkg/appmgr_client/operations/get_subscription_by_id_parameters.go @@ -0,0 +1,137 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/swag" + + strfmt "github.com/go-openapi/strfmt" +) + +// NewGetSubscriptionByIDParams creates a new GetSubscriptionByIDParams object +// with the default values initialized. +func NewGetSubscriptionByIDParams() *GetSubscriptionByIDParams { + var () + return &GetSubscriptionByIDParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewGetSubscriptionByIDParamsWithTimeout creates a new GetSubscriptionByIDParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewGetSubscriptionByIDParamsWithTimeout(timeout time.Duration) *GetSubscriptionByIDParams { + var () + return &GetSubscriptionByIDParams{ + + timeout: timeout, + } +} + +// NewGetSubscriptionByIDParamsWithContext creates a new GetSubscriptionByIDParams object +// with the default values initialized, and the ability to set a context for a request +func NewGetSubscriptionByIDParamsWithContext(ctx context.Context) *GetSubscriptionByIDParams { + var () + return &GetSubscriptionByIDParams{ + + Context: ctx, + } +} + +// NewGetSubscriptionByIDParamsWithHTTPClient creates a new GetSubscriptionByIDParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewGetSubscriptionByIDParamsWithHTTPClient(client *http.Client) *GetSubscriptionByIDParams { + var () + return &GetSubscriptionByIDParams{ + HTTPClient: client, + } +} + +/*GetSubscriptionByIDParams contains all the parameters to send to the API endpoint +for the get subscription by Id operation typically these are written to a http.Request +*/ +type GetSubscriptionByIDParams struct { + + /*SubscriptionID + ID of subscription + + */ + SubscriptionID int64 + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the get subscription by Id params +func (o *GetSubscriptionByIDParams) WithTimeout(timeout time.Duration) *GetSubscriptionByIDParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get subscription by Id params +func (o *GetSubscriptionByIDParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get subscription by Id params +func (o *GetSubscriptionByIDParams) WithContext(ctx context.Context) *GetSubscriptionByIDParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get subscription by Id params +func (o *GetSubscriptionByIDParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get subscription by Id params +func (o *GetSubscriptionByIDParams) WithHTTPClient(client *http.Client) *GetSubscriptionByIDParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get subscription by Id params +func (o *GetSubscriptionByIDParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithSubscriptionID adds the subscriptionID to the get subscription by Id params +func (o *GetSubscriptionByIDParams) WithSubscriptionID(subscriptionID int64) *GetSubscriptionByIDParams { + o.SetSubscriptionID(subscriptionID) + return o +} + +// SetSubscriptionID adds the subscriptionId to the get subscription by Id params +func (o *GetSubscriptionByIDParams) SetSubscriptionID(subscriptionID int64) { + o.SubscriptionID = subscriptionID +} + +// WriteToRequest writes these params to a swagger request +func (o *GetSubscriptionByIDParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param subscriptionId + if err := r.SetPathParam("subscriptionId", swag.FormatInt64(o.SubscriptionID)); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/appmgr_client/operations/get_subscription_by_id_responses.go b/pkg/appmgr_client/operations/get_subscription_by_id_responses.go new file mode 100644 index 0000000..2fbadfb --- /dev/null +++ b/pkg/appmgr_client/operations/get_subscription_by_id_responses.go @@ -0,0 +1,123 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + + strfmt "github.com/go-openapi/strfmt" + + appmgr_model "routing-manager/pkg/appmgr_model" +) + +// GetSubscriptionByIDReader is a Reader for the GetSubscriptionByID structure. +type GetSubscriptionByIDReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetSubscriptionByIDReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + + case 200: + result := NewGetSubscriptionByIDOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + + case 400: + result := NewGetSubscriptionByIDBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + case 404: + result := NewGetSubscriptionByIDNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("unknown error", response, response.Code()) + } +} + +// NewGetSubscriptionByIDOK creates a GetSubscriptionByIDOK with default headers values +func NewGetSubscriptionByIDOK() *GetSubscriptionByIDOK { + return &GetSubscriptionByIDOK{} +} + +/*GetSubscriptionByIDOK handles this case with default header values. + +successful operation +*/ +type GetSubscriptionByIDOK struct { + Payload *appmgr_model.Subscription +} + +func (o *GetSubscriptionByIDOK) Error() string { + return fmt.Sprintf("[GET /subscriptions/{subscriptionId}][%d] getSubscriptionByIdOK %+v", 200, o.Payload) +} + +func (o *GetSubscriptionByIDOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(appmgr_model.Subscription) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetSubscriptionByIDBadRequest creates a GetSubscriptionByIDBadRequest with default headers values +func NewGetSubscriptionByIDBadRequest() *GetSubscriptionByIDBadRequest { + return &GetSubscriptionByIDBadRequest{} +} + +/*GetSubscriptionByIDBadRequest handles this case with default header values. + +Invalid ID supplied +*/ +type GetSubscriptionByIDBadRequest struct { +} + +func (o *GetSubscriptionByIDBadRequest) Error() string { + return fmt.Sprintf("[GET /subscriptions/{subscriptionId}][%d] getSubscriptionByIdBadRequest ", 400) +} + +func (o *GetSubscriptionByIDBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +// NewGetSubscriptionByIDNotFound creates a GetSubscriptionByIDNotFound with default headers values +func NewGetSubscriptionByIDNotFound() *GetSubscriptionByIDNotFound { + return &GetSubscriptionByIDNotFound{} +} + +/*GetSubscriptionByIDNotFound handles this case with default header values. + +Subscription not found +*/ +type GetSubscriptionByIDNotFound struct { +} + +func (o *GetSubscriptionByIDNotFound) Error() string { + return fmt.Sprintf("[GET /subscriptions/{subscriptionId}][%d] getSubscriptionByIdNotFound ", 404) +} + +func (o *GetSubscriptionByIDNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} diff --git a/pkg/appmgr_client/operations/get_subscriptions_parameters.go b/pkg/appmgr_client/operations/get_subscriptions_parameters.go new file mode 100644 index 0000000..0b08d95 --- /dev/null +++ b/pkg/appmgr_client/operations/get_subscriptions_parameters.go @@ -0,0 +1,113 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + + strfmt "github.com/go-openapi/strfmt" +) + +// NewGetSubscriptionsParams creates a new GetSubscriptionsParams object +// with the default values initialized. +func NewGetSubscriptionsParams() *GetSubscriptionsParams { + + return &GetSubscriptionsParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewGetSubscriptionsParamsWithTimeout creates a new GetSubscriptionsParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewGetSubscriptionsParamsWithTimeout(timeout time.Duration) *GetSubscriptionsParams { + + return &GetSubscriptionsParams{ + + timeout: timeout, + } +} + +// NewGetSubscriptionsParamsWithContext creates a new GetSubscriptionsParams object +// with the default values initialized, and the ability to set a context for a request +func NewGetSubscriptionsParamsWithContext(ctx context.Context) *GetSubscriptionsParams { + + return &GetSubscriptionsParams{ + + Context: ctx, + } +} + +// NewGetSubscriptionsParamsWithHTTPClient creates a new GetSubscriptionsParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewGetSubscriptionsParamsWithHTTPClient(client *http.Client) *GetSubscriptionsParams { + + return &GetSubscriptionsParams{ + HTTPClient: client, + } +} + +/*GetSubscriptionsParams contains all the parameters to send to the API endpoint +for the get subscriptions operation typically these are written to a http.Request +*/ +type GetSubscriptionsParams struct { + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the get subscriptions params +func (o *GetSubscriptionsParams) WithTimeout(timeout time.Duration) *GetSubscriptionsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get subscriptions params +func (o *GetSubscriptionsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get subscriptions params +func (o *GetSubscriptionsParams) WithContext(ctx context.Context) *GetSubscriptionsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get subscriptions params +func (o *GetSubscriptionsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get subscriptions params +func (o *GetSubscriptionsParams) WithHTTPClient(client *http.Client) *GetSubscriptionsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get subscriptions params +func (o *GetSubscriptionsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WriteToRequest writes these params to a swagger request +func (o *GetSubscriptionsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/appmgr_client/operations/get_subscriptions_responses.go b/pkg/appmgr_client/operations/get_subscriptions_responses.go new file mode 100644 index 0000000..9a2a704 --- /dev/null +++ b/pkg/appmgr_client/operations/get_subscriptions_responses.go @@ -0,0 +1,65 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + + strfmt "github.com/go-openapi/strfmt" + + appmgr_model "routing-manager/pkg/appmgr_model" +) + +// GetSubscriptionsReader is a Reader for the GetSubscriptions structure. +type GetSubscriptionsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetSubscriptionsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + + case 200: + result := NewGetSubscriptionsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + + default: + return nil, runtime.NewAPIError("unknown error", response, response.Code()) + } +} + +// NewGetSubscriptionsOK creates a GetSubscriptionsOK with default headers values +func NewGetSubscriptionsOK() *GetSubscriptionsOK { + return &GetSubscriptionsOK{} +} + +/*GetSubscriptionsOK handles this case with default header values. + +successful query of subscriptions +*/ +type GetSubscriptionsOK struct { + Payload appmgr_model.AllSubscriptions +} + +func (o *GetSubscriptionsOK) Error() string { + return fmt.Sprintf("[GET /subscriptions][%d] getSubscriptionsOK %+v", 200, o.Payload) +} + +func (o *GetSubscriptionsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/appmgr_client/operations/get_xapp_by_name_parameters.go b/pkg/appmgr_client/operations/get_xapp_by_name_parameters.go new file mode 100644 index 0000000..ea7bfac --- /dev/null +++ b/pkg/appmgr_client/operations/get_xapp_by_name_parameters.go @@ -0,0 +1,136 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + + strfmt "github.com/go-openapi/strfmt" +) + +// NewGetXappByNameParams creates a new GetXappByNameParams object +// with the default values initialized. +func NewGetXappByNameParams() *GetXappByNameParams { + var () + return &GetXappByNameParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewGetXappByNameParamsWithTimeout creates a new GetXappByNameParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewGetXappByNameParamsWithTimeout(timeout time.Duration) *GetXappByNameParams { + var () + return &GetXappByNameParams{ + + timeout: timeout, + } +} + +// NewGetXappByNameParamsWithContext creates a new GetXappByNameParams object +// with the default values initialized, and the ability to set a context for a request +func NewGetXappByNameParamsWithContext(ctx context.Context) *GetXappByNameParams { + var () + return &GetXappByNameParams{ + + Context: ctx, + } +} + +// NewGetXappByNameParamsWithHTTPClient creates a new GetXappByNameParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewGetXappByNameParamsWithHTTPClient(client *http.Client) *GetXappByNameParams { + var () + return &GetXappByNameParams{ + HTTPClient: client, + } +} + +/*GetXappByNameParams contains all the parameters to send to the API endpoint +for the get xapp by name operation typically these are written to a http.Request +*/ +type GetXappByNameParams struct { + + /*XAppName + Name of xApp + + */ + XAppName string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the get xapp by name params +func (o *GetXappByNameParams) WithTimeout(timeout time.Duration) *GetXappByNameParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get xapp by name params +func (o *GetXappByNameParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get xapp by name params +func (o *GetXappByNameParams) WithContext(ctx context.Context) *GetXappByNameParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get xapp by name params +func (o *GetXappByNameParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get xapp by name params +func (o *GetXappByNameParams) WithHTTPClient(client *http.Client) *GetXappByNameParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get xapp by name params +func (o *GetXappByNameParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithXAppName adds the xAppName to the get xapp by name params +func (o *GetXappByNameParams) WithXAppName(xAppName string) *GetXappByNameParams { + o.SetXAppName(xAppName) + return o +} + +// SetXAppName adds the xAppName to the get xapp by name params +func (o *GetXappByNameParams) SetXAppName(xAppName string) { + o.XAppName = xAppName +} + +// WriteToRequest writes these params to a swagger request +func (o *GetXappByNameParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param xAppName + if err := r.SetPathParam("xAppName", o.XAppName); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/appmgr_client/operations/get_xapp_by_name_responses.go b/pkg/appmgr_client/operations/get_xapp_by_name_responses.go new file mode 100644 index 0000000..1a1e30e --- /dev/null +++ b/pkg/appmgr_client/operations/get_xapp_by_name_responses.go @@ -0,0 +1,151 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + + strfmt "github.com/go-openapi/strfmt" + + appmgr_model "routing-manager/pkg/appmgr_model" +) + +// GetXappByNameReader is a Reader for the GetXappByName structure. +type GetXappByNameReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetXappByNameReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + + case 200: + result := NewGetXappByNameOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + + case 400: + result := NewGetXappByNameBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + case 404: + result := NewGetXappByNameNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + case 500: + result := NewGetXappByNameInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("unknown error", response, response.Code()) + } +} + +// NewGetXappByNameOK creates a GetXappByNameOK with default headers values +func NewGetXappByNameOK() *GetXappByNameOK { + return &GetXappByNameOK{} +} + +/*GetXappByNameOK handles this case with default header values. + +successful operation +*/ +type GetXappByNameOK struct { + Payload *appmgr_model.Xapp +} + +func (o *GetXappByNameOK) Error() string { + return fmt.Sprintf("[GET /xapps/{xAppName}][%d] getXappByNameOK %+v", 200, o.Payload) +} + +func (o *GetXappByNameOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(appmgr_model.Xapp) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetXappByNameBadRequest creates a GetXappByNameBadRequest with default headers values +func NewGetXappByNameBadRequest() *GetXappByNameBadRequest { + return &GetXappByNameBadRequest{} +} + +/*GetXappByNameBadRequest handles this case with default header values. + +Invalid ID supplied +*/ +type GetXappByNameBadRequest struct { +} + +func (o *GetXappByNameBadRequest) Error() string { + return fmt.Sprintf("[GET /xapps/{xAppName}][%d] getXappByNameBadRequest ", 400) +} + +func (o *GetXappByNameBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +// NewGetXappByNameNotFound creates a GetXappByNameNotFound with default headers values +func NewGetXappByNameNotFound() *GetXappByNameNotFound { + return &GetXappByNameNotFound{} +} + +/*GetXappByNameNotFound handles this case with default header values. + +Xapp not found +*/ +type GetXappByNameNotFound struct { +} + +func (o *GetXappByNameNotFound) Error() string { + return fmt.Sprintf("[GET /xapps/{xAppName}][%d] getXappByNameNotFound ", 404) +} + +func (o *GetXappByNameNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +// NewGetXappByNameInternalServerError creates a GetXappByNameInternalServerError with default headers values +func NewGetXappByNameInternalServerError() *GetXappByNameInternalServerError { + return &GetXappByNameInternalServerError{} +} + +/*GetXappByNameInternalServerError handles this case with default header values. + +Internal error +*/ +type GetXappByNameInternalServerError struct { +} + +func (o *GetXappByNameInternalServerError) Error() string { + return fmt.Sprintf("[GET /xapps/{xAppName}][%d] getXappByNameInternalServerError ", 500) +} + +func (o *GetXappByNameInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} diff --git a/pkg/appmgr_client/operations/get_xapp_instance_by_name_parameters.go b/pkg/appmgr_client/operations/get_xapp_instance_by_name_parameters.go new file mode 100644 index 0000000..b0dff67 --- /dev/null +++ b/pkg/appmgr_client/operations/get_xapp_instance_by_name_parameters.go @@ -0,0 +1,157 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + + strfmt "github.com/go-openapi/strfmt" +) + +// NewGetXappInstanceByNameParams creates a new GetXappInstanceByNameParams object +// with the default values initialized. +func NewGetXappInstanceByNameParams() *GetXappInstanceByNameParams { + var () + return &GetXappInstanceByNameParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewGetXappInstanceByNameParamsWithTimeout creates a new GetXappInstanceByNameParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewGetXappInstanceByNameParamsWithTimeout(timeout time.Duration) *GetXappInstanceByNameParams { + var () + return &GetXappInstanceByNameParams{ + + timeout: timeout, + } +} + +// NewGetXappInstanceByNameParamsWithContext creates a new GetXappInstanceByNameParams object +// with the default values initialized, and the ability to set a context for a request +func NewGetXappInstanceByNameParamsWithContext(ctx context.Context) *GetXappInstanceByNameParams { + var () + return &GetXappInstanceByNameParams{ + + Context: ctx, + } +} + +// NewGetXappInstanceByNameParamsWithHTTPClient creates a new GetXappInstanceByNameParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewGetXappInstanceByNameParamsWithHTTPClient(client *http.Client) *GetXappInstanceByNameParams { + var () + return &GetXappInstanceByNameParams{ + HTTPClient: client, + } +} + +/*GetXappInstanceByNameParams contains all the parameters to send to the API endpoint +for the get xapp instance by name operation typically these are written to a http.Request +*/ +type GetXappInstanceByNameParams struct { + + /*XAppInstanceName + Name of xApp instance to get information + + */ + XAppInstanceName string + /*XAppName + Name of xApp + + */ + XAppName string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the get xapp instance by name params +func (o *GetXappInstanceByNameParams) WithTimeout(timeout time.Duration) *GetXappInstanceByNameParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get xapp instance by name params +func (o *GetXappInstanceByNameParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get xapp instance by name params +func (o *GetXappInstanceByNameParams) WithContext(ctx context.Context) *GetXappInstanceByNameParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get xapp instance by name params +func (o *GetXappInstanceByNameParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get xapp instance by name params +func (o *GetXappInstanceByNameParams) WithHTTPClient(client *http.Client) *GetXappInstanceByNameParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get xapp instance by name params +func (o *GetXappInstanceByNameParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithXAppInstanceName adds the xAppInstanceName to the get xapp instance by name params +func (o *GetXappInstanceByNameParams) WithXAppInstanceName(xAppInstanceName string) *GetXappInstanceByNameParams { + o.SetXAppInstanceName(xAppInstanceName) + return o +} + +// SetXAppInstanceName adds the xAppInstanceName to the get xapp instance by name params +func (o *GetXappInstanceByNameParams) SetXAppInstanceName(xAppInstanceName string) { + o.XAppInstanceName = xAppInstanceName +} + +// WithXAppName adds the xAppName to the get xapp instance by name params +func (o *GetXappInstanceByNameParams) WithXAppName(xAppName string) *GetXappInstanceByNameParams { + o.SetXAppName(xAppName) + return o +} + +// SetXAppName adds the xAppName to the get xapp instance by name params +func (o *GetXappInstanceByNameParams) SetXAppName(xAppName string) { + o.XAppName = xAppName +} + +// WriteToRequest writes these params to a swagger request +func (o *GetXappInstanceByNameParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param xAppInstanceName + if err := r.SetPathParam("xAppInstanceName", o.XAppInstanceName); err != nil { + return err + } + + // path param xAppName + if err := r.SetPathParam("xAppName", o.XAppName); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/appmgr_client/operations/get_xapp_instance_by_name_responses.go b/pkg/appmgr_client/operations/get_xapp_instance_by_name_responses.go new file mode 100644 index 0000000..1e0352c --- /dev/null +++ b/pkg/appmgr_client/operations/get_xapp_instance_by_name_responses.go @@ -0,0 +1,151 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + + strfmt "github.com/go-openapi/strfmt" + + appmgr_model "routing-manager/pkg/appmgr_model" +) + +// GetXappInstanceByNameReader is a Reader for the GetXappInstanceByName structure. +type GetXappInstanceByNameReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetXappInstanceByNameReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + + case 200: + result := NewGetXappInstanceByNameOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + + case 400: + result := NewGetXappInstanceByNameBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + case 404: + result := NewGetXappInstanceByNameNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + case 500: + result := NewGetXappInstanceByNameInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("unknown error", response, response.Code()) + } +} + +// NewGetXappInstanceByNameOK creates a GetXappInstanceByNameOK with default headers values +func NewGetXappInstanceByNameOK() *GetXappInstanceByNameOK { + return &GetXappInstanceByNameOK{} +} + +/*GetXappInstanceByNameOK handles this case with default header values. + +successful operation +*/ +type GetXappInstanceByNameOK struct { + Payload *appmgr_model.XappInstance +} + +func (o *GetXappInstanceByNameOK) Error() string { + return fmt.Sprintf("[GET /xapps/{xAppName}/instances/{xAppInstanceName}][%d] getXappInstanceByNameOK %+v", 200, o.Payload) +} + +func (o *GetXappInstanceByNameOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(appmgr_model.XappInstance) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetXappInstanceByNameBadRequest creates a GetXappInstanceByNameBadRequest with default headers values +func NewGetXappInstanceByNameBadRequest() *GetXappInstanceByNameBadRequest { + return &GetXappInstanceByNameBadRequest{} +} + +/*GetXappInstanceByNameBadRequest handles this case with default header values. + +Invalid name supplied +*/ +type GetXappInstanceByNameBadRequest struct { +} + +func (o *GetXappInstanceByNameBadRequest) Error() string { + return fmt.Sprintf("[GET /xapps/{xAppName}/instances/{xAppInstanceName}][%d] getXappInstanceByNameBadRequest ", 400) +} + +func (o *GetXappInstanceByNameBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +// NewGetXappInstanceByNameNotFound creates a GetXappInstanceByNameNotFound with default headers values +func NewGetXappInstanceByNameNotFound() *GetXappInstanceByNameNotFound { + return &GetXappInstanceByNameNotFound{} +} + +/*GetXappInstanceByNameNotFound handles this case with default header values. + +Xapp not found +*/ +type GetXappInstanceByNameNotFound struct { +} + +func (o *GetXappInstanceByNameNotFound) Error() string { + return fmt.Sprintf("[GET /xapps/{xAppName}/instances/{xAppInstanceName}][%d] getXappInstanceByNameNotFound ", 404) +} + +func (o *GetXappInstanceByNameNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +// NewGetXappInstanceByNameInternalServerError creates a GetXappInstanceByNameInternalServerError with default headers values +func NewGetXappInstanceByNameInternalServerError() *GetXappInstanceByNameInternalServerError { + return &GetXappInstanceByNameInternalServerError{} +} + +/*GetXappInstanceByNameInternalServerError handles this case with default header values. + +Internal error +*/ +type GetXappInstanceByNameInternalServerError struct { +} + +func (o *GetXappInstanceByNameInternalServerError) Error() string { + return fmt.Sprintf("[GET /xapps/{xAppName}/instances/{xAppInstanceName}][%d] getXappInstanceByNameInternalServerError ", 500) +} + +func (o *GetXappInstanceByNameInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} diff --git a/pkg/appmgr_client/operations/modify_subscription_parameters.go b/pkg/appmgr_client/operations/modify_subscription_parameters.go new file mode 100644 index 0000000..e10b666 --- /dev/null +++ b/pkg/appmgr_client/operations/modify_subscription_parameters.go @@ -0,0 +1,161 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/swag" + + strfmt "github.com/go-openapi/strfmt" + + appmgr_model "routing-manager/pkg/appmgr_model" +) + +// NewModifySubscriptionParams creates a new ModifySubscriptionParams object +// with the default values initialized. +func NewModifySubscriptionParams() *ModifySubscriptionParams { + var () + return &ModifySubscriptionParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewModifySubscriptionParamsWithTimeout creates a new ModifySubscriptionParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewModifySubscriptionParamsWithTimeout(timeout time.Duration) *ModifySubscriptionParams { + var () + return &ModifySubscriptionParams{ + + timeout: timeout, + } +} + +// NewModifySubscriptionParamsWithContext creates a new ModifySubscriptionParams object +// with the default values initialized, and the ability to set a context for a request +func NewModifySubscriptionParamsWithContext(ctx context.Context) *ModifySubscriptionParams { + var () + return &ModifySubscriptionParams{ + + Context: ctx, + } +} + +// NewModifySubscriptionParamsWithHTTPClient creates a new ModifySubscriptionParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewModifySubscriptionParamsWithHTTPClient(client *http.Client) *ModifySubscriptionParams { + var () + return &ModifySubscriptionParams{ + HTTPClient: client, + } +} + +/*ModifySubscriptionParams contains all the parameters to send to the API endpoint +for the modify subscription operation typically these are written to a http.Request +*/ +type ModifySubscriptionParams struct { + + /*SubscriptionID + ID of subscription + + */ + SubscriptionID int64 + /*SubscriptionRequest + Modified subscription + + */ + SubscriptionRequest *appmgr_model.SubscriptionRequest + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the modify subscription params +func (o *ModifySubscriptionParams) WithTimeout(timeout time.Duration) *ModifySubscriptionParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the modify subscription params +func (o *ModifySubscriptionParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the modify subscription params +func (o *ModifySubscriptionParams) WithContext(ctx context.Context) *ModifySubscriptionParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the modify subscription params +func (o *ModifySubscriptionParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the modify subscription params +func (o *ModifySubscriptionParams) WithHTTPClient(client *http.Client) *ModifySubscriptionParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the modify subscription params +func (o *ModifySubscriptionParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithSubscriptionID adds the subscriptionID to the modify subscription params +func (o *ModifySubscriptionParams) WithSubscriptionID(subscriptionID int64) *ModifySubscriptionParams { + o.SetSubscriptionID(subscriptionID) + return o +} + +// SetSubscriptionID adds the subscriptionId to the modify subscription params +func (o *ModifySubscriptionParams) SetSubscriptionID(subscriptionID int64) { + o.SubscriptionID = subscriptionID +} + +// WithSubscriptionRequest adds the subscriptionRequest to the modify subscription params +func (o *ModifySubscriptionParams) WithSubscriptionRequest(subscriptionRequest *appmgr_model.SubscriptionRequest) *ModifySubscriptionParams { + o.SetSubscriptionRequest(subscriptionRequest) + return o +} + +// SetSubscriptionRequest adds the subscriptionRequest to the modify subscription params +func (o *ModifySubscriptionParams) SetSubscriptionRequest(subscriptionRequest *appmgr_model.SubscriptionRequest) { + o.SubscriptionRequest = subscriptionRequest +} + +// WriteToRequest writes these params to a swagger request +func (o *ModifySubscriptionParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param subscriptionId + if err := r.SetPathParam("subscriptionId", swag.FormatInt64(o.SubscriptionID)); err != nil { + return err + } + + if o.SubscriptionRequest != nil { + if err := r.SetBodyParam(o.SubscriptionRequest); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/appmgr_client/operations/modify_subscription_responses.go b/pkg/appmgr_client/operations/modify_subscription_responses.go new file mode 100644 index 0000000..3522f63 --- /dev/null +++ b/pkg/appmgr_client/operations/modify_subscription_responses.go @@ -0,0 +1,95 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + + strfmt "github.com/go-openapi/strfmt" + + appmgr_model "routing-manager/pkg/appmgr_model" +) + +// ModifySubscriptionReader is a Reader for the ModifySubscription structure. +type ModifySubscriptionReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ModifySubscriptionReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + + case 200: + result := NewModifySubscriptionOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + + case 400: + result := NewModifySubscriptionBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("unknown error", response, response.Code()) + } +} + +// NewModifySubscriptionOK creates a ModifySubscriptionOK with default headers values +func NewModifySubscriptionOK() *ModifySubscriptionOK { + return &ModifySubscriptionOK{} +} + +/*ModifySubscriptionOK handles this case with default header values. + +Subscription modification successful +*/ +type ModifySubscriptionOK struct { + Payload *appmgr_model.SubscriptionResponse +} + +func (o *ModifySubscriptionOK) Error() string { + return fmt.Sprintf("[PUT /subscriptions/{subscriptionId}][%d] modifySubscriptionOK %+v", 200, o.Payload) +} + +func (o *ModifySubscriptionOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(appmgr_model.SubscriptionResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewModifySubscriptionBadRequest creates a ModifySubscriptionBadRequest with default headers values +func NewModifySubscriptionBadRequest() *ModifySubscriptionBadRequest { + return &ModifySubscriptionBadRequest{} +} + +/*ModifySubscriptionBadRequest handles this case with default header values. + +Invalid input +*/ +type ModifySubscriptionBadRequest struct { +} + +func (o *ModifySubscriptionBadRequest) Error() string { + return fmt.Sprintf("[PUT /subscriptions/{subscriptionId}][%d] modifySubscriptionBadRequest ", 400) +} + +func (o *ModifySubscriptionBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} diff --git a/pkg/appmgr_client/operations/operations_client.go b/pkg/appmgr_client/operations/operations_client.go new file mode 100644 index 0000000..4e00d83 --- /dev/null +++ b/pkg/appmgr_client/operations/operations_client.go @@ -0,0 +1,338 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/runtime" + + strfmt "github.com/go-openapi/strfmt" +) + +// New creates a new operations API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) *Client { + return &Client{transport: transport, formats: formats} +} + +/* +Client for operations API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +/* +AddSubscription subscribes event +*/ +func (a *Client) AddSubscription(params *AddSubscriptionParams) (*AddSubscriptionOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewAddSubscriptionParams() + } + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "addSubscription", + Method: "POST", + PathPattern: "/subscriptions", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &AddSubscriptionReader{formats: a.formats}, + Context: params.Context, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*AddSubscriptionOK), nil + +} + +/* +DeleteSubscription unsubscribes event +*/ +func (a *Client) DeleteSubscription(params *DeleteSubscriptionParams) (*DeleteSubscriptionNoContent, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteSubscriptionParams() + } + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "deleteSubscription", + Method: "DELETE", + PathPattern: "/subscriptions/{subscriptionId}", + ProducesMediaTypes: []string{""}, + ConsumesMediaTypes: []string{""}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &DeleteSubscriptionReader{formats: a.formats}, + Context: params.Context, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*DeleteSubscriptionNoContent), nil + +} + +/* +DeployXapp deploys a xapp +*/ +func (a *Client) DeployXapp(params *DeployXappParams) (*DeployXappCreated, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDeployXappParams() + } + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "deployXapp", + Method: "POST", + PathPattern: "/xapps", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &DeployXappReader{formats: a.formats}, + Context: params.Context, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*DeployXappCreated), nil + +} + +/* +GetAllXapps returns the status of all xapps +*/ +func (a *Client) GetAllXapps(params *GetAllXappsParams) (*GetAllXappsOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetAllXappsParams() + } + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "getAllXapps", + Method: "GET", + PathPattern: "/xapps", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{""}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &GetAllXappsReader{formats: a.formats}, + Context: params.Context, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*GetAllXappsOK), nil + +} + +/* +GetHealth healths check of x app manager +*/ +func (a *Client) GetHealth(params *GetHealthParams) (*GetHealthOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetHealthParams() + } + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "getHealth", + Method: "GET", + PathPattern: "/health", + ProducesMediaTypes: []string{""}, + ConsumesMediaTypes: []string{""}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &GetHealthReader{formats: a.formats}, + Context: params.Context, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*GetHealthOK), nil + +} + +/* +GetSubscriptionByID returns the information of subscription +*/ +func (a *Client) GetSubscriptionByID(params *GetSubscriptionByIDParams) (*GetSubscriptionByIDOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetSubscriptionByIDParams() + } + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "getSubscriptionById", + Method: "GET", + PathPattern: "/subscriptions/{subscriptionId}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{""}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &GetSubscriptionByIDReader{formats: a.formats}, + Context: params.Context, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*GetSubscriptionByIDOK), nil + +} + +/* +GetSubscriptions returns all subscriptions +*/ +func (a *Client) GetSubscriptions(params *GetSubscriptionsParams) (*GetSubscriptionsOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetSubscriptionsParams() + } + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "getSubscriptions", + Method: "GET", + PathPattern: "/subscriptions", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{""}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &GetSubscriptionsReader{formats: a.formats}, + Context: params.Context, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*GetSubscriptionsOK), nil + +} + +/* +GetXappByName returns the status of a given xapp +*/ +func (a *Client) GetXappByName(params *GetXappByNameParams) (*GetXappByNameOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetXappByNameParams() + } + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "getXappByName", + Method: "GET", + PathPattern: "/xapps/{xAppName}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{""}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &GetXappByNameReader{formats: a.formats}, + Context: params.Context, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*GetXappByNameOK), nil + +} + +/* +GetXappInstanceByName returns the status of a given xapp +*/ +func (a *Client) GetXappInstanceByName(params *GetXappInstanceByNameParams) (*GetXappInstanceByNameOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetXappInstanceByNameParams() + } + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "getXappInstanceByName", + Method: "GET", + PathPattern: "/xapps/{xAppName}/instances/{xAppInstanceName}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{""}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &GetXappInstanceByNameReader{formats: a.formats}, + Context: params.Context, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*GetXappInstanceByNameOK), nil + +} + +/* +ModifySubscription modifies event subscription +*/ +func (a *Client) ModifySubscription(params *ModifySubscriptionParams) (*ModifySubscriptionOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewModifySubscriptionParams() + } + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "modifySubscription", + Method: "PUT", + PathPattern: "/subscriptions/{subscriptionId}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &ModifySubscriptionReader{formats: a.formats}, + Context: params.Context, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*ModifySubscriptionOK), nil + +} + +/* +UndeployXapp undeploys an existing xapp +*/ +func (a *Client) UndeployXapp(params *UndeployXappParams) (*UndeployXappNoContent, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewUndeployXappParams() + } + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "undeployXapp", + Method: "DELETE", + PathPattern: "/xapps/{xAppName}", + ProducesMediaTypes: []string{""}, + ConsumesMediaTypes: []string{""}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &UndeployXappReader{formats: a.formats}, + Context: params.Context, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*UndeployXappNoContent), nil + +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/pkg/appmgr_client/operations/undeploy_xapp_parameters.go b/pkg/appmgr_client/operations/undeploy_xapp_parameters.go new file mode 100644 index 0000000..a427d68 --- /dev/null +++ b/pkg/appmgr_client/operations/undeploy_xapp_parameters.go @@ -0,0 +1,136 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + + strfmt "github.com/go-openapi/strfmt" +) + +// NewUndeployXappParams creates a new UndeployXappParams object +// with the default values initialized. +func NewUndeployXappParams() *UndeployXappParams { + var () + return &UndeployXappParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewUndeployXappParamsWithTimeout creates a new UndeployXappParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewUndeployXappParamsWithTimeout(timeout time.Duration) *UndeployXappParams { + var () + return &UndeployXappParams{ + + timeout: timeout, + } +} + +// NewUndeployXappParamsWithContext creates a new UndeployXappParams object +// with the default values initialized, and the ability to set a context for a request +func NewUndeployXappParamsWithContext(ctx context.Context) *UndeployXappParams { + var () + return &UndeployXappParams{ + + Context: ctx, + } +} + +// NewUndeployXappParamsWithHTTPClient creates a new UndeployXappParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewUndeployXappParamsWithHTTPClient(client *http.Client) *UndeployXappParams { + var () + return &UndeployXappParams{ + HTTPClient: client, + } +} + +/*UndeployXappParams contains all the parameters to send to the API endpoint +for the undeploy xapp operation typically these are written to a http.Request +*/ +type UndeployXappParams struct { + + /*XAppName + Xapp to be undeployed + + */ + XAppName string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the undeploy xapp params +func (o *UndeployXappParams) WithTimeout(timeout time.Duration) *UndeployXappParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the undeploy xapp params +func (o *UndeployXappParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the undeploy xapp params +func (o *UndeployXappParams) WithContext(ctx context.Context) *UndeployXappParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the undeploy xapp params +func (o *UndeployXappParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the undeploy xapp params +func (o *UndeployXappParams) WithHTTPClient(client *http.Client) *UndeployXappParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the undeploy xapp params +func (o *UndeployXappParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithXAppName adds the xAppName to the undeploy xapp params +func (o *UndeployXappParams) WithXAppName(xAppName string) *UndeployXappParams { + o.SetXAppName(xAppName) + return o +} + +// SetXAppName adds the xAppName to the undeploy xapp params +func (o *UndeployXappParams) SetXAppName(xAppName string) { + o.XAppName = xAppName +} + +// WriteToRequest writes these params to a swagger request +func (o *UndeployXappParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param xAppName + if err := r.SetPathParam("xAppName", o.XAppName); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/appmgr_client/operations/undeploy_xapp_responses.go b/pkg/appmgr_client/operations/undeploy_xapp_responses.go new file mode 100644 index 0000000..fef52c4 --- /dev/null +++ b/pkg/appmgr_client/operations/undeploy_xapp_responses.go @@ -0,0 +1,112 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + + "github.com/go-openapi/runtime" + + strfmt "github.com/go-openapi/strfmt" +) + +// UndeployXappReader is a Reader for the UndeployXapp structure. +type UndeployXappReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *UndeployXappReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + + case 204: + result := NewUndeployXappNoContent() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + + case 400: + result := NewUndeployXappBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + case 500: + result := NewUndeployXappInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("unknown error", response, response.Code()) + } +} + +// NewUndeployXappNoContent creates a UndeployXappNoContent with default headers values +func NewUndeployXappNoContent() *UndeployXappNoContent { + return &UndeployXappNoContent{} +} + +/*UndeployXappNoContent handles this case with default header values. + +Successful deletion of xApp +*/ +type UndeployXappNoContent struct { +} + +func (o *UndeployXappNoContent) Error() string { + return fmt.Sprintf("[DELETE /xapps/{xAppName}][%d] undeployXappNoContent ", 204) +} + +func (o *UndeployXappNoContent) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +// NewUndeployXappBadRequest creates a UndeployXappBadRequest with default headers values +func NewUndeployXappBadRequest() *UndeployXappBadRequest { + return &UndeployXappBadRequest{} +} + +/*UndeployXappBadRequest handles this case with default header values. + +Invalid xApp name supplied +*/ +type UndeployXappBadRequest struct { +} + +func (o *UndeployXappBadRequest) Error() string { + return fmt.Sprintf("[DELETE /xapps/{xAppName}][%d] undeployXappBadRequest ", 400) +} + +func (o *UndeployXappBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +// NewUndeployXappInternalServerError creates a UndeployXappInternalServerError with default headers values +func NewUndeployXappInternalServerError() *UndeployXappInternalServerError { + return &UndeployXappInternalServerError{} +} + +/*UndeployXappInternalServerError handles this case with default header values. + +Internal error +*/ +type UndeployXappInternalServerError struct { +} + +func (o *UndeployXappInternalServerError) Error() string { + return fmt.Sprintf("[DELETE /xapps/{xAppName}][%d] undeployXappInternalServerError ", 500) +} + +func (o *UndeployXappInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} diff --git a/pkg/appmgr_client/r_i_c_appmgr_client.go b/pkg/appmgr_client/r_i_c_appmgr_client.go new file mode 100644 index 0000000..6eaffdf --- /dev/null +++ b/pkg/appmgr_client/r_i_c_appmgr_client.go @@ -0,0 +1,117 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package appmgr_client + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/runtime" + httptransport "github.com/go-openapi/runtime/client" + + strfmt "github.com/go-openapi/strfmt" + + "routing-manager/pkg/appmgr_client/operations" +) + +// Default r i c appmgr HTTP client. +var Default = NewHTTPClient(nil) + +const ( + // DefaultHost is the default Host + // found in Meta (info) section of spec file + DefaultHost string = "hostname" + // DefaultBasePath is the default BasePath + // found in Meta (info) section of spec file + DefaultBasePath string = "/ric/v1" +) + +// DefaultSchemes are the default schemes found in Meta (info) section of spec file +var DefaultSchemes = []string{"http", "https"} + +// NewHTTPClient creates a new r i c appmgr HTTP client. +func NewHTTPClient(formats strfmt.Registry) *RICAppmgr { + return NewHTTPClientWithConfig(formats, nil) +} + +// NewHTTPClientWithConfig creates a new r i c appmgr HTTP client, +// using a customizable transport config. +func NewHTTPClientWithConfig(formats strfmt.Registry, cfg *TransportConfig) *RICAppmgr { + // ensure nullable parameters have default + if cfg == nil { + cfg = DefaultTransportConfig() + } + + // create transport and client + transport := httptransport.New(cfg.Host, cfg.BasePath, cfg.Schemes) + return New(transport, formats) +} + +// New creates a new r i c appmgr client +func New(transport runtime.ClientTransport, formats strfmt.Registry) *RICAppmgr { + // ensure nullable parameters have default + if formats == nil { + formats = strfmt.Default + } + + cli := new(RICAppmgr) + cli.Transport = transport + + cli.Operations = operations.New(transport, formats) + + return cli +} + +// DefaultTransportConfig creates a TransportConfig with the +// default settings taken from the meta section of the spec file. +func DefaultTransportConfig() *TransportConfig { + return &TransportConfig{ + Host: DefaultHost, + BasePath: DefaultBasePath, + Schemes: DefaultSchemes, + } +} + +// TransportConfig contains the transport related info, +// found in the meta section of the spec file. +type TransportConfig struct { + Host string + BasePath string + Schemes []string +} + +// WithHost overrides the default host, +// provided by the meta section of the spec file. +func (cfg *TransportConfig) WithHost(host string) *TransportConfig { + cfg.Host = host + return cfg +} + +// WithBasePath overrides the default basePath, +// provided by the meta section of the spec file. +func (cfg *TransportConfig) WithBasePath(basePath string) *TransportConfig { + cfg.BasePath = basePath + return cfg +} + +// WithSchemes overrides the default schemes, +// provided by the meta section of the spec file. +func (cfg *TransportConfig) WithSchemes(schemes []string) *TransportConfig { + cfg.Schemes = schemes + return cfg +} + +// RICAppmgr is a client for r i c appmgr +type RICAppmgr struct { + Operations *operations.Client + + Transport runtime.ClientTransport +} + +// SetTransport changes the transport on the client and all its subresources +func (c *RICAppmgr) SetTransport(transport runtime.ClientTransport) { + c.Transport = transport + + c.Operations.SetTransport(transport) + +} diff --git a/pkg/appmgr_model/all_subscriptions.go b/pkg/appmgr_model/all_subscriptions.go new file mode 100644 index 0000000..301f7c4 --- /dev/null +++ b/pkg/appmgr_model/all_subscriptions.go @@ -0,0 +1,45 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package appmgr_model + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "strconv" + + strfmt "github.com/go-openapi/strfmt" + + "github.com/go-openapi/errors" + "github.com/go-openapi/swag" +) + +// AllSubscriptions all subscriptions +// swagger:model allSubscriptions +type AllSubscriptions []*Subscription + +// Validate validates this all subscriptions +func (m AllSubscriptions) Validate(formats strfmt.Registry) error { + var res []error + + for i := 0; i < len(m); i++ { + if swag.IsZero(m[i]) { // not required + continue + } + + if m[i] != nil { + if err := m[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName(strconv.Itoa(i)) + } + return err + } + } + + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/appmgr_model/all_xapps.go b/pkg/appmgr_model/all_xapps.go new file mode 100644 index 0000000..f3125d6 --- /dev/null +++ b/pkg/appmgr_model/all_xapps.go @@ -0,0 +1,45 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package appmgr_model + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "strconv" + + strfmt "github.com/go-openapi/strfmt" + + "github.com/go-openapi/errors" + "github.com/go-openapi/swag" +) + +// AllXapps all xapps +// swagger:model AllXapps +type AllXapps []*Xapp + +// Validate validates this all xapps +func (m AllXapps) Validate(formats strfmt.Registry) error { + var res []error + + for i := 0; i < len(m); i++ { + if swag.IsZero(m[i]) { // not required + continue + } + + if m[i] != nil { + if err := m[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName(strconv.Itoa(i)) + } + return err + } + } + + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/appmgr_model/subscription.go b/pkg/appmgr_model/subscription.go new file mode 100644 index 0000000..e17db47 --- /dev/null +++ b/pkg/appmgr_model/subscription.go @@ -0,0 +1,118 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package appmgr_model + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + + strfmt "github.com/go-openapi/strfmt" + + "github.com/go-openapi/errors" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// Subscription subscription +// swagger:model subscription +type Subscription struct { + + // Event which is subscribed + // Enum: [created deleted updated all] + EventType string `json:"eventType,omitempty"` + + // id + ID string `json:"id,omitempty"` + + // Maximum number of retries + MaxRetries int64 `json:"maxRetries,omitempty"` + + // Time in seconds to wait before next retry + RetryTimer int64 `json:"retryTimer,omitempty"` + + // target Url + TargetURL string `json:"targetUrl,omitempty"` +} + +// Validate validates this subscription +func (m *Subscription) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateEventType(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +var subscriptionTypeEventTypePropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["created","deleted","updated","all"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + subscriptionTypeEventTypePropEnum = append(subscriptionTypeEventTypePropEnum, v) + } +} + +const ( + + // SubscriptionEventTypeCreated captures enum value "created" + SubscriptionEventTypeCreated string = "created" + + // SubscriptionEventTypeDeleted captures enum value "deleted" + SubscriptionEventTypeDeleted string = "deleted" + + // SubscriptionEventTypeUpdated captures enum value "updated" + SubscriptionEventTypeUpdated string = "updated" + + // SubscriptionEventTypeAll captures enum value "all" + SubscriptionEventTypeAll string = "all" +) + +// prop value enum +func (m *Subscription) validateEventTypeEnum(path, location string, value string) error { + if err := validate.Enum(path, location, value, subscriptionTypeEventTypePropEnum); err != nil { + return err + } + return nil +} + +func (m *Subscription) validateEventType(formats strfmt.Registry) error { + + if swag.IsZero(m.EventType) { // not required + return nil + } + + // value enum + if err := m.validateEventTypeEnum("eventType", "body", m.EventType); err != nil { + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *Subscription) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Subscription) UnmarshalBinary(b []byte) error { + var res Subscription + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/appmgr_model/subscription_notification.go b/pkg/appmgr_model/subscription_notification.go new file mode 100644 index 0000000..4dc053c --- /dev/null +++ b/pkg/appmgr_model/subscription_notification.go @@ -0,0 +1,132 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package appmgr_model + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + + strfmt "github.com/go-openapi/strfmt" + + "github.com/go-openapi/errors" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// SubscriptionNotification subscription notification +// swagger:model subscriptionNotification +type SubscriptionNotification struct { + + // Event to be notified + // Enum: [created deleted updated] + EventType string `json:"eventType,omitempty"` + + // id + ID string `json:"id,omitempty"` + + // version + Version int64 `json:"version,omitempty"` + + // x apps + XApps AllXapps `json:"xApps,omitempty"` +} + +// Validate validates this subscription notification +func (m *SubscriptionNotification) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateEventType(formats); err != nil { + res = append(res, err) + } + + if err := m.validateXApps(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +var subscriptionNotificationTypeEventTypePropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["created","deleted","updated"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + subscriptionNotificationTypeEventTypePropEnum = append(subscriptionNotificationTypeEventTypePropEnum, v) + } +} + +const ( + + // SubscriptionNotificationEventTypeCreated captures enum value "created" + SubscriptionNotificationEventTypeCreated string = "created" + + // SubscriptionNotificationEventTypeDeleted captures enum value "deleted" + SubscriptionNotificationEventTypeDeleted string = "deleted" + + // SubscriptionNotificationEventTypeUpdated captures enum value "updated" + SubscriptionNotificationEventTypeUpdated string = "updated" +) + +// prop value enum +func (m *SubscriptionNotification) validateEventTypeEnum(path, location string, value string) error { + if err := validate.Enum(path, location, value, subscriptionNotificationTypeEventTypePropEnum); err != nil { + return err + } + return nil +} + +func (m *SubscriptionNotification) validateEventType(formats strfmt.Registry) error { + + if swag.IsZero(m.EventType) { // not required + return nil + } + + // value enum + if err := m.validateEventTypeEnum("eventType", "body", m.EventType); err != nil { + return err + } + + return nil +} + +func (m *SubscriptionNotification) validateXApps(formats strfmt.Registry) error { + + if swag.IsZero(m.XApps) { // not required + return nil + } + + if err := m.XApps.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("xApps") + } + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *SubscriptionNotification) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *SubscriptionNotification) UnmarshalBinary(b []byte) error { + var res SubscriptionNotification + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/appmgr_model/subscription_request.go b/pkg/appmgr_model/subscription_request.go new file mode 100644 index 0000000..9d31b5c --- /dev/null +++ b/pkg/appmgr_model/subscription_request.go @@ -0,0 +1,155 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package appmgr_model + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + + strfmt "github.com/go-openapi/strfmt" + + "github.com/go-openapi/errors" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// SubscriptionRequest subscription request +// swagger:model subscriptionRequest +type SubscriptionRequest struct { + + // Event which is subscribed + // Required: true + // Enum: [created deleted all] + EventType *string `json:"eventType"` + + // Maximum number of retries + // Required: true + MaxRetries *int64 `json:"maxRetries"` + + // Time in seconds to wait before next retry + // Required: true + RetryTimer *int64 `json:"retryTimer"` + + // target Url + // Required: true + TargetURL *string `json:"targetUrl"` +} + +// Validate validates this subscription request +func (m *SubscriptionRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateEventType(formats); err != nil { + res = append(res, err) + } + + if err := m.validateMaxRetries(formats); err != nil { + res = append(res, err) + } + + if err := m.validateRetryTimer(formats); err != nil { + res = append(res, err) + } + + if err := m.validateTargetURL(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +var subscriptionRequestTypeEventTypePropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["created","deleted","all"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + subscriptionRequestTypeEventTypePropEnum = append(subscriptionRequestTypeEventTypePropEnum, v) + } +} + +const ( + + // SubscriptionRequestEventTypeCreated captures enum value "created" + SubscriptionRequestEventTypeCreated string = "created" + + // SubscriptionRequestEventTypeDeleted captures enum value "deleted" + SubscriptionRequestEventTypeDeleted string = "deleted" + + // SubscriptionRequestEventTypeAll captures enum value "all" + SubscriptionRequestEventTypeAll string = "all" +) + +// prop value enum +func (m *SubscriptionRequest) validateEventTypeEnum(path, location string, value string) error { + if err := validate.Enum(path, location, value, subscriptionRequestTypeEventTypePropEnum); err != nil { + return err + } + return nil +} + +func (m *SubscriptionRequest) validateEventType(formats strfmt.Registry) error { + + if err := validate.Required("eventType", "body", m.EventType); err != nil { + return err + } + + // value enum + if err := m.validateEventTypeEnum("eventType", "body", *m.EventType); err != nil { + return err + } + + return nil +} + +func (m *SubscriptionRequest) validateMaxRetries(formats strfmt.Registry) error { + + if err := validate.Required("maxRetries", "body", m.MaxRetries); err != nil { + return err + } + + return nil +} + +func (m *SubscriptionRequest) validateRetryTimer(formats strfmt.Registry) error { + + if err := validate.Required("retryTimer", "body", m.RetryTimer); err != nil { + return err + } + + return nil +} + +func (m *SubscriptionRequest) validateTargetURL(formats strfmt.Registry) error { + + if err := validate.Required("targetUrl", "body", m.TargetURL); err != nil { + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *SubscriptionRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *SubscriptionRequest) UnmarshalBinary(b []byte) error { + var res SubscriptionRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/appmgr_model/subscription_response.go b/pkg/appmgr_model/subscription_response.go new file mode 100644 index 0000000..13d89ee --- /dev/null +++ b/pkg/appmgr_model/subscription_response.go @@ -0,0 +1,112 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package appmgr_model + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + + strfmt "github.com/go-openapi/strfmt" + + "github.com/go-openapi/errors" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// SubscriptionResponse subscription response +// swagger:model subscriptionResponse +type SubscriptionResponse struct { + + // Event which is subscribed + // Enum: [created deleted updated all] + EventType string `json:"eventType,omitempty"` + + // id + ID string `json:"id,omitempty"` + + // version + Version int64 `json:"version,omitempty"` +} + +// Validate validates this subscription response +func (m *SubscriptionResponse) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateEventType(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +var subscriptionResponseTypeEventTypePropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["created","deleted","updated","all"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + subscriptionResponseTypeEventTypePropEnum = append(subscriptionResponseTypeEventTypePropEnum, v) + } +} + +const ( + + // SubscriptionResponseEventTypeCreated captures enum value "created" + SubscriptionResponseEventTypeCreated string = "created" + + // SubscriptionResponseEventTypeDeleted captures enum value "deleted" + SubscriptionResponseEventTypeDeleted string = "deleted" + + // SubscriptionResponseEventTypeUpdated captures enum value "updated" + SubscriptionResponseEventTypeUpdated string = "updated" + + // SubscriptionResponseEventTypeAll captures enum value "all" + SubscriptionResponseEventTypeAll string = "all" +) + +// prop value enum +func (m *SubscriptionResponse) validateEventTypeEnum(path, location string, value string) error { + if err := validate.Enum(path, location, value, subscriptionResponseTypeEventTypePropEnum); err != nil { + return err + } + return nil +} + +func (m *SubscriptionResponse) validateEventType(formats strfmt.Registry) error { + + if swag.IsZero(m.EventType) { // not required + return nil + } + + // value enum + if err := m.validateEventTypeEnum("eventType", "body", m.EventType); err != nil { + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *SubscriptionResponse) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *SubscriptionResponse) UnmarshalBinary(b []byte) error { + var res SubscriptionResponse + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/appmgr_model/xapp.go b/pkg/appmgr_model/xapp.go new file mode 100644 index 0000000..91af3e5 --- /dev/null +++ b/pkg/appmgr_model/xapp.go @@ -0,0 +1,165 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package appmgr_model + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "strconv" + + strfmt "github.com/go-openapi/strfmt" + + "github.com/go-openapi/errors" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// Xapp xapp +// swagger:model Xapp +type Xapp struct { + + // instances + Instances []*XappInstance `json:"instances"` + + // name + // Required: true + Name *string `json:"name"` + + // xapp status in the RIC + // Enum: [unknown deployed deleted superseded failed deleting] + Status string `json:"status,omitempty"` + + // version + Version string `json:"version,omitempty"` +} + +// Validate validates this xapp +func (m *Xapp) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateInstances(formats); err != nil { + res = append(res, err) + } + + if err := m.validateName(formats); err != nil { + res = append(res, err) + } + + if err := m.validateStatus(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *Xapp) validateInstances(formats strfmt.Registry) error { + + if swag.IsZero(m.Instances) { // not required + return nil + } + + for i := 0; i < len(m.Instances); i++ { + if swag.IsZero(m.Instances[i]) { // not required + continue + } + + if m.Instances[i] != nil { + if err := m.Instances[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("instances" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *Xapp) validateName(formats strfmt.Registry) error { + + if err := validate.Required("name", "body", m.Name); err != nil { + return err + } + + return nil +} + +var xappTypeStatusPropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["unknown","deployed","deleted","superseded","failed","deleting"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + xappTypeStatusPropEnum = append(xappTypeStatusPropEnum, v) + } +} + +const ( + + // XappStatusUnknown captures enum value "unknown" + XappStatusUnknown string = "unknown" + + // XappStatusDeployed captures enum value "deployed" + XappStatusDeployed string = "deployed" + + // XappStatusDeleted captures enum value "deleted" + XappStatusDeleted string = "deleted" + + // XappStatusSuperseded captures enum value "superseded" + XappStatusSuperseded string = "superseded" + + // XappStatusFailed captures enum value "failed" + XappStatusFailed string = "failed" + + // XappStatusDeleting captures enum value "deleting" + XappStatusDeleting string = "deleting" +) + +// prop value enum +func (m *Xapp) validateStatusEnum(path, location string, value string) error { + if err := validate.Enum(path, location, value, xappTypeStatusPropEnum); err != nil { + return err + } + return nil +} + +func (m *Xapp) validateStatus(formats strfmt.Registry) error { + + if swag.IsZero(m.Status) { // not required + return nil + } + + // value enum + if err := m.validateStatusEnum("status", "body", m.Status); err != nil { + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *Xapp) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Xapp) UnmarshalBinary(b []byte) error { + var res Xapp + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/appmgr_model/xapp_instance.go b/pkg/appmgr_model/xapp_instance.go new file mode 100644 index 0000000..759999a --- /dev/null +++ b/pkg/appmgr_model/xapp_instance.go @@ -0,0 +1,144 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package appmgr_model + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + + strfmt "github.com/go-openapi/strfmt" + + "github.com/go-openapi/errors" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// XappInstance xapp instance +// swagger:model XappInstance +type XappInstance struct { + + // ip + IP string `json:"ip,omitempty"` + + // name + // Required: true + Name *string `json:"name"` + + // port + Port int64 `json:"port,omitempty"` + + // rx messages + RxMessages []string `json:"rxMessages"` + + // xapp instance status + // Enum: [pending running succeeded failed unknown completed crashLoopBackOff] + Status string `json:"status,omitempty"` + + // tx messages + TxMessages []string `json:"txMessages"` +} + +// Validate validates this xapp instance +func (m *XappInstance) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateName(formats); err != nil { + res = append(res, err) + } + + if err := m.validateStatus(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *XappInstance) validateName(formats strfmt.Registry) error { + + if err := validate.Required("name", "body", m.Name); err != nil { + return err + } + + return nil +} + +var xappInstanceTypeStatusPropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["pending","running","succeeded","failed","unknown","completed","crashLoopBackOff"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + xappInstanceTypeStatusPropEnum = append(xappInstanceTypeStatusPropEnum, v) + } +} + +const ( + + // XappInstanceStatusPending captures enum value "pending" + XappInstanceStatusPending string = "pending" + + // XappInstanceStatusRunning captures enum value "running" + XappInstanceStatusRunning string = "running" + + // XappInstanceStatusSucceeded captures enum value "succeeded" + XappInstanceStatusSucceeded string = "succeeded" + + // XappInstanceStatusFailed captures enum value "failed" + XappInstanceStatusFailed string = "failed" + + // XappInstanceStatusUnknown captures enum value "unknown" + XappInstanceStatusUnknown string = "unknown" + + // XappInstanceStatusCompleted captures enum value "completed" + XappInstanceStatusCompleted string = "completed" + + // XappInstanceStatusCrashLoopBackOff captures enum value "crashLoopBackOff" + XappInstanceStatusCrashLoopBackOff string = "crashLoopBackOff" +) + +// prop value enum +func (m *XappInstance) validateStatusEnum(path, location string, value string) error { + if err := validate.Enum(path, location, value, xappInstanceTypeStatusPropEnum); err != nil { + return err + } + return nil +} + +func (m *XappInstance) validateStatus(formats strfmt.Registry) error { + + if swag.IsZero(m.Status) { // not required + return nil + } + + // value enum + if err := m.validateStatusEnum("status", "body", m.Status); err != nil { + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *XappInstance) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *XappInstance) UnmarshalBinary(b []byte) error { + var res XappInstance + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/glide.lock b/pkg/glide.lock deleted file mode 100644 index 8c2f53c..0000000 --- a/pkg/glide.lock +++ /dev/null @@ -1,52 +0,0 @@ -hash: 8a251805c06cd6f4f20b276425eabe314968e2ad14fb32525fc93c53c2cfe845 -updated: 2019-04-04T20:26:54.485838082Z -imports: -- name: github.com/droundy/goopt - version: 0b8effe182da161d81b011aba271507324ecb7ab -- name: github.com/gorilla/websocket - version: 66b9c49e59c6c48f0ffce28c2d8b8a5678502c6d -- name: github.com/jcelliott/lumber - version: dd349441af25132d146d7095c6693a15431fc9b1 -- name: github.com/Microsoft/go-winio - version: 1a8911d1ed007260465c3bfbbc785ac6915a0bb8 -- name: golang.org/x/sys - version: 81d4e9dc473e5e8c933f2aaeba2a3d81efb9aed2 - subpackages: - - windows -- name: nanomsg.org/go/mangos/v2 - version: 63f66a65137b9a648ac9f7bf0160b4a4d17d7999 - subpackages: - - errors - - internal/core - - protocol - - protocol/bus - - protocol/pair - - protocol/pub - - protocol/pull - - protocol/push - - protocol/rep - - protocol/req - - protocol/respondent - - protocol/star - - protocol/sub - - protocol/surveyor - - protocol/xbus - - protocol/xpair - - protocol/xpub - - protocol/xpull - - protocol/xpush - - protocol/xrep - - protocol/xstar - - transport - - transport/all - - transport/inproc - - transport/ipc - - transport/tcp - - transport/tlstcp - - transport/ws - - transport/wss -testImports: -- name: github.com/smartystreets/goconvey - version: 68dc04aab96ae4326137d6b77330c224063a927e - subpackages: - - convey diff --git a/pkg/models/health_status.go b/pkg/models/health_status.go new file mode 100644 index 0000000..dcf1e6f --- /dev/null +++ b/pkg/models/health_status.go @@ -0,0 +1,133 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// ================================================================================== +// Unless otherwise specified, all software contained herein is licensed +// under the Apache License, Version 2.0 (the "Software License"); +// you may not use this software except in compliance with the Software +// License. You may obtain a copy of the Software License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the Software License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the Software License for the specific language governing permissions +// and limitations under the Software License. +// +// ================================================================================== +// +// Unless otherwise specified, all documentation contained herein is licensed +// under the Creative Commons License, Attribution 4.0 Intl. (the +// "Documentation License"); you may not use this documentation except in +// compliance with the Documentation License. You may obtain a copy of the +// Documentation License at +// +// https://creativecommons.org/licenses/by/4.0/ +// +// Unless required by applicable law or agreed to in writing, documentation +// distributed under the Documentation License is distributed on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +// implied. See the Documentation License for the specific language governing +// permissions and limitations under the Documentation License. +// ================================================================================== +// +// + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + + strfmt "github.com/go-openapi/strfmt" + + "github.com/go-openapi/errors" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// HealthStatus health status +// swagger:model health-status +type HealthStatus struct { + + // status + // Enum: [healthy unhealthy] + Status string `json:"status,omitempty"` +} + +// Validate validates this health status +func (m *HealthStatus) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateStatus(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +var healthStatusTypeStatusPropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["healthy","unhealthy"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + healthStatusTypeStatusPropEnum = append(healthStatusTypeStatusPropEnum, v) + } +} + +const ( + + // HealthStatusStatusHealthy captures enum value "healthy" + HealthStatusStatusHealthy string = "healthy" + + // HealthStatusStatusUnhealthy captures enum value "unhealthy" + HealthStatusStatusUnhealthy string = "unhealthy" +) + +// prop value enum +func (m *HealthStatus) validateStatusEnum(path, location string, value string) error { + if err := validate.Enum(path, location, value, healthStatusTypeStatusPropEnum); err != nil { + return err + } + return nil +} + +func (m *HealthStatus) validateStatus(formats strfmt.Registry) error { + + if swag.IsZero(m.Status) { // not required + return nil + } + + // value enum + if err := m.validateStatusEnum("status", "body", m.Status); err != nil { + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *HealthStatus) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *HealthStatus) UnmarshalBinary(b []byte) error { + var res HealthStatus + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/models/route.go b/pkg/models/route.go new file mode 100644 index 0000000..3b5b05b --- /dev/null +++ b/pkg/models/route.go @@ -0,0 +1,161 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// ================================================================================== +// Unless otherwise specified, all software contained herein is licensed +// under the Apache License, Version 2.0 (the "Software License"); +// you may not use this software except in compliance with the Software +// License. You may obtain a copy of the Software License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the Software License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the Software License for the specific language governing permissions +// and limitations under the Software License. +// +// ================================================================================== +// +// Unless otherwise specified, all documentation contained herein is licensed +// under the Creative Commons License, Attribution 4.0 Intl. (the +// "Documentation License"); you may not use this documentation except in +// compliance with the Documentation License. You may obtain a copy of the +// Documentation License at +// +// https://creativecommons.org/licenses/by/4.0/ +// +// Unless required by applicable law or agreed to in writing, documentation +// distributed under the Documentation License is distributed on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +// implied. See the Documentation License for the specific language governing +// permissions and limitations under the Documentation License. +// ================================================================================== +// +// + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "strconv" + + strfmt "github.com/go-openapi/strfmt" + + "github.com/go-openapi/errors" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// Route route +// swagger:model route +type Route struct { + + // id + // Required: true + ID *int64 `json:"id"` + + // message type + MessageType int64 `json:"message-type,omitempty"` + + // receiver groups + ReceiverGroups []XappGroup `json:"receiver-groups"` + + // senders + Senders []*XappInstance `json:"senders"` +} + +// Validate validates this route +func (m *Route) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateReceiverGroups(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSenders(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *Route) validateID(formats strfmt.Registry) error { + + if err := validate.Required("id", "body", m.ID); err != nil { + return err + } + + return nil +} + +func (m *Route) validateReceiverGroups(formats strfmt.Registry) error { + + if swag.IsZero(m.ReceiverGroups) { // not required + return nil + } + + for i := 0; i < len(m.ReceiverGroups); i++ { + + if err := m.ReceiverGroups[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("receiver-groups" + "." + strconv.Itoa(i)) + } + return err + } + + } + + return nil +} + +func (m *Route) validateSenders(formats strfmt.Registry) error { + + if swag.IsZero(m.Senders) { // not required + return nil + } + + for i := 0; i < len(m.Senders); i++ { + if swag.IsZero(m.Senders[i]) { // not required + continue + } + + if m.Senders[i] != nil { + if err := m.Senders[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("senders" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *Route) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Route) UnmarshalBinary(b []byte) error { + var res Route + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/models/routes.go b/pkg/models/routes.go new file mode 100644 index 0000000..bcc4a51 --- /dev/null +++ b/pkg/models/routes.go @@ -0,0 +1,78 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// ================================================================================== +// Unless otherwise specified, all software contained herein is licensed +// under the Apache License, Version 2.0 (the "Software License"); +// you may not use this software except in compliance with the Software +// License. You may obtain a copy of the Software License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the Software License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the Software License for the specific language governing permissions +// and limitations under the Software License. +// +// ================================================================================== +// +// Unless otherwise specified, all documentation contained herein is licensed +// under the Creative Commons License, Attribution 4.0 Intl. (the +// "Documentation License"); you may not use this documentation except in +// compliance with the Documentation License. You may obtain a copy of the +// Documentation License at +// +// https://creativecommons.org/licenses/by/4.0/ +// +// Unless required by applicable law or agreed to in writing, documentation +// distributed under the Documentation License is distributed on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +// implied. See the Documentation License for the specific language governing +// permissions and limitations under the Documentation License. +// ================================================================================== +// +// + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "strconv" + + strfmt "github.com/go-openapi/strfmt" + + "github.com/go-openapi/errors" + "github.com/go-openapi/swag" +) + +// Routes routes +// swagger:model routes +type Routes []*Route + +// Validate validates this routes +func (m Routes) Validate(formats strfmt.Registry) error { + var res []error + + for i := 0; i < len(m); i++ { + if swag.IsZero(m[i]) { // not required + continue + } + + if m[i] != nil { + if err := m[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName(strconv.Itoa(i)) + } + return err + } + } + + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/models/xapp_callback_data.go b/pkg/models/xapp_callback_data.go new file mode 100644 index 0000000..7a82127 --- /dev/null +++ b/pkg/models/xapp_callback_data.go @@ -0,0 +1,85 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// ================================================================================== +// Unless otherwise specified, all software contained herein is licensed +// under the Apache License, Version 2.0 (the "Software License"); +// you may not use this software except in compliance with the Software +// License. You may obtain a copy of the Software License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the Software License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the Software License for the specific language governing permissions +// and limitations under the Software License. +// +// ================================================================================== +// +// Unless otherwise specified, all documentation contained herein is licensed +// under the Creative Commons License, Attribution 4.0 Intl. (the +// "Documentation License"); you may not use this documentation except in +// compliance with the Documentation License. You may obtain a copy of the +// Documentation License at +// +// https://creativecommons.org/licenses/by/4.0/ +// +// Unless required by applicable law or agreed to in writing, documentation +// distributed under the Documentation License is distributed on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +// implied. See the Documentation License for the specific language governing +// permissions and limitations under the Documentation License. +// ================================================================================== +// +// + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + strfmt "github.com/go-openapi/strfmt" + + "github.com/go-openapi/swag" +) + +// XappCallbackData xapp callback data +// swagger:model xapp-callback-data +type XappCallbackData struct { + + // data + Data string `json:"data,omitempty"` + + // data version + DataVersion int64 `json:"data-version,omitempty"` + + // event + Event string `json:"event,omitempty"` + + // id + ID int64 `json:"id,omitempty"` +} + +// Validate validates this xapp callback data +func (m *XappCallbackData) Validate(formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *XappCallbackData) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *XappCallbackData) UnmarshalBinary(b []byte) error { + var res XappCallbackData + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/models/xapp_group.go b/pkg/models/xapp_group.go new file mode 100644 index 0000000..6ff6289 --- /dev/null +++ b/pkg/models/xapp_group.go @@ -0,0 +1,78 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// ================================================================================== +// Unless otherwise specified, all software contained herein is licensed +// under the Apache License, Version 2.0 (the "Software License"); +// you may not use this software except in compliance with the Software +// License. You may obtain a copy of the Software License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the Software License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the Software License for the specific language governing permissions +// and limitations under the Software License. +// +// ================================================================================== +// +// Unless otherwise specified, all documentation contained herein is licensed +// under the Creative Commons License, Attribution 4.0 Intl. (the +// "Documentation License"); you may not use this documentation except in +// compliance with the Documentation License. You may obtain a copy of the +// Documentation License at +// +// https://creativecommons.org/licenses/by/4.0/ +// +// Unless required by applicable law or agreed to in writing, documentation +// distributed under the Documentation License is distributed on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +// implied. See the Documentation License for the specific language governing +// permissions and limitations under the Documentation License. +// ================================================================================== +// +// + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "strconv" + + strfmt "github.com/go-openapi/strfmt" + + "github.com/go-openapi/errors" + "github.com/go-openapi/swag" +) + +// XappGroup xapp group +// swagger:model xapp-group +type XappGroup []*XappInstance + +// Validate validates this xapp group +func (m XappGroup) Validate(formats strfmt.Registry) error { + var res []error + + for i := 0; i < len(m); i++ { + if swag.IsZero(m[i]) { // not required + continue + } + + if m[i] != nil { + if err := m[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName(strconv.Itoa(i)) + } + return err + } + } + + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/models/xapp_instance.go b/pkg/models/xapp_instance.go new file mode 100644 index 0000000..7740c5f --- /dev/null +++ b/pkg/models/xapp_instance.go @@ -0,0 +1,124 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// ================================================================================== +// Unless otherwise specified, all software contained herein is licensed +// under the Apache License, Version 2.0 (the "Software License"); +// you may not use this software except in compliance with the Software +// License. You may obtain a copy of the Software License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the Software License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the Software License for the specific language governing permissions +// and limitations under the Software License. +// +// ================================================================================== +// +// Unless otherwise specified, all documentation contained herein is licensed +// under the Creative Commons License, Attribution 4.0 Intl. (the +// "Documentation License"); you may not use this documentation except in +// compliance with the Documentation License. You may obtain a copy of the +// Documentation License at +// +// https://creativecommons.org/licenses/by/4.0/ +// +// Unless required by applicable law or agreed to in writing, documentation +// distributed under the Documentation License is distributed on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +// implied. See the Documentation License for the specific language governing +// permissions and limitations under the Documentation License. +// ================================================================================== +// +// + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + strfmt "github.com/go-openapi/strfmt" + + "github.com/go-openapi/errors" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// XappInstance xapp instance +// swagger:model xapp-instance +type XappInstance struct { + + // address + // Required: true + Address *string `json:"address"` + + // port + // Required: true + // Maximum: 65535 + // Minimum: 0 + Port *int32 `json:"port"` +} + +// Validate validates this xapp instance +func (m *XappInstance) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateAddress(formats); err != nil { + res = append(res, err) + } + + if err := m.validatePort(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *XappInstance) validateAddress(formats strfmt.Registry) error { + + if err := validate.Required("address", "body", m.Address); err != nil { + return err + } + + return nil +} + +func (m *XappInstance) validatePort(formats strfmt.Registry) error { + + if err := validate.Required("port", "body", m.Port); err != nil { + return err + } + + if err := validate.MinimumInt("port", "body", int64(*m.Port), 0, false); err != nil { + return err + } + + if err := validate.MaximumInt("port", "body", int64(*m.Port), 65535, false); err != nil { + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *XappInstance) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *XappInstance) UnmarshalBinary(b []byte) error { + var res XappInstance + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/nbi/httpgetter.go b/pkg/nbi/httpgetter.go index 6780403..46ad52e 100644 --- a/pkg/nbi/httpgetter.go +++ b/pkg/nbi/httpgetter.go @@ -28,23 +28,51 @@ package nbi import ( "encoding/json" "net/http" - "rtmgr" + "routing-manager/pkg/rtmgr" + "routing-manager/pkg/sdl" "time" ) +type HttpGetter struct { + NbiEngine + FetchAllXapps FetchAllXappsHandler +} + +func NewHttpGetter() *HttpGetter { + instance := new(HttpGetter) + instance.FetchAllXapps = fetchAllXapps + return instance +} + var myClient = &http.Client{Timeout: 1 * time.Second} -func fetchXappList(url string) (*[]rtmgr.XApp, error) { - rtmgr.Logger.Debug("Invoked httpgetter.fetchXappList") - r, err := myClient.Get(url) +func fetchAllXapps(xmurl string) (*[]rtmgr.XApp, error) { + rtmgr.Logger.Info("Invoked httpgetter.fetchXappList: " + xmurl) + r, err := myClient.Get(xmurl) if err != nil { return nil, err } defer r.Body.Close() - rtmgr.Logger.Debug("http client raw response: %v", r) - var xapps []rtmgr.XApp - json.NewDecoder(r.Body).Decode(&xapps) - rtmgr.Logger.Info("HTTP GET: OK") - rtmgr.Logger.Debug("httpgetter.fetchXappList returns: %v", xapps) - return &xapps, err + + if r.StatusCode == 200 { + rtmgr.Logger.Debug("http client raw response: %v", r) + var xapps []rtmgr.XApp + err = json.NewDecoder(r.Body).Decode(&xapps) + if err != nil { + rtmgr.Logger.Warn("Json decode failed: " + err.Error()) + } + rtmgr.Logger.Info("HTTP GET: OK") + rtmgr.Logger.Debug("httpgetter.fetchXappList returns: %v", xapps) + return &xapps, err + } + rtmgr.Logger.Warn("httpgetter got an unexpected http status code: %v", r.StatusCode) + return nil, nil +} + +func (g *HttpGetter) Initialize(xmurl string, nbiif string, fileName string, sdlEngine sdl.SdlEngine, triggerSBI chan<- bool) error { + return nil +} + +func (g *HttpGetter) Terminate() error { + return nil } diff --git a/pkg/nbi/httpgetter_test.go b/pkg/nbi/httpgetter_test.go new file mode 100644 index 0000000..a6cbbf7 --- /dev/null +++ b/pkg/nbi/httpgetter_test.go @@ -0,0 +1,130 @@ +/* +================================================================================== + Copyright (c) 2019 AT&T Intellectual Property. + Copyright (c) 2019 Nokia + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +================================================================================== +*/ +/* + Mnemonic: httpgetter.go + Abstract: HTTPgetter unit tests + Date: 14 May 2019 +*/ + +package nbi + +import ( + "net" + "net/http" + "net/http/httptest" + "routing-manager/pkg/rtmgr" + "testing" +) + +var ( + XMURL string = "http://127.0.0.1:3000/ric/v1/xapps" +) + + +func TestFetchXappListInvalidData(t *testing.T) { + var httpGetter = NewHttpGetter() + _, err := httpGetter.FetchAllXapps(XMURL) + if err == nil { + t.Error("No XApp data received: "+err.Error()) + } +} + + +func TestFetchXappListWithInvalidData(t *testing.T) { + var expected int = 0 + rtmgr.SetLogLevel("debug") + b := []byte(`{"ID":"deadbeef1234567890", "Version":0, "EventType":"all"}`) + l, err := net.Listen("tcp", "127.0.0.1:3000") + if err != nil { + t.Error("Failed to create listener: " + err.Error()) + } + ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + //t.Log(r.Method) + //t.Log(r.URL) + if r.Method == "GET" && r.URL.String() == "/ric/v1/xapps" { + //t.Log("Sending reply") + w.Header().Add("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + w.Write(b) + } + })) + ts.Listener.Close() + ts.Listener = l + + ts.Start() + defer ts.Close() + var httpGetter = NewHttpGetter() + xapplist, err := httpGetter.FetchAllXapps(XMURL) + if err == nil { + t.Error("Error occured: " + err.Error()) + } else { + //t.Log(len(*xapplist)) + if len(*xapplist) != expected { + t.Error("Invalid XApp data: got " + string(len(*xapplist)) + ", expected " + string(expected)) + } + } +} + +func TestFetchAllXappsWithValidData(t *testing.T) { + var expected int = 1 + b := []byte(`[ + { + "name":"xapp-01","status":"unknown","version":"1.2.3", + "instances":[ + {"name":"xapp-01-instance-01","status":"pending","ip":"172.16.1.103","port":4555, + "txMessages":["ControlIndication"], + "rxMessages":["LoadIndication","Reset"] + }, + {"name":"xapp-01-instance-02","status":"pending","ip":"10.244.1.12","port":4561, + "txMessages":["ControlIndication","SNStatusTransfer"], + "rxMessages":["LoadIndication","HandoverPreparation"] + } + ] +} +]`) + l, err := net.Listen("tcp", "127.0.0.1:3000") + if err != nil { + t.Error("Failed to create listener: " + err.Error()) + } + ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + //t.Log(r.Method) + //t.Log(r.URL) + if r.Method == "GET" && r.URL.String() == "/ric/v1/xapps" { + //t.Log("Sending reply") + w.Header().Add("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + w.Write(b) + } + })) + ts.Listener.Close() + ts.Listener = l + + ts.Start() + defer ts.Close() + var httpGetter = NewHttpGetter() + xapplist, err := httpGetter.FetchAllXapps(XMURL) + if err != nil { + t.Error("Error occured: " + err.Error()) + } else { + if len(*xapplist) != expected { + t.Error("Invalid XApp data: got " + string(len(*xapplist)) + ", expected " + string(expected)) + } + } +} + diff --git a/pkg/nbi/httprestful.go b/pkg/nbi/httprestful.go new file mode 100644 index 0000000..a273a1d --- /dev/null +++ b/pkg/nbi/httprestful.go @@ -0,0 +1,243 @@ +/* +================================================================================== + Copyright (c) 2019 AT&T Intellectual Property. + Copyright (c) 2019 Nokia + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +================================================================================== +*/ +/* + Mnemonic: httprestful.go + Abstract: HTTP Restful API NBI implementation + Based on Swagger generated code + Date: 25 March 2019 +*/ + +package nbi + +import ( + "fmt" + "os" + "time" + "net/url" + "strconv" + "errors" + "encoding/json" + "routing-manager/pkg/rtmgr" + "routing-manager/pkg/sdl" + "routing-manager/pkg/models" + "routing-manager/pkg/restapi" + "routing-manager/pkg/restapi/operations" + "github.com/go-openapi/runtime/middleware" + "routing-manager/pkg/restapi/operations/handle" + loads "github.com/go-openapi/loads" +) + +//var myClient = &http.Client{Timeout: 1 * time.Second} + +type HttpRestful struct { + NbiEngine + LaunchRest LaunchRestHandler + RecvXappCallbackData RecvXappCallbackDataHandler + ProvideXappHandleHandlerImpl ProvideXappHandleHandlerImpl + RetrieveStartupData RetrieveStartupDataHandler +} + +func NewHttpRestful() *HttpRestful { + instance := new(HttpRestful) + instance.LaunchRest = launchRest + instance.RecvXappCallbackData = recvXappCallbackData + instance.ProvideXappHandleHandlerImpl = provideXappHandleHandlerImpl + instance.RetrieveStartupData = retrieveStartupData + return instance +} + +// ToDo: Use Range over channel. Read and return only the latest one. +func recvXappCallbackData(dataChannel <-chan *models.XappCallbackData) (*[]rtmgr.XApp, error) { + var xappData *models.XappCallbackData + // Drain the channel as we are only looking for the latest value until + // xapp manager sends all xapp data with every request. + length := len(dataChannel) + //rtmgr.Logger.Info(length) + for i := 0; i <= length; i++ { + rtmgr.Logger.Info("data received") + // If no data received from the REST, it blocks. + xappData = <-dataChannel + } + if nil != xappData { + var xapps []rtmgr.XApp + err := json.Unmarshal([]byte(xappData.Data), &xapps) + return &xapps, err + } else { + rtmgr.Logger.Info("No data") + } + + rtmgr.Logger.Debug("Nothing received on the Http interface") + return nil, nil + +} + +func validateXappCallbackData(callbackData *models.XappCallbackData) error { + if len(callbackData.Data) == 0 { + return fmt.Errorf("Invalid Data field: \"%s\"", callbackData.Data) + } + var xapps []rtmgr.XApp + err := json.Unmarshal([]byte(callbackData.Data), &xapps) + if err != nil { + return fmt.Errorf("Unmarshal failed: \"%s\"", err.Error()) + } + return nil +} + +func provideXappHandleHandlerImpl(datach chan<- *models.XappCallbackData, data *models.XappCallbackData) error { + if data != nil { + rtmgr.Logger.Debug("Received callback data") + } + err := validateXappCallbackData(data) + if err != nil { + rtmgr.Logger.Debug("XApp callback data validation failed: "+err.Error()) + return err + } else { + datach<-data + return nil + } +} + + +func launchRest(nbiif *string, datach chan<- *models.XappCallbackData) { + swaggerSpec, err := loads.Embedded(restapi.SwaggerJSON, restapi.FlatSwaggerJSON) + if err != nil { + //log.Fatalln(err) + rtmgr.Logger.Error(err.Error()) + os.Exit(1) + } + nbiUrl, err := url.Parse(*nbiif) + if err != nil { + rtmgr.Logger.Error(err.Error()) + os.Exit(1) + } + api := operations.NewRoutingManagerAPI(swaggerSpec) + server := restapi.NewServer(api) + defer server.Shutdown() + + server.Port, err = strconv.Atoi(nbiUrl.Port()) + if err != nil { + rtmgr.Logger.Error("Invalid NBI RestAPI port") + os.Exit(1) + } + server.Host = nbiUrl.Hostname() + // set handlers + api.HandleProvideXappHandleHandler = handle.ProvideXappHandleHandlerFunc( + func(params handle.ProvideXappHandleParams) middleware.Responder { + rtmgr.Logger.Info("Data received on Http interface") + err := provideXappHandleHandlerImpl(datach, params.XappCallbackData) + if err != nil { + rtmgr.Logger.Error("Invalid XApp callback data: "+err.Error()) + return handle.NewProvideXappHandleBadRequest() + } else { + return handle.NewGetHandlesOK() + } + }) + // start to serve API + rtmgr.Logger.Info("Starting the HTTP Rest service") + if err := server.Serve(); err != nil { + rtmgr.Logger.Error(err.Error()) + } +} + +func httpGetXapps(xmurl string) (*[]rtmgr.XApp, error) { + rtmgr.Logger.Info("Invoked httpgetter.fetchXappList: " + xmurl) + r, err := myClient.Get(xmurl) + if err != nil { + return nil, err + } + defer r.Body.Close() + + if r.StatusCode == 200 { + rtmgr.Logger.Debug("http client raw response: %v", r) + var xapps []rtmgr.XApp + err = json.NewDecoder(r.Body).Decode(&xapps) + if err != nil { + rtmgr.Logger.Warn("Json decode failed: " + err.Error()) + } + rtmgr.Logger.Info("HTTP GET: OK") + rtmgr.Logger.Debug("httpgetter.fetchXappList returns: %v", xapps) + return &xapps, err + } + rtmgr.Logger.Warn("httpgetter got an unexpected http status code: %v", r.StatusCode) + return nil, nil +} + +func retrieveStartupData(xmurl string, nbiif string, fileName string, sdlEngine sdl.SdlEngine) error { + var readErr error + var maxRetries = 10 + + for i := 1; i <= maxRetries; i++ { + time.Sleep(2 * time.Second) + + data, err := httpGetXapps(xmurl) + + if data != nil && err == nil { + rtmgr.Logger.Info("Recieved intial xapp data, writing into SDL.") + writeErr := sdlEngine.WriteAll(fileName, data) + if writeErr != nil { + rtmgr.Logger.Error(writeErr.Error()) + } + // post subscription req to appmgr + readErr = PostSubReq(xmurl, nbiif) + if readErr == nil { + return nil + } + } else if err == nil { + readErr = errors.New("Unexpected HTTP status code") + } else { + rtmgr.Logger.Warn("cannot get xapp data due to: " + err.Error()) + readErr = err + } + } + return readErr +} + +func (r *HttpRestful) Initialize(xmurl string, nbiif string, fileName string, sdlEngine sdl.SdlEngine, triggerSBI chan<- bool) error { + err := r.RetrieveStartupData(xmurl, nbiif, fileName, sdlEngine) + if err != nil { + rtmgr.Logger.Error("Exiting as nbi failed to get the intial startup data from the xapp manager: " + err.Error()) + return err + } + + datach := make(chan *models.XappCallbackData, 10) + + rtmgr.Logger.Info("Launching Rest Http service") + go func() { + r.LaunchRest(&nbiif, datach) + }() + + go func() { + for { + data, err := r.RecvXappCallbackData(datach) + if err != nil { + rtmgr.Logger.Error("cannot get data from rest api dute to: " + err.Error()) + } else if data != nil { + sdlEngine.WriteAll(fileName, data) + triggerSBI <- true + } + } + }() + + return nil +} + +func (r *HttpRestful) Terminate() error { + return nil +} + diff --git a/pkg/nbi/httprestful_test.go b/pkg/nbi/httprestful_test.go new file mode 100644 index 0000000..1137f08 --- /dev/null +++ b/pkg/nbi/httprestful_test.go @@ -0,0 +1,219 @@ +/* +================================================================================== + Copyright (c) 2019 AT&T Intellectual Property. + Copyright (c) 2019 Nokia + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +================================================================================== +*/ +/* + Mnemonic: httprestful_test.go + Abstract: HTTPRestful unit tests + Date: 15 May 2019 +*/ + +package nbi + +import ( + "routing-manager/pkg/models" + "routing-manager/pkg/sdl" + "github.com/go-openapi/swag" + "testing" + "time" + "net" + "net/http" + "net/http/httptest" + "fmt" + "os" +) + +var BASIC_XAPPLIST = []byte(`[ + { + "name":"xapp-01","status":"unknown","version":"1.2.3", + "instances":[ + {"name":"xapp-01-instance-01","status":"pending","ip":"172.16.1.103","port":4555, + "txMessages":["ControlIndication"], + "rxMessages":["LoadIndication","Reset"] + }, + {"name":"xapp-01-instance-02","status":"pending","ip":"10.244.1.12","port":4561, + "txMessages":["ControlIndication","SNStatusTransfer"], + "rxMessages":["LoadIndication","HandoverPreparation"] + } + ] +} +]`) + +var SUBSCRIPTION_RESP = []byte(`{"ID":"deadbeef1234567890", "Version":0, "EventType":"all"}`) + + +var INVALID_SUB_RESP = []byte(`{"Version":0, "EventType":all}`) + + +func createMockAppmgrWithData(url string, g []byte, p []byte) *httptest.Server { + l, err := net.Listen("tcp", url) + if err != nil { + fmt.Println("Failed to create listener: " + err.Error()) + } + ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == "GET" && r.URL.String() == "/ric/v1/xapps" { + w.Header().Add("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + w.Write(g) + } + if r.Method == "POST" && r.URL.String() == "/ric/v1/subscriptions" { + w.Header().Add("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + w.Write(p) + } + + })) + ts.Listener.Close() + ts.Listener = l + return ts +} + +func TestRecvXappCallbackData(t *testing.T) { + data := models.XappCallbackData { + Data: *swag.String("[]"), + DataVersion: *swag.Int64(1), + Event: *swag.String("any"), + ID: *swag.Int64(123456), + } + + ch := make(chan *models.XappCallbackData) + defer close(ch) + httpRestful := NewHttpRestful() + go func() {ch<- &data}() + time.Sleep(1 * time.Second) + t.Log(string(len(ch))) + xappList, err := httpRestful.RecvXappCallbackData(ch) + if err != nil { + t.Error("Receive failed: "+err.Error()) + } else { + if xappList == nil { + t.Error("Expected an XApp notification list") + } else { + t.Log("whatever") + } + } +} + +func TestProvideXappHandleHandlerImpl(t *testing.T) { + datach := make(chan *models.XappCallbackData, 10) + defer close(datach) + data := models.XappCallbackData{ + Data: *swag.String("[]"), + DataVersion: *swag.Int64(1), + Event: *swag.String("someevent"), + ID: *swag.Int64(123456)} + var httpRestful, _ = GetNbi("httpRESTful") + err := httpRestful.(*HttpRestful).ProvideXappHandleHandlerImpl(datach, &data) + if err != nil { + t.Error("Error occured: "+err.Error()) + } else { + recv := <-datach + if recv == nil { + t.Error("Something gone wrong: "+err.Error()) + } else { + if recv != &data { + t.Error("Malformed data on channel") + } + } + } +} + +func TestValidateXappCallbackData(t *testing.T) { + data := models.XappCallbackData{ + Data: *swag.String("[]"), + DataVersion: *swag.Int64(1), + Event: *swag.String("someevent"), + ID: *swag.Int64(123456)} + + err := validateXappCallbackData(&data) + if err != nil { + t.Error("Invalid XApp callback data: "+err.Error()) + } +} + +func TestValidateXappCallbackDataWithInvalidData(t *testing.T) { + data := models.XappCallbackData{ + Data: *swag.String("{}"), + DataVersion: *swag.Int64(1), + Event: *swag.String("someevent"), + ID: *swag.Int64(123456)} + + err := validateXappCallbackData(&data) + if err == nil { + t.Error("Invalid XApp callback data: "+err.Error()) + } +} + + +func TestHttpGetXappsInvalidData(t *testing.T) { + _, err := httpGetXapps(XMURL) + if err == nil { + t.Error("No XApp data received: "+err.Error()) + } +} + +func TestHttpGetXappsWithValidData(t *testing.T) { + var expected int = 1 + ts := createMockAppmgrWithData("127.0.0.1:3000", BASIC_XAPPLIST, nil) + + ts.Start() + defer ts.Close() + xapplist, err := httpGetXapps(XMURL) + if err != nil { + t.Error("Error occured: " + err.Error()) + } else { + if len(*xapplist) != expected { + t.Error("Invalid XApp data: got " + string(len(*xapplist)) + ", expected " + string(expected)) + } + } +} + +func TestRetrieveStartupDataTimeout(t *testing.T) { + sdlEngine, _ := sdl.GetSdl("file") + err := retrieveStartupData(XMURL, "httpgetter","rt.json", sdlEngine) + if err == nil { + t.Error("Cannot retrieve startup data: "+err.Error()) + } + os.Remove("rt.json") +} + +func TestRetrieveStartupData(t *testing.T) { + ts := createMockAppmgrWithData("127.0.0.1:3000", BASIC_XAPPLIST, SUBSCRIPTION_RESP) + ts.Start() + defer ts.Close() + sdlEngine, _ := sdl.GetSdl("file") + var httpRestful, _ = GetNbi("httpRESTful") + err := httpRestful.(*HttpRestful).RetrieveStartupData(XMURL, "httpgetter", "rt.json", sdlEngine) + err = retrieveStartupData(XMURL, "httpgetter", "rt.json", sdlEngine) + if err != nil { + t.Error("Cannot retrieve startup data: "+err.Error()) + } + os.Remove("rt.json") +} + +func TestRetrieveStartupDataWithInvalidSubResp(t *testing.T) { + ts := createMockAppmgrWithData("127.0.0.1:3000", BASIC_XAPPLIST, INVALID_SUB_RESP) + ts.Start() + defer ts.Close() + sdlEngine, _ := sdl.GetSdl("file") + var httpRestful, _ = GetNbi("httpRESTful") + err := httpRestful.(*HttpRestful).RetrieveStartupData(XMURL, "httpgetter", "rt.json", sdlEngine) + if err == nil { + t.Error("Cannot retrieve startup data: "+err.Error()) + } + os.Remove("rt.json") +} diff --git a/pkg/nbi/nbi.go b/pkg/nbi/nbi.go index 84282bd..bb0f485 100644 --- a/pkg/nbi/nbi.go +++ b/pkg/nbi/nbi.go @@ -26,56 +26,87 @@ package nbi import ( "errors" - "fmt" - "rtmgr" + "routing-manager/pkg/rtmgr" + "net/url" + apiclient "routing-manager/pkg/appmgr_client" + "routing-manager/pkg/appmgr_client/operations" + "routing-manager/pkg/appmgr_model" + httptransport "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "time" + ) var ( SupportedNbis = []*NbiEngineConfig{ &NbiEngineConfig{ - NbiEngine{ - Name: "httpGetter", - Version: "v1", - Protocol: "http", - }, - batchFetch(fetchXappList), - true, - }, - &NbiEngineConfig{ - NbiEngine{ - Name: "httpRESTful", - Version: "v1", - Protocol: "http", - }, - batchFetch(nil), - false, + Name: "httpGetter", + Version: "v1", + Protocol: "http", + Instance: NewHttpGetter(), + IsAvailable: true, }, &NbiEngineConfig{ - NbiEngine{ - Name: "gRPC", - Version: "v1", - Protocol: "http2", - }, - batchFetch(nil), - false, + Name: "httpRESTful", + Version: "v1", + Protocol: "http", + Instance: NewHttpRestful(), + IsAvailable: true, }, } ) -func ListNbis() { - fmt.Printf("NBI:\n") - for _, nbi := range SupportedNbis { - if nbi.IsAvailable { - rtmgr.Logger.Info(nbi.Engine.Name + "/" + nbi.Engine.Version) - } - } +type Nbi struct { + } -func GetNbi(nbiName string) (*NbiEngineConfig, error) { +func GetNbi(nbiName string) (NbiEngine, error) { for _, nbi := range SupportedNbis { - if nbi.Engine.Name == nbiName && nbi.IsAvailable { - return nbi, nil + if nbi.Name == nbiName && nbi.IsAvailable { + return nbi.Instance, nil } } return nil, errors.New("NBI:" + nbiName + " is not supported or still not a available") } + +func CreateSubReq(restUrl string, restPort string) *appmgr_model.SubscriptionRequest { + // TODO: parametize function + subReq := appmgr_model.SubscriptionRequest{ + TargetURL: swag.String(restUrl + ":" + restPort + "/ric/v1/handles/xapp-handle/"), + EventType: swag.String("all"), + MaxRetries: swag.Int64(5), + RetryTimer: swag.Int64(10), + } + + return &subReq +} + +func PostSubReq(xmUrl string, nbiif string) error { + // setting up POST request to Xapp Manager + appmgrUrl, err := url.Parse(xmUrl) + if err != nil { + rtmgr.Logger.Error("Invalid XApp manager url/hostname: " + err.Error()) + return err + } + nbiifUrl, err := url.Parse(nbiif) + if err != nil { + rtmgr.Logger.Error("Invalid NBI address/port: " + err.Error()) + return err + } + transport := httptransport.New(appmgrUrl.Hostname()+":"+appmgrUrl.Port(), "/ric/v1", []string{"http"}) + client := apiclient.New(transport, strfmt.Default) + addSubParams := operations.NewAddSubscriptionParamsWithTimeout(10 * time.Second) + // create sub req with rest url and port + subReq := CreateSubReq(nbiifUrl.Hostname(), nbiifUrl.Port()) + resp, postErr := client.Operations.AddSubscription(addSubParams.WithSubscriptionRequest(subReq)) + if postErr != nil { + rtmgr.Logger.Error("POST unsuccessful:"+postErr.Error()) + return postErr + } else { + // TODO: use the received ID + rtmgr.Logger.Info("POST received: "+string(resp.Payload.ID)) + return nil + } +} + diff --git a/pkg/nbi/nbi_test.go b/pkg/nbi/nbi_test.go new file mode 100644 index 0000000..85b95ed --- /dev/null +++ b/pkg/nbi/nbi_test.go @@ -0,0 +1,124 @@ +/* +================================================================================== + Copyright (c) 2019 AT&T Intellectual Property. + Copyright (c) 2019 Nokia + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +================================================================================== +*/ +/* + Mnemonic: nbi_test.go + Abstract: NBI unit tests + Date: 21 May 2019 +*/ + +package nbi + +import ( + "testing" + "reflect" + "errors" + "routing-manager/pkg/appmgr_model" + "github.com/go-openapi/swag" + "net" + "net/http" + "net/http/httptest" +) + +func TestGetNbi(t *testing.T) { + var errtype = errors.New("") + var nbitype = new(HttpGetter) + var invalids = []string{"httpgetter", ""} + + nbii, err := GetNbi("httpGetter") + if err != nil { + t.Errorf("GetNbi(HttpGetter) was incorrect, got: %v, want: %v.", reflect.TypeOf(err), nil) + } + if reflect.TypeOf(nbii) != reflect.TypeOf(nbitype) { + t.Errorf("GetNbi(HttpGetter) was incorrect, got: %v, want: %v.", reflect.TypeOf(nbii), reflect.TypeOf(nbitype)) + } + + for _, arg := range invalids { + _, err := GetNbi(arg) + if err == nil { + t.Errorf("GetNbi("+arg+") was incorrect, got: %v, want: %v.", reflect.TypeOf(err), reflect.TypeOf(errtype)) + } + } +} + +func TestCreateSubReq(t *testing.T) { + var subReq = appmgr_model.SubscriptionRequest{ + TargetURL: swag.String("localhost:8000/ric/v1/handles/xapp-handle/"), + EventType: swag.String("all"), + MaxRetries: swag.Int64(5), + RetryTimer: swag.Int64(10), + } + subReq2 := CreateSubReq("localhost","8000") + if reflect.TypeOf(subReq) != reflect.TypeOf(*subReq2) { + t.Errorf("Invalid type, got: %v, want: %v.", reflect.TypeOf(subReq), reflect.TypeOf(*subReq2)) + } + if *(subReq.TargetURL) != *(subReq2.TargetURL) { + t.Errorf("Invalid TargetURL generated, got %v, want %v", *subReq.TargetURL, *subReq2.TargetURL) + } + if *(subReq.EventType) != *(subReq2.EventType) { + t.Errorf("Invalid EventType generated, got %v, want %v", *subReq.EventType, *subReq2.EventType) + } + if *(subReq.MaxRetries) != *(subReq2.MaxRetries) { + t.Errorf("Invalid MaxRetries generated, got %v, want %v", *subReq.MaxRetries, *subReq2.MaxRetries) + } + if *(subReq.RetryTimer) != *(subReq2.RetryTimer) { + t.Errorf("Invalid RetryTimer generated, got %v, want %v", *subReq.RetryTimer, *subReq2.RetryTimer) + } +} + +func TestPostSubReq(t *testing.T) { + b := []byte(`{"ID":"deadbeef1234567890", "Version":0, "EventType":"all"}`) + l, err := net.Listen("tcp", "127.0.0.1:3000") + if err != nil { + t.Error("Failed to create listener: " + err.Error()) + } + ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + t.Log(r.Method) + t.Log(r.URL) + if r.Method == "POST" && r.URL.String() == "/ric/v1/subscriptions" { + t.Log("Sending reply") + w.Header().Add("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + w.Write(b) + } + })) + ts.Listener.Close() + ts.Listener = l + + ts.Start() + defer ts.Close() + //subReq := CreateSubReq("localhost","8888") + err = PostSubReq("http://127.0.0.1:3000/","http://localhost:8888") + if err != nil { + t.Error("Error occured: "+err.Error()) + } +} + +func TestPostSubReqWithInvalidUrls(t *testing.T) { + // invalid Xapp Manager URL + err := PostSubReq("http://127.0","http://localhost:8888") + if err == nil { + t.Error("Error occured: "+err.Error()) + } + // invalid rest api url + err = PostSubReq("http://127.0.0.1:3000/","localhost:8888") + if err == nil { + t.Error("Error occured: "+err.Error()) + } +} + diff --git a/pkg/nbi/types.go b/pkg/nbi/types.go index e02c30d..0f9c07f 100644 --- a/pkg/nbi/types.go +++ b/pkg/nbi/types.go @@ -24,18 +24,28 @@ package nbi -import "rtmgr" - -type batchFetch func(url string) (*[]rtmgr.XApp, error) - -type NbiEngine struct { - Name string - Version string - Protocol string -} +import ( + "routing-manager/pkg/rtmgr" + "routing-manager/pkg/models" + "routing-manager/pkg/sdl" +) + +type FetchAllXappsHandler func(string) (*[]rtmgr.XApp, error) +type RecvXappCallbackDataHandler func(<-chan *models.XappCallbackData) (*[]rtmgr.XApp, error) +type LaunchRestHandler func(*string, chan<- *models.XappCallbackData) +type ProvideXappHandleHandlerImpl func(chan<- *models.XappCallbackData, *models.XappCallbackData) (error) +type RetrieveStartupDataHandler func(string, string, string, sdl.SdlEngine) error type NbiEngineConfig struct { - Engine NbiEngine - BatchFetch batchFetch + Name string + Version string + Protocol string + Instance NbiEngine IsAvailable bool } + +type NbiEngine interface { + Initialize(string, string, string, sdl.SdlEngine, chan<- bool) error + Terminate() error +} + diff --git a/pkg/restapi/configure_routing_manager.go b/pkg/restapi/configure_routing_manager.go new file mode 100644 index 0000000..412f544 --- /dev/null +++ b/pkg/restapi/configure_routing_manager.go @@ -0,0 +1,131 @@ +// This file is safe to edit. Once it exists it will not be overwritten + +// ================================================================================== +// Unless otherwise specified, all software contained herein is licensed +// under the Apache License, Version 2.0 (the "Software License"); +// you may not use this software except in compliance with the Software +// License. You may obtain a copy of the Software License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the Software License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the Software License for the specific language governing permissions +// and limitations under the Software License. +// +// ================================================================================== +// +// Unless otherwise specified, all documentation contained herein is licensed +// under the Creative Commons License, Attribution 4.0 Intl. (the +// "Documentation License"); you may not use this documentation except in +// compliance with the Documentation License. You may obtain a copy of the +// Documentation License at +// +// https://creativecommons.org/licenses/by/4.0/ +// +// Unless required by applicable law or agreed to in writing, documentation +// distributed under the Documentation License is distributed on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +// implied. See the Documentation License for the specific language governing +// permissions and limitations under the Documentation License. +// ================================================================================== +// +// + +package restapi + +import ( + "crypto/tls" + "net/http" + + errors "github.com/go-openapi/errors" + runtime "github.com/go-openapi/runtime" + middleware "github.com/go-openapi/runtime/middleware" + + "routing-manager/pkg/restapi/operations" + "routing-manager/pkg/restapi/operations/handle" + "routing-manager/pkg/restapi/operations/health" + "routing-manager/pkg/restapi/operations/route" + //"fmt" +) + +//go:generate swagger generate server --target ../../pkg --name RoutingManager --spec ../../api/routing_manager.yaml --exclude-main + +func configureFlags(api *operations.RoutingManagerAPI) { + // api.CommandLineOptionsGroups = []swag.CommandLineOptionsGroup{ ... } +} + +func configureAPI(api *operations.RoutingManagerAPI) http.Handler { + // configure the api here + api.ServeError = errors.ServeError + + // Set your custom logger if needed. Default one is log.Printf + // Expected interface func(string, ...interface{}) + // + // Example: + // api.Logger = log.Printf + + api.JSONConsumer = runtime.JSONConsumer() + + api.JSONProducer = runtime.JSONProducer() + + api.RouteAddRouteHandler = route.AddRouteHandlerFunc(func(params route.AddRouteParams) middleware.Responder { + return middleware.NotImplemented("operation route.AddRoute has not yet been implemented") + }) + api.RouteDeleteRouteByIDHandler = route.DeleteRouteByIDHandlerFunc(func(params route.DeleteRouteByIDParams) middleware.Responder { + return middleware.NotImplemented("operation route.DeleteRouteByID has not yet been implemented") + }) + api.HandleGetHandlesHandler = handle.GetHandlesHandlerFunc(func(params handle.GetHandlesParams) middleware.Responder { + return middleware.NotImplemented("operation handle.GetHandles has not yet been implemented") + }) + api.HealthGetHealthHandler = health.GetHealthHandlerFunc(func(params health.GetHealthParams) middleware.Responder { + return middleware.NotImplemented("operation health.GetHealth has not yet been implemented") + }) + api.RouteGetRouteByIDHandler = route.GetRouteByIDHandlerFunc(func(params route.GetRouteByIDParams) middleware.Responder { + return middleware.NotImplemented("operation route.GetRouteByID has not yet been implemented") + }) + api.RouteGetRoutesHandler = route.GetRoutesHandlerFunc(func(params route.GetRoutesParams) middleware.Responder { + return middleware.NotImplemented("operation route.GetRoutes has not yet been implemented") + }) + api.HandleProvideXappHandleHandler = handle.ProvideXappHandleHandlerFunc(func(params handle.ProvideXappHandleParams) middleware.Responder { + //fmt.Println(params.XappCallbackData.Data) + //return middleware.NewGetHandlesOK() + //return handle.NewGetHandlesOK() + return middleware.NotImplemented("operation handle.ProvideXappHandle has not yet been implemented") + }) + api.RouteUpdateRouteByIDHandler = route.UpdateRouteByIDHandlerFunc(func(params route.UpdateRouteByIDParams) middleware.Responder { + return middleware.NotImplemented("operation route.UpdateRouteByID has not yet been implemented") + }) + api.RouteUpdateRouteHandler = route.UpdateRouteHandlerFunc(func(params route.UpdateRouteParams) middleware.Responder { + return middleware.NotImplemented("operation route.UpdateRoute has not yet been implemented") + }) + + api.ServerShutdown = func() {} + + return setupGlobalMiddleware(api.Serve(setupMiddlewares)) +} + +// The TLS configuration before HTTPS server starts. +func configureTLS(tlsConfig *tls.Config) { + // Make all necessary changes to the TLS configuration here. +} + +// As soon as server is initialized but not run yet, this function will be called. +// If you need to modify a config, store server instance to stop it individually later, this is the place. +// This function can be called multiple times, depending on the number of serving schemes. +// scheme value will be set accordingly: "http", "https" or "unix" +func configureServer(s *http.Server, scheme, addr string) { +} + +// The middleware configuration is for the handler executors. These do not apply to the swagger.json document. +// The middleware executes after routing but before authentication, binding and validation +func setupMiddlewares(handler http.Handler) http.Handler { + return handler +} + +// The middleware configuration happens before anything, this middleware also applies to serving the swagger.json document. +// So this is a good place to plug in a panic handling middleware, logging and metrics +func setupGlobalMiddleware(handler http.Handler) http.Handler { + return handler +} diff --git a/pkg/restapi/doc.go b/pkg/restapi/doc.go new file mode 100644 index 0000000..97a92d2 --- /dev/null +++ b/pkg/restapi/doc.go @@ -0,0 +1,56 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// ================================================================================== +// Unless otherwise specified, all software contained herein is licensed +// under the Apache License, Version 2.0 (the "Software License"); +// you may not use this software except in compliance with the Software +// License. You may obtain a copy of the Software License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the Software License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the Software License for the specific language governing permissions +// and limitations under the Software License. +// +// ================================================================================== +// +// Unless otherwise specified, all documentation contained herein is licensed +// under the Creative Commons License, Attribution 4.0 Intl. (the +// "Documentation License"); you may not use this documentation except in +// compliance with the Documentation License. You may obtain a copy of the +// Documentation License at +// +// https://creativecommons.org/licenses/by/4.0/ +// +// Unless required by applicable law or agreed to in writing, documentation +// distributed under the Documentation License is distributed on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +// implied. See the Documentation License for the specific language governing +// permissions and limitations under the Documentation License. +// ================================================================================== +// +// + +/* +Package restapi Routing Manager +This is the Swagger/OpenAPI 2.0 definition of Routing Manager's Northbound API. + + + Schemes: + http + Host: rtmgr + BasePath: /v1 + Version: 0.2.2 + License: Apache 2.0 http://www.apache.org/licenses/LICENSE-2.0.html + + Consumes: + - application/json + + Produces: + - application/json + +swagger:meta +*/ +package restapi diff --git a/pkg/restapi/embedded_spec.go b/pkg/restapi/embedded_spec.go new file mode 100644 index 0000000..249bed5 --- /dev/null +++ b/pkg/restapi/embedded_spec.go @@ -0,0 +1,872 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// ================================================================================== +// Unless otherwise specified, all software contained herein is licensed +// under the Apache License, Version 2.0 (the "Software License"); +// you may not use this software except in compliance with the Software +// License. You may obtain a copy of the Software License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the Software License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the Software License for the specific language governing permissions +// and limitations under the Software License. +// +// ================================================================================== +// +// Unless otherwise specified, all documentation contained herein is licensed +// under the Creative Commons License, Attribution 4.0 Intl. (the +// "Documentation License"); you may not use this documentation except in +// compliance with the Documentation License. You may obtain a copy of the +// Documentation License at +// +// https://creativecommons.org/licenses/by/4.0/ +// +// Unless required by applicable law or agreed to in writing, documentation +// distributed under the Documentation License is distributed on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +// implied. See the Documentation License for the specific language governing +// permissions and limitations under the Documentation License. +// ================================================================================== +// +// + +package restapi + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" +) + +var ( + // SwaggerJSON embedded version of the swagger document used at generation time + SwaggerJSON json.RawMessage + // FlatSwaggerJSON embedded flattened version of the swagger document used at generation time + FlatSwaggerJSON json.RawMessage +) + +func init() { + SwaggerJSON = json.RawMessage([]byte(`{ + "schemes": [ + "http" + ], + "swagger": "2.0", + "info": { + "description": "This is the Swagger/OpenAPI 2.0 definition of Routing Manager's Northbound API.", + "title": "Routing Manager", + "license": { + "name": "Apache 2.0", + "url": "http://www.apache.org/licenses/LICENSE-2.0.html" + }, + "version": "0.2.2" + }, + "host": "rtmgr", + "basePath": "/v1", + "paths": { + "/handles": { + "get": { + "description": "Placeholder for further usage.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "handle" + ], + "summary": "Placeholder for further usage", + "operationId": "get_handles", + "responses": { + "200": { + "description": "Dummy response" + } + } + } + }, + "/handles/xapp-handle": { + "post": { + "description": "By performing a POST method on the xapp-handle resource, the API caller is able to perform a callback on Routing Manager.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "handle" + ], + "summary": "Provide callback", + "operationId": "provide_xapp_handle", + "parameters": [ + { + "description": "xApp related callback data", + "name": "xapp-callback-data", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/xapp-callback-data" + } + } + ], + "responses": { + "201": { + "description": "Callback received" + }, + "400": { + "description": "Invalid data" + } + } + } + }, + "/health": { + "get": { + "description": "By performing a GET method on the health resource, the API caller is able to retrieve the health of Routing Manager", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "health" + ], + "summary": "Retrive the health of Routing Manager", + "operationId": "get_health", + "responses": { + "200": { + "description": "The health of the system", + "schema": { + "$ref": "#/definitions/health-status" + } + } + } + } + }, + "/routes": { + "get": { + "description": "By performing a GET method on the routes resource, the API caller is able to retrieve all routes", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "route" + ], + "summary": "Retrieve the list of routes", + "operationId": "get_routes", + "responses": { + "200": { + "description": "All the routes", + "schema": { + "$ref": "#/definitions/routes" + } + } + } + }, + "put": { + "description": "By performing a PUT method on the routes resource, the API caller is able to update an already existing route.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "route" + ], + "summary": "Update an existing route", + "operationId": "update_route", + "parameters": [ + { + "description": "Route object that needs to be updated or created", + "name": "route", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/route" + } + } + ], + "responses": { + "204": { + "description": "Route updated" + }, + "400": { + "description": "Invalid route ID supplied" + }, + "404": { + "description": "Route not found" + } + } + }, + "post": { + "description": "By performing a POST method on the routes resource, the API caller is able to create a new route.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "route" + ], + "summary": "Add new route", + "operationId": "add_route", + "parameters": [ + { + "description": "Route object that needs to be created", + "name": "route", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/route" + } + } + ], + "responses": { + "201": { + "description": "Route created" + }, + "400": { + "description": "Invalid route" + } + } + } + }, + "/routes/{route-id}": { + "get": { + "description": "Returns a single route", + "produces": [ + "application/json" + ], + "tags": [ + "route" + ], + "summary": "Find route by ID", + "operationId": "get_route_by_id", + "parameters": [ + { + "type": "integer", + "format": "int64", + "description": "ID of route to return", + "name": "route-id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "$ref": "#/definitions/route" + } + }, + "400": { + "description": "Invalid route ID supplied" + }, + "404": { + "description": "Route not found" + } + } + }, + "put": { + "description": "By performing a PUT method on a specific route referenced by the route-id the API caller is able to update that specific route", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "route" + ], + "summary": "Updates a route by explicitly referencing it by route-id", + "operationId": "update-route-by-id", + "parameters": [ + { + "type": "integer", + "format": "int64", + "description": "ID of route that needs to be updated", + "name": "route-id", + "in": "path", + "required": true + }, + { + "description": "The updated route instance", + "name": "route", + "in": "body", + "schema": { + "$ref": "#/definitions/route" + } + } + ], + "responses": { + "204": { + "description": "Route updated" + }, + "400": { + "description": "Invalid route ID supplied" + } + } + }, + "delete": { + "description": "By performing a DELETE method on a specific route referenced by the route-id, the API caller is able to delete that specific route", + "produces": [ + "application/json" + ], + "tags": [ + "route" + ], + "summary": "Deletes a route", + "operationId": "delete_route_by_id", + "parameters": [ + { + "type": "integer", + "format": "int64", + "description": "ID of the route that needs to be deleted", + "name": "route-id", + "in": "path", + "required": true + } + ], + "responses": { + "204": { + "description": "Route deleted" + }, + "400": { + "description": "Invalid route ID supplied" + }, + "404": { + "description": "Route not found" + } + } + } + } + }, + "definitions": { + "health-status": { + "type": "object", + "properties": { + "status": { + "type": "string", + "enum": [ + "healthy", + "unhealthy" + ] + } + } + }, + "route": { + "type": "object", + "required": [ + "id" + ], + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "message-type": { + "type": "integer", + "format": "int64" + }, + "receiver-groups": { + "type": "array", + "items": { + "$ref": "#/definitions/xapp-group" + } + }, + "senders": { + "type": "array", + "items": { + "$ref": "#/definitions/xapp-instance" + } + } + } + }, + "routes": { + "type": "array", + "items": { + "$ref": "#/definitions/route" + } + }, + "xapp-callback-data": { + "type": "object", + "properties": { + "data": { + "type": "string" + }, + "data-version": { + "type": "integer", + "format": "int64" + }, + "event": { + "type": "string" + }, + "id": { + "type": "integer", + "format": "int64" + } + } + }, + "xapp-group": { + "type": "array", + "items": { + "$ref": "#/definitions/xapp-instance" + } + }, + "xapp-instance": { + "type": "object", + "required": [ + "address", + "port" + ], + "properties": { + "address": { + "type": "string" + }, + "port": { + "type": "integer", + "format": "int32", + "maximum": 65535 + } + } + } + }, + "tags": [ + { + "description": "Available handles", + "name": "handle" + }, + { + "description": "Available routes", + "name": "route" + }, + { + "description": "Health of the system", + "name": "health" + } + ], + "externalDocs": { + "description": "Routing Manager", + "url": "http://placeholder" + } +}`)) + FlatSwaggerJSON = json.RawMessage([]byte(`{ + "schemes": [ + "http" + ], + "swagger": "2.0", + "info": { + "description": "This is the Swagger/OpenAPI 2.0 definition of Routing Manager's Northbound API.", + "title": "Routing Manager", + "license": { + "name": "Apache 2.0", + "url": "http://www.apache.org/licenses/LICENSE-2.0.html" + }, + "version": "0.2.2" + }, + "host": "rtmgr", + "basePath": "/v1", + "paths": { + "/handles": { + "get": { + "description": "Placeholder for further usage.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "handle" + ], + "summary": "Placeholder for further usage", + "operationId": "get_handles", + "responses": { + "200": { + "description": "Dummy response" + } + } + } + }, + "/handles/xapp-handle": { + "post": { + "description": "By performing a POST method on the xapp-handle resource, the API caller is able to perform a callback on Routing Manager.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "handle" + ], + "summary": "Provide callback", + "operationId": "provide_xapp_handle", + "parameters": [ + { + "description": "xApp related callback data", + "name": "xapp-callback-data", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/xapp-callback-data" + } + } + ], + "responses": { + "201": { + "description": "Callback received" + }, + "400": { + "description": "Invalid data" + } + } + } + }, + "/health": { + "get": { + "description": "By performing a GET method on the health resource, the API caller is able to retrieve the health of Routing Manager", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "health" + ], + "summary": "Retrive the health of Routing Manager", + "operationId": "get_health", + "responses": { + "200": { + "description": "The health of the system", + "schema": { + "$ref": "#/definitions/health-status" + } + } + } + } + }, + "/routes": { + "get": { + "description": "By performing a GET method on the routes resource, the API caller is able to retrieve all routes", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "route" + ], + "summary": "Retrieve the list of routes", + "operationId": "get_routes", + "responses": { + "200": { + "description": "All the routes", + "schema": { + "$ref": "#/definitions/routes" + } + } + } + }, + "put": { + "description": "By performing a PUT method on the routes resource, the API caller is able to update an already existing route.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "route" + ], + "summary": "Update an existing route", + "operationId": "update_route", + "parameters": [ + { + "description": "Route object that needs to be updated or created", + "name": "route", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/route" + } + } + ], + "responses": { + "204": { + "description": "Route updated" + }, + "400": { + "description": "Invalid route ID supplied" + }, + "404": { + "description": "Route not found" + } + } + }, + "post": { + "description": "By performing a POST method on the routes resource, the API caller is able to create a new route.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "route" + ], + "summary": "Add new route", + "operationId": "add_route", + "parameters": [ + { + "description": "Route object that needs to be created", + "name": "route", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/route" + } + } + ], + "responses": { + "201": { + "description": "Route created" + }, + "400": { + "description": "Invalid route" + } + } + } + }, + "/routes/{route-id}": { + "get": { + "description": "Returns a single route", + "produces": [ + "application/json" + ], + "tags": [ + "route" + ], + "summary": "Find route by ID", + "operationId": "get_route_by_id", + "parameters": [ + { + "type": "integer", + "format": "int64", + "description": "ID of route to return", + "name": "route-id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "$ref": "#/definitions/route" + } + }, + "400": { + "description": "Invalid route ID supplied" + }, + "404": { + "description": "Route not found" + } + } + }, + "put": { + "description": "By performing a PUT method on a specific route referenced by the route-id the API caller is able to update that specific route", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "route" + ], + "summary": "Updates a route by explicitly referencing it by route-id", + "operationId": "update-route-by-id", + "parameters": [ + { + "type": "integer", + "format": "int64", + "description": "ID of route that needs to be updated", + "name": "route-id", + "in": "path", + "required": true + }, + { + "description": "The updated route instance", + "name": "route", + "in": "body", + "schema": { + "$ref": "#/definitions/route" + } + } + ], + "responses": { + "204": { + "description": "Route updated" + }, + "400": { + "description": "Invalid route ID supplied" + } + } + }, + "delete": { + "description": "By performing a DELETE method on a specific route referenced by the route-id, the API caller is able to delete that specific route", + "produces": [ + "application/json" + ], + "tags": [ + "route" + ], + "summary": "Deletes a route", + "operationId": "delete_route_by_id", + "parameters": [ + { + "type": "integer", + "format": "int64", + "description": "ID of the route that needs to be deleted", + "name": "route-id", + "in": "path", + "required": true + } + ], + "responses": { + "204": { + "description": "Route deleted" + }, + "400": { + "description": "Invalid route ID supplied" + }, + "404": { + "description": "Route not found" + } + } + } + } + }, + "definitions": { + "health-status": { + "type": "object", + "properties": { + "status": { + "type": "string", + "enum": [ + "healthy", + "unhealthy" + ] + } + } + }, + "route": { + "type": "object", + "required": [ + "id" + ], + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "message-type": { + "type": "integer", + "format": "int64" + }, + "receiver-groups": { + "type": "array", + "items": { + "$ref": "#/definitions/xapp-group" + } + }, + "senders": { + "type": "array", + "items": { + "$ref": "#/definitions/xapp-instance" + } + } + } + }, + "routes": { + "type": "array", + "items": { + "$ref": "#/definitions/route" + } + }, + "xapp-callback-data": { + "type": "object", + "properties": { + "data": { + "type": "string" + }, + "data-version": { + "type": "integer", + "format": "int64" + }, + "event": { + "type": "string" + }, + "id": { + "type": "integer", + "format": "int64" + } + } + }, + "xapp-group": { + "type": "array", + "items": { + "$ref": "#/definitions/xapp-instance" + } + }, + "xapp-instance": { + "type": "object", + "required": [ + "address", + "port" + ], + "properties": { + "address": { + "type": "string" + }, + "port": { + "type": "integer", + "format": "int32", + "maximum": 65535, + "minimum": 0 + } + } + } + }, + "tags": [ + { + "description": "Available handles", + "name": "handle" + }, + { + "description": "Available routes", + "name": "route" + }, + { + "description": "Health of the system", + "name": "health" + } + ], + "externalDocs": { + "description": "Routing Manager", + "url": "http://placeholder" + } +}`)) +} diff --git a/pkg/restapi/operations/handle/get_handles.go b/pkg/restapi/operations/handle/get_handles.go new file mode 100644 index 0000000..92a7a9f --- /dev/null +++ b/pkg/restapi/operations/handle/get_handles.go @@ -0,0 +1,93 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// ================================================================================== +// Unless otherwise specified, all software contained herein is licensed +// under the Apache License, Version 2.0 (the "Software License"); +// you may not use this software except in compliance with the Software +// License. You may obtain a copy of the Software License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the Software License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the Software License for the specific language governing permissions +// and limitations under the Software License. +// +// ================================================================================== +// +// Unless otherwise specified, all documentation contained herein is licensed +// under the Creative Commons License, Attribution 4.0 Intl. (the +// "Documentation License"); you may not use this documentation except in +// compliance with the Documentation License. You may obtain a copy of the +// Documentation License at +// +// https://creativecommons.org/licenses/by/4.0/ +// +// Unless required by applicable law or agreed to in writing, documentation +// distributed under the Documentation License is distributed on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +// implied. See the Documentation License for the specific language governing +// permissions and limitations under the Documentation License. +// ================================================================================== +// +// + +package handle + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + middleware "github.com/go-openapi/runtime/middleware" +) + +// GetHandlesHandlerFunc turns a function with the right signature into a get handles handler +type GetHandlesHandlerFunc func(GetHandlesParams) middleware.Responder + +// Handle executing the request and returning a response +func (fn GetHandlesHandlerFunc) Handle(params GetHandlesParams) middleware.Responder { + return fn(params) +} + +// GetHandlesHandler interface for that can handle valid get handles params +type GetHandlesHandler interface { + Handle(GetHandlesParams) middleware.Responder +} + +// NewGetHandles creates a new http.Handler for the get handles operation +func NewGetHandles(ctx *middleware.Context, handler GetHandlesHandler) *GetHandles { + return &GetHandles{Context: ctx, Handler: handler} +} + +/*GetHandles swagger:route GET /handles handle getHandles + +Placeholder for further usage + +Placeholder for further usage. + +*/ +type GetHandles struct { + Context *middleware.Context + Handler GetHandlesHandler +} + +func (o *GetHandles) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewGetHandlesParams() + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/pkg/restapi/operations/handle/get_handles_parameters.go b/pkg/restapi/operations/handle/get_handles_parameters.go new file mode 100644 index 0000000..dd5610d --- /dev/null +++ b/pkg/restapi/operations/handle/get_handles_parameters.go @@ -0,0 +1,78 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// ================================================================================== +// Unless otherwise specified, all software contained herein is licensed +// under the Apache License, Version 2.0 (the "Software License"); +// you may not use this software except in compliance with the Software +// License. You may obtain a copy of the Software License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the Software License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the Software License for the specific language governing permissions +// and limitations under the Software License. +// +// ================================================================================== +// +// Unless otherwise specified, all documentation contained herein is licensed +// under the Creative Commons License, Attribution 4.0 Intl. (the +// "Documentation License"); you may not use this documentation except in +// compliance with the Documentation License. You may obtain a copy of the +// Documentation License at +// +// https://creativecommons.org/licenses/by/4.0/ +// +// Unless required by applicable law or agreed to in writing, documentation +// distributed under the Documentation License is distributed on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +// implied. See the Documentation License for the specific language governing +// permissions and limitations under the Documentation License. +// ================================================================================== +// +// + +package handle + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime/middleware" +) + +// NewGetHandlesParams creates a new GetHandlesParams object +// no default values defined in spec. +func NewGetHandlesParams() GetHandlesParams { + + return GetHandlesParams{} +} + +// GetHandlesParams contains all the bound params for the get handles operation +// typically these are obtained from a http.Request +// +// swagger:parameters get_handles +type GetHandlesParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewGetHandlesParams() beforehand. +func (o *GetHandlesParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/restapi/operations/handle/get_handles_responses.go b/pkg/restapi/operations/handle/get_handles_responses.go new file mode 100644 index 0000000..b828225 --- /dev/null +++ b/pkg/restapi/operations/handle/get_handles_responses.go @@ -0,0 +1,69 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// ================================================================================== +// Unless otherwise specified, all software contained herein is licensed +// under the Apache License, Version 2.0 (the "Software License"); +// you may not use this software except in compliance with the Software +// License. You may obtain a copy of the Software License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the Software License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the Software License for the specific language governing permissions +// and limitations under the Software License. +// +// ================================================================================== +// +// Unless otherwise specified, all documentation contained herein is licensed +// under the Creative Commons License, Attribution 4.0 Intl. (the +// "Documentation License"); you may not use this documentation except in +// compliance with the Documentation License. You may obtain a copy of the +// Documentation License at +// +// https://creativecommons.org/licenses/by/4.0/ +// +// Unless required by applicable law or agreed to in writing, documentation +// distributed under the Documentation License is distributed on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +// implied. See the Documentation License for the specific language governing +// permissions and limitations under the Documentation License. +// ================================================================================== +// +// + +package handle + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" +) + +// GetHandlesOKCode is the HTTP code returned for type GetHandlesOK +const GetHandlesOKCode int = 200 + +/*GetHandlesOK Dummy response + +swagger:response getHandlesOK +*/ +type GetHandlesOK struct { +} + +// NewGetHandlesOK creates GetHandlesOK with default headers values +func NewGetHandlesOK() *GetHandlesOK { + + return &GetHandlesOK{} +} + +// WriteResponse to the client +func (o *GetHandlesOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses + + rw.WriteHeader(200) +} diff --git a/pkg/restapi/operations/handle/get_handles_urlbuilder.go b/pkg/restapi/operations/handle/get_handles_urlbuilder.go new file mode 100644 index 0000000..867ce80 --- /dev/null +++ b/pkg/restapi/operations/handle/get_handles_urlbuilder.go @@ -0,0 +1,120 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// ================================================================================== +// Unless otherwise specified, all software contained herein is licensed +// under the Apache License, Version 2.0 (the "Software License"); +// you may not use this software except in compliance with the Software +// License. You may obtain a copy of the Software License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the Software License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the Software License for the specific language governing permissions +// and limitations under the Software License. +// +// ================================================================================== +// +// Unless otherwise specified, all documentation contained herein is licensed +// under the Creative Commons License, Attribution 4.0 Intl. (the +// "Documentation License"); you may not use this documentation except in +// compliance with the Documentation License. You may obtain a copy of the +// Documentation License at +// +// https://creativecommons.org/licenses/by/4.0/ +// +// Unless required by applicable law or agreed to in writing, documentation +// distributed under the Documentation License is distributed on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +// implied. See the Documentation License for the specific language governing +// permissions and limitations under the Documentation License. +// ================================================================================== +// +// + +package handle + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" +) + +// GetHandlesURL generates an URL for the get handles operation +type GetHandlesURL struct { + _basePath string +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetHandlesURL) WithBasePath(bp string) *GetHandlesURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetHandlesURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *GetHandlesURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/handles" + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/v1" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *GetHandlesURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *GetHandlesURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *GetHandlesURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on GetHandlesURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on GetHandlesURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *GetHandlesURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/pkg/restapi/operations/handle/provide_xapp_handle.go b/pkg/restapi/operations/handle/provide_xapp_handle.go new file mode 100644 index 0000000..ab890e0 --- /dev/null +++ b/pkg/restapi/operations/handle/provide_xapp_handle.go @@ -0,0 +1,93 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// ================================================================================== +// Unless otherwise specified, all software contained herein is licensed +// under the Apache License, Version 2.0 (the "Software License"); +// you may not use this software except in compliance with the Software +// License. You may obtain a copy of the Software License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the Software License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the Software License for the specific language governing permissions +// and limitations under the Software License. +// +// ================================================================================== +// +// Unless otherwise specified, all documentation contained herein is licensed +// under the Creative Commons License, Attribution 4.0 Intl. (the +// "Documentation License"); you may not use this documentation except in +// compliance with the Documentation License. You may obtain a copy of the +// Documentation License at +// +// https://creativecommons.org/licenses/by/4.0/ +// +// Unless required by applicable law or agreed to in writing, documentation +// distributed under the Documentation License is distributed on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +// implied. See the Documentation License for the specific language governing +// permissions and limitations under the Documentation License. +// ================================================================================== +// +// + +package handle + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + middleware "github.com/go-openapi/runtime/middleware" +) + +// ProvideXappHandleHandlerFunc turns a function with the right signature into a provide xapp handle handler +type ProvideXappHandleHandlerFunc func(ProvideXappHandleParams) middleware.Responder + +// Handle executing the request and returning a response +func (fn ProvideXappHandleHandlerFunc) Handle(params ProvideXappHandleParams) middleware.Responder { + return fn(params) +} + +// ProvideXappHandleHandler interface for that can handle valid provide xapp handle params +type ProvideXappHandleHandler interface { + Handle(ProvideXappHandleParams) middleware.Responder +} + +// NewProvideXappHandle creates a new http.Handler for the provide xapp handle operation +func NewProvideXappHandle(ctx *middleware.Context, handler ProvideXappHandleHandler) *ProvideXappHandle { + return &ProvideXappHandle{Context: ctx, Handler: handler} +} + +/*ProvideXappHandle swagger:route POST /handles/xapp-handle handle provideXappHandle + +Provide callback + +By performing a POST method on the xapp-handle resource, the API caller is able to perform a callback on Routing Manager. + +*/ +type ProvideXappHandle struct { + Context *middleware.Context + Handler ProvideXappHandleHandler +} + +func (o *ProvideXappHandle) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewProvideXappHandleParams() + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/pkg/restapi/operations/handle/provide_xapp_handle_parameters.go b/pkg/restapi/operations/handle/provide_xapp_handle_parameters.go new file mode 100644 index 0000000..53c1f2d --- /dev/null +++ b/pkg/restapi/operations/handle/provide_xapp_handle_parameters.go @@ -0,0 +1,110 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// ================================================================================== +// Unless otherwise specified, all software contained herein is licensed +// under the Apache License, Version 2.0 (the "Software License"); +// you may not use this software except in compliance with the Software +// License. You may obtain a copy of the Software License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the Software License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the Software License for the specific language governing permissions +// and limitations under the Software License. +// +// ================================================================================== +// +// Unless otherwise specified, all documentation contained herein is licensed +// under the Creative Commons License, Attribution 4.0 Intl. (the +// "Documentation License"); you may not use this documentation except in +// compliance with the Documentation License. You may obtain a copy of the +// Documentation License at +// +// https://creativecommons.org/licenses/by/4.0/ +// +// Unless required by applicable law or agreed to in writing, documentation +// distributed under the Documentation License is distributed on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +// implied. See the Documentation License for the specific language governing +// permissions and limitations under the Documentation License. +// ================================================================================== +// +// + +package handle + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "io" + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + + models "routing-manager/pkg/models" +) + +// NewProvideXappHandleParams creates a new ProvideXappHandleParams object +// no default values defined in spec. +func NewProvideXappHandleParams() ProvideXappHandleParams { + + return ProvideXappHandleParams{} +} + +// ProvideXappHandleParams contains all the bound params for the provide xapp handle operation +// typically these are obtained from a http.Request +// +// swagger:parameters provide_xapp_handle +type ProvideXappHandleParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*xApp related callback data + Required: true + In: body + */ + XappCallbackData *models.XappCallbackData +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewProvideXappHandleParams() beforehand. +func (o *ProvideXappHandleParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + if runtime.HasBody(r) { + defer r.Body.Close() + var body models.XappCallbackData + if err := route.Consumer.Consume(r.Body, &body); err != nil { + if err == io.EOF { + res = append(res, errors.Required("xappCallbackData", "body")) + } else { + res = append(res, errors.NewParseError("xappCallbackData", "body", "", err)) + } + } else { + // validate body object + if err := body.Validate(route.Formats); err != nil { + res = append(res, err) + } + + if len(res) == 0 { + o.XappCallbackData = &body + } + } + } else { + res = append(res, errors.Required("xappCallbackData", "body")) + } + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/restapi/operations/handle/provide_xapp_handle_responses.go b/pkg/restapi/operations/handle/provide_xapp_handle_responses.go new file mode 100644 index 0000000..3861df4 --- /dev/null +++ b/pkg/restapi/operations/handle/provide_xapp_handle_responses.go @@ -0,0 +1,93 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// ================================================================================== +// Unless otherwise specified, all software contained herein is licensed +// under the Apache License, Version 2.0 (the "Software License"); +// you may not use this software except in compliance with the Software +// License. You may obtain a copy of the Software License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the Software License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the Software License for the specific language governing permissions +// and limitations under the Software License. +// +// ================================================================================== +// +// Unless otherwise specified, all documentation contained herein is licensed +// under the Creative Commons License, Attribution 4.0 Intl. (the +// "Documentation License"); you may not use this documentation except in +// compliance with the Documentation License. You may obtain a copy of the +// Documentation License at +// +// https://creativecommons.org/licenses/by/4.0/ +// +// Unless required by applicable law or agreed to in writing, documentation +// distributed under the Documentation License is distributed on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +// implied. See the Documentation License for the specific language governing +// permissions and limitations under the Documentation License. +// ================================================================================== +// +// + +package handle + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" +) + +// ProvideXappHandleCreatedCode is the HTTP code returned for type ProvideXappHandleCreated +const ProvideXappHandleCreatedCode int = 201 + +/*ProvideXappHandleCreated Callback received + +swagger:response provideXappHandleCreated +*/ +type ProvideXappHandleCreated struct { +} + +// NewProvideXappHandleCreated creates ProvideXappHandleCreated with default headers values +func NewProvideXappHandleCreated() *ProvideXappHandleCreated { + + return &ProvideXappHandleCreated{} +} + +// WriteResponse to the client +func (o *ProvideXappHandleCreated) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses + + rw.WriteHeader(201) +} + +// ProvideXappHandleBadRequestCode is the HTTP code returned for type ProvideXappHandleBadRequest +const ProvideXappHandleBadRequestCode int = 400 + +/*ProvideXappHandleBadRequest Invalid data + +swagger:response provideXappHandleBadRequest +*/ +type ProvideXappHandleBadRequest struct { +} + +// NewProvideXappHandleBadRequest creates ProvideXappHandleBadRequest with default headers values +func NewProvideXappHandleBadRequest() *ProvideXappHandleBadRequest { + + return &ProvideXappHandleBadRequest{} +} + +// WriteResponse to the client +func (o *ProvideXappHandleBadRequest) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses + + rw.WriteHeader(400) +} diff --git a/pkg/restapi/operations/handle/provide_xapp_handle_urlbuilder.go b/pkg/restapi/operations/handle/provide_xapp_handle_urlbuilder.go new file mode 100644 index 0000000..48993d1 --- /dev/null +++ b/pkg/restapi/operations/handle/provide_xapp_handle_urlbuilder.go @@ -0,0 +1,120 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// ================================================================================== +// Unless otherwise specified, all software contained herein is licensed +// under the Apache License, Version 2.0 (the "Software License"); +// you may not use this software except in compliance with the Software +// License. You may obtain a copy of the Software License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the Software License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the Software License for the specific language governing permissions +// and limitations under the Software License. +// +// ================================================================================== +// +// Unless otherwise specified, all documentation contained herein is licensed +// under the Creative Commons License, Attribution 4.0 Intl. (the +// "Documentation License"); you may not use this documentation except in +// compliance with the Documentation License. You may obtain a copy of the +// Documentation License at +// +// https://creativecommons.org/licenses/by/4.0/ +// +// Unless required by applicable law or agreed to in writing, documentation +// distributed under the Documentation License is distributed on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +// implied. See the Documentation License for the specific language governing +// permissions and limitations under the Documentation License. +// ================================================================================== +// +// + +package handle + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" +) + +// ProvideXappHandleURL generates an URL for the provide xapp handle operation +type ProvideXappHandleURL struct { + _basePath string +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ProvideXappHandleURL) WithBasePath(bp string) *ProvideXappHandleURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ProvideXappHandleURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *ProvideXappHandleURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/handles/xapp-handle" + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/v1" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *ProvideXappHandleURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *ProvideXappHandleURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *ProvideXappHandleURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on ProvideXappHandleURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on ProvideXappHandleURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *ProvideXappHandleURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/pkg/restapi/operations/health/get_health.go b/pkg/restapi/operations/health/get_health.go new file mode 100644 index 0000000..e1044c9 --- /dev/null +++ b/pkg/restapi/operations/health/get_health.go @@ -0,0 +1,93 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// ================================================================================== +// Unless otherwise specified, all software contained herein is licensed +// under the Apache License, Version 2.0 (the "Software License"); +// you may not use this software except in compliance with the Software +// License. You may obtain a copy of the Software License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the Software License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the Software License for the specific language governing permissions +// and limitations under the Software License. +// +// ================================================================================== +// +// Unless otherwise specified, all documentation contained herein is licensed +// under the Creative Commons License, Attribution 4.0 Intl. (the +// "Documentation License"); you may not use this documentation except in +// compliance with the Documentation License. You may obtain a copy of the +// Documentation License at +// +// https://creativecommons.org/licenses/by/4.0/ +// +// Unless required by applicable law or agreed to in writing, documentation +// distributed under the Documentation License is distributed on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +// implied. See the Documentation License for the specific language governing +// permissions and limitations under the Documentation License. +// ================================================================================== +// +// + +package health + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + middleware "github.com/go-openapi/runtime/middleware" +) + +// GetHealthHandlerFunc turns a function with the right signature into a get health handler +type GetHealthHandlerFunc func(GetHealthParams) middleware.Responder + +// Handle executing the request and returning a response +func (fn GetHealthHandlerFunc) Handle(params GetHealthParams) middleware.Responder { + return fn(params) +} + +// GetHealthHandler interface for that can handle valid get health params +type GetHealthHandler interface { + Handle(GetHealthParams) middleware.Responder +} + +// NewGetHealth creates a new http.Handler for the get health operation +func NewGetHealth(ctx *middleware.Context, handler GetHealthHandler) *GetHealth { + return &GetHealth{Context: ctx, Handler: handler} +} + +/*GetHealth swagger:route GET /health health getHealth + +Retrive the health of Routing Manager + +By performing a GET method on the health resource, the API caller is able to retrieve the health of Routing Manager + +*/ +type GetHealth struct { + Context *middleware.Context + Handler GetHealthHandler +} + +func (o *GetHealth) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewGetHealthParams() + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/pkg/restapi/operations/health/get_health_parameters.go b/pkg/restapi/operations/health/get_health_parameters.go new file mode 100644 index 0000000..78e212a --- /dev/null +++ b/pkg/restapi/operations/health/get_health_parameters.go @@ -0,0 +1,78 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// ================================================================================== +// Unless otherwise specified, all software contained herein is licensed +// under the Apache License, Version 2.0 (the "Software License"); +// you may not use this software except in compliance with the Software +// License. You may obtain a copy of the Software License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the Software License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the Software License for the specific language governing permissions +// and limitations under the Software License. +// +// ================================================================================== +// +// Unless otherwise specified, all documentation contained herein is licensed +// under the Creative Commons License, Attribution 4.0 Intl. (the +// "Documentation License"); you may not use this documentation except in +// compliance with the Documentation License. You may obtain a copy of the +// Documentation License at +// +// https://creativecommons.org/licenses/by/4.0/ +// +// Unless required by applicable law or agreed to in writing, documentation +// distributed under the Documentation License is distributed on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +// implied. See the Documentation License for the specific language governing +// permissions and limitations under the Documentation License. +// ================================================================================== +// +// + +package health + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime/middleware" +) + +// NewGetHealthParams creates a new GetHealthParams object +// no default values defined in spec. +func NewGetHealthParams() GetHealthParams { + + return GetHealthParams{} +} + +// GetHealthParams contains all the bound params for the get health operation +// typically these are obtained from a http.Request +// +// swagger:parameters get_health +type GetHealthParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewGetHealthParams() beforehand. +func (o *GetHealthParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/restapi/operations/health/get_health_responses.go b/pkg/restapi/operations/health/get_health_responses.go new file mode 100644 index 0000000..32f5b37 --- /dev/null +++ b/pkg/restapi/operations/health/get_health_responses.go @@ -0,0 +1,91 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// ================================================================================== +// Unless otherwise specified, all software contained herein is licensed +// under the Apache License, Version 2.0 (the "Software License"); +// you may not use this software except in compliance with the Software +// License. You may obtain a copy of the Software License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the Software License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the Software License for the specific language governing permissions +// and limitations under the Software License. +// +// ================================================================================== +// +// Unless otherwise specified, all documentation contained herein is licensed +// under the Creative Commons License, Attribution 4.0 Intl. (the +// "Documentation License"); you may not use this documentation except in +// compliance with the Documentation License. You may obtain a copy of the +// Documentation License at +// +// https://creativecommons.org/licenses/by/4.0/ +// +// Unless required by applicable law or agreed to in writing, documentation +// distributed under the Documentation License is distributed on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +// implied. See the Documentation License for the specific language governing +// permissions and limitations under the Documentation License. +// ================================================================================== +// +// + +package health + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + models "routing-manager/pkg/models" +) + +// GetHealthOKCode is the HTTP code returned for type GetHealthOK +const GetHealthOKCode int = 200 + +/*GetHealthOK The health of the system + +swagger:response getHealthOK +*/ +type GetHealthOK struct { + + /* + In: Body + */ + Payload *models.HealthStatus `json:"body,omitempty"` +} + +// NewGetHealthOK creates GetHealthOK with default headers values +func NewGetHealthOK() *GetHealthOK { + + return &GetHealthOK{} +} + +// WithPayload adds the payload to the get health o k response +func (o *GetHealthOK) WithPayload(payload *models.HealthStatus) *GetHealthOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get health o k response +func (o *GetHealthOK) SetPayload(payload *models.HealthStatus) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetHealthOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/pkg/restapi/operations/health/get_health_urlbuilder.go b/pkg/restapi/operations/health/get_health_urlbuilder.go new file mode 100644 index 0000000..d3ee66d --- /dev/null +++ b/pkg/restapi/operations/health/get_health_urlbuilder.go @@ -0,0 +1,120 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// ================================================================================== +// Unless otherwise specified, all software contained herein is licensed +// under the Apache License, Version 2.0 (the "Software License"); +// you may not use this software except in compliance with the Software +// License. You may obtain a copy of the Software License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the Software License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the Software License for the specific language governing permissions +// and limitations under the Software License. +// +// ================================================================================== +// +// Unless otherwise specified, all documentation contained herein is licensed +// under the Creative Commons License, Attribution 4.0 Intl. (the +// "Documentation License"); you may not use this documentation except in +// compliance with the Documentation License. You may obtain a copy of the +// Documentation License at +// +// https://creativecommons.org/licenses/by/4.0/ +// +// Unless required by applicable law or agreed to in writing, documentation +// distributed under the Documentation License is distributed on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +// implied. See the Documentation License for the specific language governing +// permissions and limitations under the Documentation License. +// ================================================================================== +// +// + +package health + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" +) + +// GetHealthURL generates an URL for the get health operation +type GetHealthURL struct { + _basePath string +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetHealthURL) WithBasePath(bp string) *GetHealthURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetHealthURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *GetHealthURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/health" + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/v1" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *GetHealthURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *GetHealthURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *GetHealthURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on GetHealthURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on GetHealthURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *GetHealthURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/pkg/restapi/operations/route/add_route.go b/pkg/restapi/operations/route/add_route.go new file mode 100644 index 0000000..48a303b --- /dev/null +++ b/pkg/restapi/operations/route/add_route.go @@ -0,0 +1,93 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// ================================================================================== +// Unless otherwise specified, all software contained herein is licensed +// under the Apache License, Version 2.0 (the "Software License"); +// you may not use this software except in compliance with the Software +// License. You may obtain a copy of the Software License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the Software License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the Software License for the specific language governing permissions +// and limitations under the Software License. +// +// ================================================================================== +// +// Unless otherwise specified, all documentation contained herein is licensed +// under the Creative Commons License, Attribution 4.0 Intl. (the +// "Documentation License"); you may not use this documentation except in +// compliance with the Documentation License. You may obtain a copy of the +// Documentation License at +// +// https://creativecommons.org/licenses/by/4.0/ +// +// Unless required by applicable law or agreed to in writing, documentation +// distributed under the Documentation License is distributed on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +// implied. See the Documentation License for the specific language governing +// permissions and limitations under the Documentation License. +// ================================================================================== +// +// + +package route + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + middleware "github.com/go-openapi/runtime/middleware" +) + +// AddRouteHandlerFunc turns a function with the right signature into a add route handler +type AddRouteHandlerFunc func(AddRouteParams) middleware.Responder + +// Handle executing the request and returning a response +func (fn AddRouteHandlerFunc) Handle(params AddRouteParams) middleware.Responder { + return fn(params) +} + +// AddRouteHandler interface for that can handle valid add route params +type AddRouteHandler interface { + Handle(AddRouteParams) middleware.Responder +} + +// NewAddRoute creates a new http.Handler for the add route operation +func NewAddRoute(ctx *middleware.Context, handler AddRouteHandler) *AddRoute { + return &AddRoute{Context: ctx, Handler: handler} +} + +/*AddRoute swagger:route POST /routes route addRoute + +Add new route + +By performing a POST method on the routes resource, the API caller is able to create a new route. + +*/ +type AddRoute struct { + Context *middleware.Context + Handler AddRouteHandler +} + +func (o *AddRoute) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewAddRouteParams() + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/pkg/restapi/operations/route/add_route_parameters.go b/pkg/restapi/operations/route/add_route_parameters.go new file mode 100644 index 0000000..8a1c4e2 --- /dev/null +++ b/pkg/restapi/operations/route/add_route_parameters.go @@ -0,0 +1,110 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// ================================================================================== +// Unless otherwise specified, all software contained herein is licensed +// under the Apache License, Version 2.0 (the "Software License"); +// you may not use this software except in compliance with the Software +// License. You may obtain a copy of the Software License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the Software License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the Software License for the specific language governing permissions +// and limitations under the Software License. +// +// ================================================================================== +// +// Unless otherwise specified, all documentation contained herein is licensed +// under the Creative Commons License, Attribution 4.0 Intl. (the +// "Documentation License"); you may not use this documentation except in +// compliance with the Documentation License. You may obtain a copy of the +// Documentation License at +// +// https://creativecommons.org/licenses/by/4.0/ +// +// Unless required by applicable law or agreed to in writing, documentation +// distributed under the Documentation License is distributed on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +// implied. See the Documentation License for the specific language governing +// permissions and limitations under the Documentation License. +// ================================================================================== +// +// + +package route + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "io" + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + + models "routing-manager/pkg/models" +) + +// NewAddRouteParams creates a new AddRouteParams object +// no default values defined in spec. +func NewAddRouteParams() AddRouteParams { + + return AddRouteParams{} +} + +// AddRouteParams contains all the bound params for the add route operation +// typically these are obtained from a http.Request +// +// swagger:parameters add_route +type AddRouteParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Route object that needs to be created + Required: true + In: body + */ + Route *models.Route +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewAddRouteParams() beforehand. +func (o *AddRouteParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + if runtime.HasBody(r) { + defer r.Body.Close() + var body models.Route + if err := route.Consumer.Consume(r.Body, &body); err != nil { + if err == io.EOF { + res = append(res, errors.Required("route", "body")) + } else { + res = append(res, errors.NewParseError("route", "body", "", err)) + } + } else { + // validate body object + if err := body.Validate(route.Formats); err != nil { + res = append(res, err) + } + + if len(res) == 0 { + o.Route = &body + } + } + } else { + res = append(res, errors.Required("route", "body")) + } + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/restapi/operations/route/add_route_responses.go b/pkg/restapi/operations/route/add_route_responses.go new file mode 100644 index 0000000..a387c8a --- /dev/null +++ b/pkg/restapi/operations/route/add_route_responses.go @@ -0,0 +1,93 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// ================================================================================== +// Unless otherwise specified, all software contained herein is licensed +// under the Apache License, Version 2.0 (the "Software License"); +// you may not use this software except in compliance with the Software +// License. You may obtain a copy of the Software License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the Software License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the Software License for the specific language governing permissions +// and limitations under the Software License. +// +// ================================================================================== +// +// Unless otherwise specified, all documentation contained herein is licensed +// under the Creative Commons License, Attribution 4.0 Intl. (the +// "Documentation License"); you may not use this documentation except in +// compliance with the Documentation License. You may obtain a copy of the +// Documentation License at +// +// https://creativecommons.org/licenses/by/4.0/ +// +// Unless required by applicable law or agreed to in writing, documentation +// distributed under the Documentation License is distributed on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +// implied. See the Documentation License for the specific language governing +// permissions and limitations under the Documentation License. +// ================================================================================== +// +// + +package route + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" +) + +// AddRouteCreatedCode is the HTTP code returned for type AddRouteCreated +const AddRouteCreatedCode int = 201 + +/*AddRouteCreated Route created + +swagger:response addRouteCreated +*/ +type AddRouteCreated struct { +} + +// NewAddRouteCreated creates AddRouteCreated with default headers values +func NewAddRouteCreated() *AddRouteCreated { + + return &AddRouteCreated{} +} + +// WriteResponse to the client +func (o *AddRouteCreated) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses + + rw.WriteHeader(201) +} + +// AddRouteBadRequestCode is the HTTP code returned for type AddRouteBadRequest +const AddRouteBadRequestCode int = 400 + +/*AddRouteBadRequest Invalid route + +swagger:response addRouteBadRequest +*/ +type AddRouteBadRequest struct { +} + +// NewAddRouteBadRequest creates AddRouteBadRequest with default headers values +func NewAddRouteBadRequest() *AddRouteBadRequest { + + return &AddRouteBadRequest{} +} + +// WriteResponse to the client +func (o *AddRouteBadRequest) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses + + rw.WriteHeader(400) +} diff --git a/pkg/restapi/operations/route/add_route_urlbuilder.go b/pkg/restapi/operations/route/add_route_urlbuilder.go new file mode 100644 index 0000000..937dd73 --- /dev/null +++ b/pkg/restapi/operations/route/add_route_urlbuilder.go @@ -0,0 +1,120 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// ================================================================================== +// Unless otherwise specified, all software contained herein is licensed +// under the Apache License, Version 2.0 (the "Software License"); +// you may not use this software except in compliance with the Software +// License. You may obtain a copy of the Software License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the Software License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the Software License for the specific language governing permissions +// and limitations under the Software License. +// +// ================================================================================== +// +// Unless otherwise specified, all documentation contained herein is licensed +// under the Creative Commons License, Attribution 4.0 Intl. (the +// "Documentation License"); you may not use this documentation except in +// compliance with the Documentation License. You may obtain a copy of the +// Documentation License at +// +// https://creativecommons.org/licenses/by/4.0/ +// +// Unless required by applicable law or agreed to in writing, documentation +// distributed under the Documentation License is distributed on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +// implied. See the Documentation License for the specific language governing +// permissions and limitations under the Documentation License. +// ================================================================================== +// +// + +package route + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" +) + +// AddRouteURL generates an URL for the add route operation +type AddRouteURL struct { + _basePath string +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *AddRouteURL) WithBasePath(bp string) *AddRouteURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *AddRouteURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *AddRouteURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/routes" + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/v1" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *AddRouteURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *AddRouteURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *AddRouteURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on AddRouteURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on AddRouteURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *AddRouteURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/pkg/restapi/operations/route/delete_route_by_id.go b/pkg/restapi/operations/route/delete_route_by_id.go new file mode 100644 index 0000000..8899b2d --- /dev/null +++ b/pkg/restapi/operations/route/delete_route_by_id.go @@ -0,0 +1,93 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// ================================================================================== +// Unless otherwise specified, all software contained herein is licensed +// under the Apache License, Version 2.0 (the "Software License"); +// you may not use this software except in compliance with the Software +// License. You may obtain a copy of the Software License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the Software License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the Software License for the specific language governing permissions +// and limitations under the Software License. +// +// ================================================================================== +// +// Unless otherwise specified, all documentation contained herein is licensed +// under the Creative Commons License, Attribution 4.0 Intl. (the +// "Documentation License"); you may not use this documentation except in +// compliance with the Documentation License. You may obtain a copy of the +// Documentation License at +// +// https://creativecommons.org/licenses/by/4.0/ +// +// Unless required by applicable law or agreed to in writing, documentation +// distributed under the Documentation License is distributed on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +// implied. See the Documentation License for the specific language governing +// permissions and limitations under the Documentation License. +// ================================================================================== +// +// + +package route + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + middleware "github.com/go-openapi/runtime/middleware" +) + +// DeleteRouteByIDHandlerFunc turns a function with the right signature into a delete route by id handler +type DeleteRouteByIDHandlerFunc func(DeleteRouteByIDParams) middleware.Responder + +// Handle executing the request and returning a response +func (fn DeleteRouteByIDHandlerFunc) Handle(params DeleteRouteByIDParams) middleware.Responder { + return fn(params) +} + +// DeleteRouteByIDHandler interface for that can handle valid delete route by id params +type DeleteRouteByIDHandler interface { + Handle(DeleteRouteByIDParams) middleware.Responder +} + +// NewDeleteRouteByID creates a new http.Handler for the delete route by id operation +func NewDeleteRouteByID(ctx *middleware.Context, handler DeleteRouteByIDHandler) *DeleteRouteByID { + return &DeleteRouteByID{Context: ctx, Handler: handler} +} + +/*DeleteRouteByID swagger:route DELETE /routes/{route-id} route deleteRouteById + +Deletes a route + +By performing a DELETE method on a specific route referenced by the route-id, the API caller is able to delete that specific route + +*/ +type DeleteRouteByID struct { + Context *middleware.Context + Handler DeleteRouteByIDHandler +} + +func (o *DeleteRouteByID) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewDeleteRouteByIDParams() + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/pkg/restapi/operations/route/delete_route_by_id_parameters.go b/pkg/restapi/operations/route/delete_route_by_id_parameters.go new file mode 100644 index 0000000..d40cbab --- /dev/null +++ b/pkg/restapi/operations/route/delete_route_by_id_parameters.go @@ -0,0 +1,111 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// ================================================================================== +// Unless otherwise specified, all software contained herein is licensed +// under the Apache License, Version 2.0 (the "Software License"); +// you may not use this software except in compliance with the Software +// License. You may obtain a copy of the Software License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the Software License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the Software License for the specific language governing permissions +// and limitations under the Software License. +// +// ================================================================================== +// +// Unless otherwise specified, all documentation contained herein is licensed +// under the Creative Commons License, Attribution 4.0 Intl. (the +// "Documentation License"); you may not use this documentation except in +// compliance with the Documentation License. You may obtain a copy of the +// Documentation License at +// +// https://creativecommons.org/licenses/by/4.0/ +// +// Unless required by applicable law or agreed to in writing, documentation +// distributed under the Documentation License is distributed on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +// implied. See the Documentation License for the specific language governing +// permissions and limitations under the Documentation License. +// ================================================================================== +// +// + +package route + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/swag" + + strfmt "github.com/go-openapi/strfmt" +) + +// NewDeleteRouteByIDParams creates a new DeleteRouteByIDParams object +// no default values defined in spec. +func NewDeleteRouteByIDParams() DeleteRouteByIDParams { + + return DeleteRouteByIDParams{} +} + +// DeleteRouteByIDParams contains all the bound params for the delete route by id operation +// typically these are obtained from a http.Request +// +// swagger:parameters delete_route_by_id +type DeleteRouteByIDParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*ID of the route that needs to be deleted + Required: true + In: path + */ + RouteID int64 +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewDeleteRouteByIDParams() beforehand. +func (o *DeleteRouteByIDParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + rRouteID, rhkRouteID, _ := route.Params.GetOK("route-id") + if err := o.bindRouteID(rRouteID, rhkRouteID, route.Formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindRouteID binds and validates parameter RouteID from path. +func (o *DeleteRouteByIDParams) bindRouteID(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: true + // Parameter is provided by construction from the route + + value, err := swag.ConvertInt64(raw) + if err != nil { + return errors.InvalidType("route-id", "path", "int64", raw) + } + o.RouteID = value + + return nil +} diff --git a/pkg/restapi/operations/route/delete_route_by_id_responses.go b/pkg/restapi/operations/route/delete_route_by_id_responses.go new file mode 100644 index 0000000..689b935 --- /dev/null +++ b/pkg/restapi/operations/route/delete_route_by_id_responses.go @@ -0,0 +1,117 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// ================================================================================== +// Unless otherwise specified, all software contained herein is licensed +// under the Apache License, Version 2.0 (the "Software License"); +// you may not use this software except in compliance with the Software +// License. You may obtain a copy of the Software License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the Software License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the Software License for the specific language governing permissions +// and limitations under the Software License. +// +// ================================================================================== +// +// Unless otherwise specified, all documentation contained herein is licensed +// under the Creative Commons License, Attribution 4.0 Intl. (the +// "Documentation License"); you may not use this documentation except in +// compliance with the Documentation License. You may obtain a copy of the +// Documentation License at +// +// https://creativecommons.org/licenses/by/4.0/ +// +// Unless required by applicable law or agreed to in writing, documentation +// distributed under the Documentation License is distributed on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +// implied. See the Documentation License for the specific language governing +// permissions and limitations under the Documentation License. +// ================================================================================== +// +// + +package route + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" +) + +// DeleteRouteByIDNoContentCode is the HTTP code returned for type DeleteRouteByIDNoContent +const DeleteRouteByIDNoContentCode int = 204 + +/*DeleteRouteByIDNoContent Route deleted + +swagger:response deleteRouteByIdNoContent +*/ +type DeleteRouteByIDNoContent struct { +} + +// NewDeleteRouteByIDNoContent creates DeleteRouteByIDNoContent with default headers values +func NewDeleteRouteByIDNoContent() *DeleteRouteByIDNoContent { + + return &DeleteRouteByIDNoContent{} +} + +// WriteResponse to the client +func (o *DeleteRouteByIDNoContent) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses + + rw.WriteHeader(204) +} + +// DeleteRouteByIDBadRequestCode is the HTTP code returned for type DeleteRouteByIDBadRequest +const DeleteRouteByIDBadRequestCode int = 400 + +/*DeleteRouteByIDBadRequest Invalid route ID supplied + +swagger:response deleteRouteByIdBadRequest +*/ +type DeleteRouteByIDBadRequest struct { +} + +// NewDeleteRouteByIDBadRequest creates DeleteRouteByIDBadRequest with default headers values +func NewDeleteRouteByIDBadRequest() *DeleteRouteByIDBadRequest { + + return &DeleteRouteByIDBadRequest{} +} + +// WriteResponse to the client +func (o *DeleteRouteByIDBadRequest) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses + + rw.WriteHeader(400) +} + +// DeleteRouteByIDNotFoundCode is the HTTP code returned for type DeleteRouteByIDNotFound +const DeleteRouteByIDNotFoundCode int = 404 + +/*DeleteRouteByIDNotFound Route not found + +swagger:response deleteRouteByIdNotFound +*/ +type DeleteRouteByIDNotFound struct { +} + +// NewDeleteRouteByIDNotFound creates DeleteRouteByIDNotFound with default headers values +func NewDeleteRouteByIDNotFound() *DeleteRouteByIDNotFound { + + return &DeleteRouteByIDNotFound{} +} + +// WriteResponse to the client +func (o *DeleteRouteByIDNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses + + rw.WriteHeader(404) +} diff --git a/pkg/restapi/operations/route/delete_route_by_id_urlbuilder.go b/pkg/restapi/operations/route/delete_route_by_id_urlbuilder.go new file mode 100644 index 0000000..583157b --- /dev/null +++ b/pkg/restapi/operations/route/delete_route_by_id_urlbuilder.go @@ -0,0 +1,134 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// ================================================================================== +// Unless otherwise specified, all software contained herein is licensed +// under the Apache License, Version 2.0 (the "Software License"); +// you may not use this software except in compliance with the Software +// License. You may obtain a copy of the Software License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the Software License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the Software License for the specific language governing permissions +// and limitations under the Software License. +// +// ================================================================================== +// +// Unless otherwise specified, all documentation contained herein is licensed +// under the Creative Commons License, Attribution 4.0 Intl. (the +// "Documentation License"); you may not use this documentation except in +// compliance with the Documentation License. You may obtain a copy of the +// Documentation License at +// +// https://creativecommons.org/licenses/by/4.0/ +// +// Unless required by applicable law or agreed to in writing, documentation +// distributed under the Documentation License is distributed on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +// implied. See the Documentation License for the specific language governing +// permissions and limitations under the Documentation License. +// ================================================================================== +// +// + +package route + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" + "strings" + + "github.com/go-openapi/swag" +) + +// DeleteRouteByIDURL generates an URL for the delete route by id operation +type DeleteRouteByIDURL struct { + RouteID int64 + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *DeleteRouteByIDURL) WithBasePath(bp string) *DeleteRouteByIDURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *DeleteRouteByIDURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *DeleteRouteByIDURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/routes/{route-id}" + + routeID := swag.FormatInt64(o.RouteID) + if routeID != "" { + _path = strings.Replace(_path, "{route-id}", routeID, -1) + } else { + return nil, errors.New("routeId is required on DeleteRouteByIDURL") + } + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/v1" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *DeleteRouteByIDURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *DeleteRouteByIDURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *DeleteRouteByIDURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on DeleteRouteByIDURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on DeleteRouteByIDURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *DeleteRouteByIDURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/pkg/restapi/operations/route/get_route_by_id.go b/pkg/restapi/operations/route/get_route_by_id.go new file mode 100644 index 0000000..9433f9c --- /dev/null +++ b/pkg/restapi/operations/route/get_route_by_id.go @@ -0,0 +1,93 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// ================================================================================== +// Unless otherwise specified, all software contained herein is licensed +// under the Apache License, Version 2.0 (the "Software License"); +// you may not use this software except in compliance with the Software +// License. You may obtain a copy of the Software License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the Software License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the Software License for the specific language governing permissions +// and limitations under the Software License. +// +// ================================================================================== +// +// Unless otherwise specified, all documentation contained herein is licensed +// under the Creative Commons License, Attribution 4.0 Intl. (the +// "Documentation License"); you may not use this documentation except in +// compliance with the Documentation License. You may obtain a copy of the +// Documentation License at +// +// https://creativecommons.org/licenses/by/4.0/ +// +// Unless required by applicable law or agreed to in writing, documentation +// distributed under the Documentation License is distributed on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +// implied. See the Documentation License for the specific language governing +// permissions and limitations under the Documentation License. +// ================================================================================== +// +// + +package route + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + middleware "github.com/go-openapi/runtime/middleware" +) + +// GetRouteByIDHandlerFunc turns a function with the right signature into a get route by id handler +type GetRouteByIDHandlerFunc func(GetRouteByIDParams) middleware.Responder + +// Handle executing the request and returning a response +func (fn GetRouteByIDHandlerFunc) Handle(params GetRouteByIDParams) middleware.Responder { + return fn(params) +} + +// GetRouteByIDHandler interface for that can handle valid get route by id params +type GetRouteByIDHandler interface { + Handle(GetRouteByIDParams) middleware.Responder +} + +// NewGetRouteByID creates a new http.Handler for the get route by id operation +func NewGetRouteByID(ctx *middleware.Context, handler GetRouteByIDHandler) *GetRouteByID { + return &GetRouteByID{Context: ctx, Handler: handler} +} + +/*GetRouteByID swagger:route GET /routes/{route-id} route getRouteById + +Find route by ID + +Returns a single route + +*/ +type GetRouteByID struct { + Context *middleware.Context + Handler GetRouteByIDHandler +} + +func (o *GetRouteByID) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewGetRouteByIDParams() + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/pkg/restapi/operations/route/get_route_by_id_parameters.go b/pkg/restapi/operations/route/get_route_by_id_parameters.go new file mode 100644 index 0000000..bfab502 --- /dev/null +++ b/pkg/restapi/operations/route/get_route_by_id_parameters.go @@ -0,0 +1,111 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// ================================================================================== +// Unless otherwise specified, all software contained herein is licensed +// under the Apache License, Version 2.0 (the "Software License"); +// you may not use this software except in compliance with the Software +// License. You may obtain a copy of the Software License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the Software License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the Software License for the specific language governing permissions +// and limitations under the Software License. +// +// ================================================================================== +// +// Unless otherwise specified, all documentation contained herein is licensed +// under the Creative Commons License, Attribution 4.0 Intl. (the +// "Documentation License"); you may not use this documentation except in +// compliance with the Documentation License. You may obtain a copy of the +// Documentation License at +// +// https://creativecommons.org/licenses/by/4.0/ +// +// Unless required by applicable law or agreed to in writing, documentation +// distributed under the Documentation License is distributed on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +// implied. See the Documentation License for the specific language governing +// permissions and limitations under the Documentation License. +// ================================================================================== +// +// + +package route + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/swag" + + strfmt "github.com/go-openapi/strfmt" +) + +// NewGetRouteByIDParams creates a new GetRouteByIDParams object +// no default values defined in spec. +func NewGetRouteByIDParams() GetRouteByIDParams { + + return GetRouteByIDParams{} +} + +// GetRouteByIDParams contains all the bound params for the get route by id operation +// typically these are obtained from a http.Request +// +// swagger:parameters get_route_by_id +type GetRouteByIDParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*ID of route to return + Required: true + In: path + */ + RouteID int64 +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewGetRouteByIDParams() beforehand. +func (o *GetRouteByIDParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + rRouteID, rhkRouteID, _ := route.Params.GetOK("route-id") + if err := o.bindRouteID(rRouteID, rhkRouteID, route.Formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindRouteID binds and validates parameter RouteID from path. +func (o *GetRouteByIDParams) bindRouteID(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: true + // Parameter is provided by construction from the route + + value, err := swag.ConvertInt64(raw) + if err != nil { + return errors.InvalidType("route-id", "path", "int64", raw) + } + o.RouteID = value + + return nil +} diff --git a/pkg/restapi/operations/route/get_route_by_id_responses.go b/pkg/restapi/operations/route/get_route_by_id_responses.go new file mode 100644 index 0000000..092c19b --- /dev/null +++ b/pkg/restapi/operations/route/get_route_by_id_responses.go @@ -0,0 +1,139 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// ================================================================================== +// Unless otherwise specified, all software contained herein is licensed +// under the Apache License, Version 2.0 (the "Software License"); +// you may not use this software except in compliance with the Software +// License. You may obtain a copy of the Software License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the Software License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the Software License for the specific language governing permissions +// and limitations under the Software License. +// +// ================================================================================== +// +// Unless otherwise specified, all documentation contained herein is licensed +// under the Creative Commons License, Attribution 4.0 Intl. (the +// "Documentation License"); you may not use this documentation except in +// compliance with the Documentation License. You may obtain a copy of the +// Documentation License at +// +// https://creativecommons.org/licenses/by/4.0/ +// +// Unless required by applicable law or agreed to in writing, documentation +// distributed under the Documentation License is distributed on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +// implied. See the Documentation License for the specific language governing +// permissions and limitations under the Documentation License. +// ================================================================================== +// +// + +package route + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + models "routing-manager/pkg/models" +) + +// GetRouteByIDOKCode is the HTTP code returned for type GetRouteByIDOK +const GetRouteByIDOKCode int = 200 + +/*GetRouteByIDOK successful operation + +swagger:response getRouteByIdOK +*/ +type GetRouteByIDOK struct { + + /* + In: Body + */ + Payload *models.Route `json:"body,omitempty"` +} + +// NewGetRouteByIDOK creates GetRouteByIDOK with default headers values +func NewGetRouteByIDOK() *GetRouteByIDOK { + + return &GetRouteByIDOK{} +} + +// WithPayload adds the payload to the get route by Id o k response +func (o *GetRouteByIDOK) WithPayload(payload *models.Route) *GetRouteByIDOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get route by Id o k response +func (o *GetRouteByIDOK) SetPayload(payload *models.Route) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetRouteByIDOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// GetRouteByIDBadRequestCode is the HTTP code returned for type GetRouteByIDBadRequest +const GetRouteByIDBadRequestCode int = 400 + +/*GetRouteByIDBadRequest Invalid route ID supplied + +swagger:response getRouteByIdBadRequest +*/ +type GetRouteByIDBadRequest struct { +} + +// NewGetRouteByIDBadRequest creates GetRouteByIDBadRequest with default headers values +func NewGetRouteByIDBadRequest() *GetRouteByIDBadRequest { + + return &GetRouteByIDBadRequest{} +} + +// WriteResponse to the client +func (o *GetRouteByIDBadRequest) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses + + rw.WriteHeader(400) +} + +// GetRouteByIDNotFoundCode is the HTTP code returned for type GetRouteByIDNotFound +const GetRouteByIDNotFoundCode int = 404 + +/*GetRouteByIDNotFound Route not found + +swagger:response getRouteByIdNotFound +*/ +type GetRouteByIDNotFound struct { +} + +// NewGetRouteByIDNotFound creates GetRouteByIDNotFound with default headers values +func NewGetRouteByIDNotFound() *GetRouteByIDNotFound { + + return &GetRouteByIDNotFound{} +} + +// WriteResponse to the client +func (o *GetRouteByIDNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses + + rw.WriteHeader(404) +} diff --git a/pkg/restapi/operations/route/get_route_by_id_urlbuilder.go b/pkg/restapi/operations/route/get_route_by_id_urlbuilder.go new file mode 100644 index 0000000..f670389 --- /dev/null +++ b/pkg/restapi/operations/route/get_route_by_id_urlbuilder.go @@ -0,0 +1,134 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// ================================================================================== +// Unless otherwise specified, all software contained herein is licensed +// under the Apache License, Version 2.0 (the "Software License"); +// you may not use this software except in compliance with the Software +// License. You may obtain a copy of the Software License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the Software License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the Software License for the specific language governing permissions +// and limitations under the Software License. +// +// ================================================================================== +// +// Unless otherwise specified, all documentation contained herein is licensed +// under the Creative Commons License, Attribution 4.0 Intl. (the +// "Documentation License"); you may not use this documentation except in +// compliance with the Documentation License. You may obtain a copy of the +// Documentation License at +// +// https://creativecommons.org/licenses/by/4.0/ +// +// Unless required by applicable law or agreed to in writing, documentation +// distributed under the Documentation License is distributed on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +// implied. See the Documentation License for the specific language governing +// permissions and limitations under the Documentation License. +// ================================================================================== +// +// + +package route + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" + "strings" + + "github.com/go-openapi/swag" +) + +// GetRouteByIDURL generates an URL for the get route by id operation +type GetRouteByIDURL struct { + RouteID int64 + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetRouteByIDURL) WithBasePath(bp string) *GetRouteByIDURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetRouteByIDURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *GetRouteByIDURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/routes/{route-id}" + + routeID := swag.FormatInt64(o.RouteID) + if routeID != "" { + _path = strings.Replace(_path, "{route-id}", routeID, -1) + } else { + return nil, errors.New("routeId is required on GetRouteByIDURL") + } + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/v1" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *GetRouteByIDURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *GetRouteByIDURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *GetRouteByIDURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on GetRouteByIDURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on GetRouteByIDURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *GetRouteByIDURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/pkg/restapi/operations/route/get_routes.go b/pkg/restapi/operations/route/get_routes.go new file mode 100644 index 0000000..0d89a2f --- /dev/null +++ b/pkg/restapi/operations/route/get_routes.go @@ -0,0 +1,93 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// ================================================================================== +// Unless otherwise specified, all software contained herein is licensed +// under the Apache License, Version 2.0 (the "Software License"); +// you may not use this software except in compliance with the Software +// License. You may obtain a copy of the Software License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the Software License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the Software License for the specific language governing permissions +// and limitations under the Software License. +// +// ================================================================================== +// +// Unless otherwise specified, all documentation contained herein is licensed +// under the Creative Commons License, Attribution 4.0 Intl. (the +// "Documentation License"); you may not use this documentation except in +// compliance with the Documentation License. You may obtain a copy of the +// Documentation License at +// +// https://creativecommons.org/licenses/by/4.0/ +// +// Unless required by applicable law or agreed to in writing, documentation +// distributed under the Documentation License is distributed on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +// implied. See the Documentation License for the specific language governing +// permissions and limitations under the Documentation License. +// ================================================================================== +// +// + +package route + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + middleware "github.com/go-openapi/runtime/middleware" +) + +// GetRoutesHandlerFunc turns a function with the right signature into a get routes handler +type GetRoutesHandlerFunc func(GetRoutesParams) middleware.Responder + +// Handle executing the request and returning a response +func (fn GetRoutesHandlerFunc) Handle(params GetRoutesParams) middleware.Responder { + return fn(params) +} + +// GetRoutesHandler interface for that can handle valid get routes params +type GetRoutesHandler interface { + Handle(GetRoutesParams) middleware.Responder +} + +// NewGetRoutes creates a new http.Handler for the get routes operation +func NewGetRoutes(ctx *middleware.Context, handler GetRoutesHandler) *GetRoutes { + return &GetRoutes{Context: ctx, Handler: handler} +} + +/*GetRoutes swagger:route GET /routes route getRoutes + +Retrieve the list of routes + +By performing a GET method on the routes resource, the API caller is able to retrieve all routes + +*/ +type GetRoutes struct { + Context *middleware.Context + Handler GetRoutesHandler +} + +func (o *GetRoutes) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewGetRoutesParams() + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/pkg/restapi/operations/route/get_routes_parameters.go b/pkg/restapi/operations/route/get_routes_parameters.go new file mode 100644 index 0000000..2a1ccd2 --- /dev/null +++ b/pkg/restapi/operations/route/get_routes_parameters.go @@ -0,0 +1,78 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// ================================================================================== +// Unless otherwise specified, all software contained herein is licensed +// under the Apache License, Version 2.0 (the "Software License"); +// you may not use this software except in compliance with the Software +// License. You may obtain a copy of the Software License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the Software License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the Software License for the specific language governing permissions +// and limitations under the Software License. +// +// ================================================================================== +// +// Unless otherwise specified, all documentation contained herein is licensed +// under the Creative Commons License, Attribution 4.0 Intl. (the +// "Documentation License"); you may not use this documentation except in +// compliance with the Documentation License. You may obtain a copy of the +// Documentation License at +// +// https://creativecommons.org/licenses/by/4.0/ +// +// Unless required by applicable law or agreed to in writing, documentation +// distributed under the Documentation License is distributed on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +// implied. See the Documentation License for the specific language governing +// permissions and limitations under the Documentation License. +// ================================================================================== +// +// + +package route + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime/middleware" +) + +// NewGetRoutesParams creates a new GetRoutesParams object +// no default values defined in spec. +func NewGetRoutesParams() GetRoutesParams { + + return GetRoutesParams{} +} + +// GetRoutesParams contains all the bound params for the get routes operation +// typically these are obtained from a http.Request +// +// swagger:parameters get_routes +type GetRoutesParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewGetRoutesParams() beforehand. +func (o *GetRoutesParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/restapi/operations/route/get_routes_responses.go b/pkg/restapi/operations/route/get_routes_responses.go new file mode 100644 index 0000000..9b4631c --- /dev/null +++ b/pkg/restapi/operations/route/get_routes_responses.go @@ -0,0 +1,94 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// ================================================================================== +// Unless otherwise specified, all software contained herein is licensed +// under the Apache License, Version 2.0 (the "Software License"); +// you may not use this software except in compliance with the Software +// License. You may obtain a copy of the Software License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the Software License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the Software License for the specific language governing permissions +// and limitations under the Software License. +// +// ================================================================================== +// +// Unless otherwise specified, all documentation contained herein is licensed +// under the Creative Commons License, Attribution 4.0 Intl. (the +// "Documentation License"); you may not use this documentation except in +// compliance with the Documentation License. You may obtain a copy of the +// Documentation License at +// +// https://creativecommons.org/licenses/by/4.0/ +// +// Unless required by applicable law or agreed to in writing, documentation +// distributed under the Documentation License is distributed on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +// implied. See the Documentation License for the specific language governing +// permissions and limitations under the Documentation License. +// ================================================================================== +// +// + +package route + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + models "routing-manager/pkg/models" +) + +// GetRoutesOKCode is the HTTP code returned for type GetRoutesOK +const GetRoutesOKCode int = 200 + +/*GetRoutesOK All the routes + +swagger:response getRoutesOK +*/ +type GetRoutesOK struct { + + /* + In: Body + */ + Payload models.Routes `json:"body,omitempty"` +} + +// NewGetRoutesOK creates GetRoutesOK with default headers values +func NewGetRoutesOK() *GetRoutesOK { + + return &GetRoutesOK{} +} + +// WithPayload adds the payload to the get routes o k response +func (o *GetRoutesOK) WithPayload(payload models.Routes) *GetRoutesOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get routes o k response +func (o *GetRoutesOK) SetPayload(payload models.Routes) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetRoutesOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + payload := o.Payload + if payload == nil { + // return empty array + payload = models.Routes{} + } + + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } +} diff --git a/pkg/restapi/operations/route/get_routes_urlbuilder.go b/pkg/restapi/operations/route/get_routes_urlbuilder.go new file mode 100644 index 0000000..ef819fa --- /dev/null +++ b/pkg/restapi/operations/route/get_routes_urlbuilder.go @@ -0,0 +1,120 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// ================================================================================== +// Unless otherwise specified, all software contained herein is licensed +// under the Apache License, Version 2.0 (the "Software License"); +// you may not use this software except in compliance with the Software +// License. You may obtain a copy of the Software License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the Software License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the Software License for the specific language governing permissions +// and limitations under the Software License. +// +// ================================================================================== +// +// Unless otherwise specified, all documentation contained herein is licensed +// under the Creative Commons License, Attribution 4.0 Intl. (the +// "Documentation License"); you may not use this documentation except in +// compliance with the Documentation License. You may obtain a copy of the +// Documentation License at +// +// https://creativecommons.org/licenses/by/4.0/ +// +// Unless required by applicable law or agreed to in writing, documentation +// distributed under the Documentation License is distributed on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +// implied. See the Documentation License for the specific language governing +// permissions and limitations under the Documentation License. +// ================================================================================== +// +// + +package route + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" +) + +// GetRoutesURL generates an URL for the get routes operation +type GetRoutesURL struct { + _basePath string +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetRoutesURL) WithBasePath(bp string) *GetRoutesURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetRoutesURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *GetRoutesURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/routes" + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/v1" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *GetRoutesURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *GetRoutesURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *GetRoutesURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on GetRoutesURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on GetRoutesURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *GetRoutesURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/pkg/restapi/operations/route/update_route.go b/pkg/restapi/operations/route/update_route.go new file mode 100644 index 0000000..bafd120 --- /dev/null +++ b/pkg/restapi/operations/route/update_route.go @@ -0,0 +1,93 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// ================================================================================== +// Unless otherwise specified, all software contained herein is licensed +// under the Apache License, Version 2.0 (the "Software License"); +// you may not use this software except in compliance with the Software +// License. You may obtain a copy of the Software License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the Software License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the Software License for the specific language governing permissions +// and limitations under the Software License. +// +// ================================================================================== +// +// Unless otherwise specified, all documentation contained herein is licensed +// under the Creative Commons License, Attribution 4.0 Intl. (the +// "Documentation License"); you may not use this documentation except in +// compliance with the Documentation License. You may obtain a copy of the +// Documentation License at +// +// https://creativecommons.org/licenses/by/4.0/ +// +// Unless required by applicable law or agreed to in writing, documentation +// distributed under the Documentation License is distributed on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +// implied. See the Documentation License for the specific language governing +// permissions and limitations under the Documentation License. +// ================================================================================== +// +// + +package route + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + middleware "github.com/go-openapi/runtime/middleware" +) + +// UpdateRouteHandlerFunc turns a function with the right signature into a update route handler +type UpdateRouteHandlerFunc func(UpdateRouteParams) middleware.Responder + +// Handle executing the request and returning a response +func (fn UpdateRouteHandlerFunc) Handle(params UpdateRouteParams) middleware.Responder { + return fn(params) +} + +// UpdateRouteHandler interface for that can handle valid update route params +type UpdateRouteHandler interface { + Handle(UpdateRouteParams) middleware.Responder +} + +// NewUpdateRoute creates a new http.Handler for the update route operation +func NewUpdateRoute(ctx *middleware.Context, handler UpdateRouteHandler) *UpdateRoute { + return &UpdateRoute{Context: ctx, Handler: handler} +} + +/*UpdateRoute swagger:route PUT /routes route updateRoute + +Update an existing route + +By performing a PUT method on the routes resource, the API caller is able to update an already existing route. + +*/ +type UpdateRoute struct { + Context *middleware.Context + Handler UpdateRouteHandler +} + +func (o *UpdateRoute) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewUpdateRouteParams() + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/pkg/restapi/operations/route/update_route_by_id.go b/pkg/restapi/operations/route/update_route_by_id.go new file mode 100644 index 0000000..440b167 --- /dev/null +++ b/pkg/restapi/operations/route/update_route_by_id.go @@ -0,0 +1,93 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// ================================================================================== +// Unless otherwise specified, all software contained herein is licensed +// under the Apache License, Version 2.0 (the "Software License"); +// you may not use this software except in compliance with the Software +// License. You may obtain a copy of the Software License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the Software License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the Software License for the specific language governing permissions +// and limitations under the Software License. +// +// ================================================================================== +// +// Unless otherwise specified, all documentation contained herein is licensed +// under the Creative Commons License, Attribution 4.0 Intl. (the +// "Documentation License"); you may not use this documentation except in +// compliance with the Documentation License. You may obtain a copy of the +// Documentation License at +// +// https://creativecommons.org/licenses/by/4.0/ +// +// Unless required by applicable law or agreed to in writing, documentation +// distributed under the Documentation License is distributed on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +// implied. See the Documentation License for the specific language governing +// permissions and limitations under the Documentation License. +// ================================================================================== +// +// + +package route + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + middleware "github.com/go-openapi/runtime/middleware" +) + +// UpdateRouteByIDHandlerFunc turns a function with the right signature into a update route by id handler +type UpdateRouteByIDHandlerFunc func(UpdateRouteByIDParams) middleware.Responder + +// Handle executing the request and returning a response +func (fn UpdateRouteByIDHandlerFunc) Handle(params UpdateRouteByIDParams) middleware.Responder { + return fn(params) +} + +// UpdateRouteByIDHandler interface for that can handle valid update route by id params +type UpdateRouteByIDHandler interface { + Handle(UpdateRouteByIDParams) middleware.Responder +} + +// NewUpdateRouteByID creates a new http.Handler for the update route by id operation +func NewUpdateRouteByID(ctx *middleware.Context, handler UpdateRouteByIDHandler) *UpdateRouteByID { + return &UpdateRouteByID{Context: ctx, Handler: handler} +} + +/*UpdateRouteByID swagger:route PUT /routes/{route-id} route updateRouteById + +Updates a route by explicitly referencing it by route-id + +By performing a PUT method on a specific route referenced by the route-id the API caller is able to update that specific route + +*/ +type UpdateRouteByID struct { + Context *middleware.Context + Handler UpdateRouteByIDHandler +} + +func (o *UpdateRouteByID) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewUpdateRouteByIDParams() + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/pkg/restapi/operations/route/update_route_by_id_parameters.go b/pkg/restapi/operations/route/update_route_by_id_parameters.go new file mode 100644 index 0000000..a730f41 --- /dev/null +++ b/pkg/restapi/operations/route/update_route_by_id_parameters.go @@ -0,0 +1,134 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// ================================================================================== +// Unless otherwise specified, all software contained herein is licensed +// under the Apache License, Version 2.0 (the "Software License"); +// you may not use this software except in compliance with the Software +// License. You may obtain a copy of the Software License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the Software License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the Software License for the specific language governing permissions +// and limitations under the Software License. +// +// ================================================================================== +// +// Unless otherwise specified, all documentation contained herein is licensed +// under the Creative Commons License, Attribution 4.0 Intl. (the +// "Documentation License"); you may not use this documentation except in +// compliance with the Documentation License. You may obtain a copy of the +// Documentation License at +// +// https://creativecommons.org/licenses/by/4.0/ +// +// Unless required by applicable law or agreed to in writing, documentation +// distributed under the Documentation License is distributed on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +// implied. See the Documentation License for the specific language governing +// permissions and limitations under the Documentation License. +// ================================================================================== +// +// + +package route + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/swag" + + strfmt "github.com/go-openapi/strfmt" + + models "routing-manager/pkg/models" +) + +// NewUpdateRouteByIDParams creates a new UpdateRouteByIDParams object +// no default values defined in spec. +func NewUpdateRouteByIDParams() UpdateRouteByIDParams { + + return UpdateRouteByIDParams{} +} + +// UpdateRouteByIDParams contains all the bound params for the update route by id operation +// typically these are obtained from a http.Request +// +// swagger:parameters update-route-by-id +type UpdateRouteByIDParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*The updated route instance + In: body + */ + Route *models.Route + /*ID of route that needs to be updated + Required: true + In: path + */ + RouteID int64 +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewUpdateRouteByIDParams() beforehand. +func (o *UpdateRouteByIDParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + if runtime.HasBody(r) { + defer r.Body.Close() + var body models.Route + if err := route.Consumer.Consume(r.Body, &body); err != nil { + res = append(res, errors.NewParseError("route", "body", "", err)) + } else { + // validate body object + if err := body.Validate(route.Formats); err != nil { + res = append(res, err) + } + + if len(res) == 0 { + o.Route = &body + } + } + } + rRouteID, rhkRouteID, _ := route.Params.GetOK("route-id") + if err := o.bindRouteID(rRouteID, rhkRouteID, route.Formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindRouteID binds and validates parameter RouteID from path. +func (o *UpdateRouteByIDParams) bindRouteID(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: true + // Parameter is provided by construction from the route + + value, err := swag.ConvertInt64(raw) + if err != nil { + return errors.InvalidType("route-id", "path", "int64", raw) + } + o.RouteID = value + + return nil +} diff --git a/pkg/restapi/operations/route/update_route_by_id_responses.go b/pkg/restapi/operations/route/update_route_by_id_responses.go new file mode 100644 index 0000000..c86c215 --- /dev/null +++ b/pkg/restapi/operations/route/update_route_by_id_responses.go @@ -0,0 +1,93 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// ================================================================================== +// Unless otherwise specified, all software contained herein is licensed +// under the Apache License, Version 2.0 (the "Software License"); +// you may not use this software except in compliance with the Software +// License. You may obtain a copy of the Software License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the Software License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the Software License for the specific language governing permissions +// and limitations under the Software License. +// +// ================================================================================== +// +// Unless otherwise specified, all documentation contained herein is licensed +// under the Creative Commons License, Attribution 4.0 Intl. (the +// "Documentation License"); you may not use this documentation except in +// compliance with the Documentation License. You may obtain a copy of the +// Documentation License at +// +// https://creativecommons.org/licenses/by/4.0/ +// +// Unless required by applicable law or agreed to in writing, documentation +// distributed under the Documentation License is distributed on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +// implied. See the Documentation License for the specific language governing +// permissions and limitations under the Documentation License. +// ================================================================================== +// +// + +package route + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" +) + +// UpdateRouteByIDNoContentCode is the HTTP code returned for type UpdateRouteByIDNoContent +const UpdateRouteByIDNoContentCode int = 204 + +/*UpdateRouteByIDNoContent Route updated + +swagger:response updateRouteByIdNoContent +*/ +type UpdateRouteByIDNoContent struct { +} + +// NewUpdateRouteByIDNoContent creates UpdateRouteByIDNoContent with default headers values +func NewUpdateRouteByIDNoContent() *UpdateRouteByIDNoContent { + + return &UpdateRouteByIDNoContent{} +} + +// WriteResponse to the client +func (o *UpdateRouteByIDNoContent) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses + + rw.WriteHeader(204) +} + +// UpdateRouteByIDBadRequestCode is the HTTP code returned for type UpdateRouteByIDBadRequest +const UpdateRouteByIDBadRequestCode int = 400 + +/*UpdateRouteByIDBadRequest Invalid route ID supplied + +swagger:response updateRouteByIdBadRequest +*/ +type UpdateRouteByIDBadRequest struct { +} + +// NewUpdateRouteByIDBadRequest creates UpdateRouteByIDBadRequest with default headers values +func NewUpdateRouteByIDBadRequest() *UpdateRouteByIDBadRequest { + + return &UpdateRouteByIDBadRequest{} +} + +// WriteResponse to the client +func (o *UpdateRouteByIDBadRequest) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses + + rw.WriteHeader(400) +} diff --git a/pkg/restapi/operations/route/update_route_by_id_urlbuilder.go b/pkg/restapi/operations/route/update_route_by_id_urlbuilder.go new file mode 100644 index 0000000..7b5ba96 --- /dev/null +++ b/pkg/restapi/operations/route/update_route_by_id_urlbuilder.go @@ -0,0 +1,134 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// ================================================================================== +// Unless otherwise specified, all software contained herein is licensed +// under the Apache License, Version 2.0 (the "Software License"); +// you may not use this software except in compliance with the Software +// License. You may obtain a copy of the Software License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the Software License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the Software License for the specific language governing permissions +// and limitations under the Software License. +// +// ================================================================================== +// +// Unless otherwise specified, all documentation contained herein is licensed +// under the Creative Commons License, Attribution 4.0 Intl. (the +// "Documentation License"); you may not use this documentation except in +// compliance with the Documentation License. You may obtain a copy of the +// Documentation License at +// +// https://creativecommons.org/licenses/by/4.0/ +// +// Unless required by applicable law or agreed to in writing, documentation +// distributed under the Documentation License is distributed on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +// implied. See the Documentation License for the specific language governing +// permissions and limitations under the Documentation License. +// ================================================================================== +// +// + +package route + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" + "strings" + + "github.com/go-openapi/swag" +) + +// UpdateRouteByIDURL generates an URL for the update route by id operation +type UpdateRouteByIDURL struct { + RouteID int64 + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *UpdateRouteByIDURL) WithBasePath(bp string) *UpdateRouteByIDURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *UpdateRouteByIDURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *UpdateRouteByIDURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/routes/{route-id}" + + routeID := swag.FormatInt64(o.RouteID) + if routeID != "" { + _path = strings.Replace(_path, "{route-id}", routeID, -1) + } else { + return nil, errors.New("routeId is required on UpdateRouteByIDURL") + } + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/v1" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *UpdateRouteByIDURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *UpdateRouteByIDURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *UpdateRouteByIDURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on UpdateRouteByIDURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on UpdateRouteByIDURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *UpdateRouteByIDURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/pkg/restapi/operations/route/update_route_parameters.go b/pkg/restapi/operations/route/update_route_parameters.go new file mode 100644 index 0000000..8c48d12 --- /dev/null +++ b/pkg/restapi/operations/route/update_route_parameters.go @@ -0,0 +1,110 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// ================================================================================== +// Unless otherwise specified, all software contained herein is licensed +// under the Apache License, Version 2.0 (the "Software License"); +// you may not use this software except in compliance with the Software +// License. You may obtain a copy of the Software License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the Software License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the Software License for the specific language governing permissions +// and limitations under the Software License. +// +// ================================================================================== +// +// Unless otherwise specified, all documentation contained herein is licensed +// under the Creative Commons License, Attribution 4.0 Intl. (the +// "Documentation License"); you may not use this documentation except in +// compliance with the Documentation License. You may obtain a copy of the +// Documentation License at +// +// https://creativecommons.org/licenses/by/4.0/ +// +// Unless required by applicable law or agreed to in writing, documentation +// distributed under the Documentation License is distributed on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +// implied. See the Documentation License for the specific language governing +// permissions and limitations under the Documentation License. +// ================================================================================== +// +// + +package route + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "io" + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + + models "routing-manager/pkg/models" +) + +// NewUpdateRouteParams creates a new UpdateRouteParams object +// no default values defined in spec. +func NewUpdateRouteParams() UpdateRouteParams { + + return UpdateRouteParams{} +} + +// UpdateRouteParams contains all the bound params for the update route operation +// typically these are obtained from a http.Request +// +// swagger:parameters update_route +type UpdateRouteParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Route object that needs to be updated or created + Required: true + In: body + */ + Route *models.Route +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewUpdateRouteParams() beforehand. +func (o *UpdateRouteParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + if runtime.HasBody(r) { + defer r.Body.Close() + var body models.Route + if err := route.Consumer.Consume(r.Body, &body); err != nil { + if err == io.EOF { + res = append(res, errors.Required("route", "body")) + } else { + res = append(res, errors.NewParseError("route", "body", "", err)) + } + } else { + // validate body object + if err := body.Validate(route.Formats); err != nil { + res = append(res, err) + } + + if len(res) == 0 { + o.Route = &body + } + } + } else { + res = append(res, errors.Required("route", "body")) + } + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/restapi/operations/route/update_route_responses.go b/pkg/restapi/operations/route/update_route_responses.go new file mode 100644 index 0000000..d5e560c --- /dev/null +++ b/pkg/restapi/operations/route/update_route_responses.go @@ -0,0 +1,117 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// ================================================================================== +// Unless otherwise specified, all software contained herein is licensed +// under the Apache License, Version 2.0 (the "Software License"); +// you may not use this software except in compliance with the Software +// License. You may obtain a copy of the Software License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the Software License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the Software License for the specific language governing permissions +// and limitations under the Software License. +// +// ================================================================================== +// +// Unless otherwise specified, all documentation contained herein is licensed +// under the Creative Commons License, Attribution 4.0 Intl. (the +// "Documentation License"); you may not use this documentation except in +// compliance with the Documentation License. You may obtain a copy of the +// Documentation License at +// +// https://creativecommons.org/licenses/by/4.0/ +// +// Unless required by applicable law or agreed to in writing, documentation +// distributed under the Documentation License is distributed on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +// implied. See the Documentation License for the specific language governing +// permissions and limitations under the Documentation License. +// ================================================================================== +// +// + +package route + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" +) + +// UpdateRouteNoContentCode is the HTTP code returned for type UpdateRouteNoContent +const UpdateRouteNoContentCode int = 204 + +/*UpdateRouteNoContent Route updated + +swagger:response updateRouteNoContent +*/ +type UpdateRouteNoContent struct { +} + +// NewUpdateRouteNoContent creates UpdateRouteNoContent with default headers values +func NewUpdateRouteNoContent() *UpdateRouteNoContent { + + return &UpdateRouteNoContent{} +} + +// WriteResponse to the client +func (o *UpdateRouteNoContent) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses + + rw.WriteHeader(204) +} + +// UpdateRouteBadRequestCode is the HTTP code returned for type UpdateRouteBadRequest +const UpdateRouteBadRequestCode int = 400 + +/*UpdateRouteBadRequest Invalid route ID supplied + +swagger:response updateRouteBadRequest +*/ +type UpdateRouteBadRequest struct { +} + +// NewUpdateRouteBadRequest creates UpdateRouteBadRequest with default headers values +func NewUpdateRouteBadRequest() *UpdateRouteBadRequest { + + return &UpdateRouteBadRequest{} +} + +// WriteResponse to the client +func (o *UpdateRouteBadRequest) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses + + rw.WriteHeader(400) +} + +// UpdateRouteNotFoundCode is the HTTP code returned for type UpdateRouteNotFound +const UpdateRouteNotFoundCode int = 404 + +/*UpdateRouteNotFound Route not found + +swagger:response updateRouteNotFound +*/ +type UpdateRouteNotFound struct { +} + +// NewUpdateRouteNotFound creates UpdateRouteNotFound with default headers values +func NewUpdateRouteNotFound() *UpdateRouteNotFound { + + return &UpdateRouteNotFound{} +} + +// WriteResponse to the client +func (o *UpdateRouteNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses + + rw.WriteHeader(404) +} diff --git a/pkg/restapi/operations/route/update_route_urlbuilder.go b/pkg/restapi/operations/route/update_route_urlbuilder.go new file mode 100644 index 0000000..26d23a6 --- /dev/null +++ b/pkg/restapi/operations/route/update_route_urlbuilder.go @@ -0,0 +1,120 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// ================================================================================== +// Unless otherwise specified, all software contained herein is licensed +// under the Apache License, Version 2.0 (the "Software License"); +// you may not use this software except in compliance with the Software +// License. You may obtain a copy of the Software License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the Software License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the Software License for the specific language governing permissions +// and limitations under the Software License. +// +// ================================================================================== +// +// Unless otherwise specified, all documentation contained herein is licensed +// under the Creative Commons License, Attribution 4.0 Intl. (the +// "Documentation License"); you may not use this documentation except in +// compliance with the Documentation License. You may obtain a copy of the +// Documentation License at +// +// https://creativecommons.org/licenses/by/4.0/ +// +// Unless required by applicable law or agreed to in writing, documentation +// distributed under the Documentation License is distributed on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +// implied. See the Documentation License for the specific language governing +// permissions and limitations under the Documentation License. +// ================================================================================== +// +// + +package route + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" +) + +// UpdateRouteURL generates an URL for the update route operation +type UpdateRouteURL struct { + _basePath string +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *UpdateRouteURL) WithBasePath(bp string) *UpdateRouteURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *UpdateRouteURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *UpdateRouteURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/routes" + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/v1" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *UpdateRouteURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *UpdateRouteURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *UpdateRouteURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on UpdateRouteURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on UpdateRouteURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *UpdateRouteURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/pkg/restapi/operations/routing_manager_api.go b/pkg/restapi/operations/routing_manager_api.go new file mode 100644 index 0000000..24fa272 --- /dev/null +++ b/pkg/restapi/operations/routing_manager_api.go @@ -0,0 +1,424 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// ================================================================================== +// Unless otherwise specified, all software contained herein is licensed +// under the Apache License, Version 2.0 (the "Software License"); +// you may not use this software except in compliance with the Software +// License. You may obtain a copy of the Software License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the Software License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the Software License for the specific language governing permissions +// and limitations under the Software License. +// +// ================================================================================== +// +// Unless otherwise specified, all documentation contained herein is licensed +// under the Creative Commons License, Attribution 4.0 Intl. (the +// "Documentation License"); you may not use this documentation except in +// compliance with the Documentation License. You may obtain a copy of the +// Documentation License at +// +// https://creativecommons.org/licenses/by/4.0/ +// +// Unless required by applicable law or agreed to in writing, documentation +// distributed under the Documentation License is distributed on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +// implied. See the Documentation License for the specific language governing +// permissions and limitations under the Documentation License. +// ================================================================================== +// +// + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "net/http" + "strings" + + errors "github.com/go-openapi/errors" + loads "github.com/go-openapi/loads" + runtime "github.com/go-openapi/runtime" + middleware "github.com/go-openapi/runtime/middleware" + security "github.com/go-openapi/runtime/security" + spec "github.com/go-openapi/spec" + strfmt "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + + "routing-manager/pkg/restapi/operations/handle" + "routing-manager/pkg/restapi/operations/health" + "routing-manager/pkg/restapi/operations/route" +) + +// NewRoutingManagerAPI creates a new RoutingManager instance +func NewRoutingManagerAPI(spec *loads.Document) *RoutingManagerAPI { + return &RoutingManagerAPI{ + handlers: make(map[string]map[string]http.Handler), + formats: strfmt.Default, + defaultConsumes: "application/json", + defaultProduces: "application/json", + customConsumers: make(map[string]runtime.Consumer), + customProducers: make(map[string]runtime.Producer), + ServerShutdown: func() {}, + spec: spec, + ServeError: errors.ServeError, + BasicAuthenticator: security.BasicAuth, + APIKeyAuthenticator: security.APIKeyAuth, + BearerAuthenticator: security.BearerAuth, + JSONConsumer: runtime.JSONConsumer(), + JSONProducer: runtime.JSONProducer(), + RouteAddRouteHandler: route.AddRouteHandlerFunc(func(params route.AddRouteParams) middleware.Responder { + return middleware.NotImplemented("operation RouteAddRoute has not yet been implemented") + }), + RouteDeleteRouteByIDHandler: route.DeleteRouteByIDHandlerFunc(func(params route.DeleteRouteByIDParams) middleware.Responder { + return middleware.NotImplemented("operation RouteDeleteRouteByID has not yet been implemented") + }), + HandleGetHandlesHandler: handle.GetHandlesHandlerFunc(func(params handle.GetHandlesParams) middleware.Responder { + return middleware.NotImplemented("operation HandleGetHandles has not yet been implemented") + }), + HealthGetHealthHandler: health.GetHealthHandlerFunc(func(params health.GetHealthParams) middleware.Responder { + return middleware.NotImplemented("operation HealthGetHealth has not yet been implemented") + }), + RouteGetRouteByIDHandler: route.GetRouteByIDHandlerFunc(func(params route.GetRouteByIDParams) middleware.Responder { + return middleware.NotImplemented("operation RouteGetRouteByID has not yet been implemented") + }), + RouteGetRoutesHandler: route.GetRoutesHandlerFunc(func(params route.GetRoutesParams) middleware.Responder { + return middleware.NotImplemented("operation RouteGetRoutes has not yet been implemented") + }), + HandleProvideXappHandleHandler: handle.ProvideXappHandleHandlerFunc(func(params handle.ProvideXappHandleParams) middleware.Responder { + fmt.Println("hello there") + return middleware.NotImplemented("operation HandleProvideXappHandle has not yet been implemented") + }), + RouteUpdateRouteByIDHandler: route.UpdateRouteByIDHandlerFunc(func(params route.UpdateRouteByIDParams) middleware.Responder { + return middleware.NotImplemented("operation RouteUpdateRouteByID has not yet been implemented") + }), + RouteUpdateRouteHandler: route.UpdateRouteHandlerFunc(func(params route.UpdateRouteParams) middleware.Responder { + return middleware.NotImplemented("operation RouteUpdateRoute has not yet been implemented") + }), + } +} + +/*RoutingManagerAPI This is the Swagger/OpenAPI 2.0 definition of Routing Manager's Northbound API. */ +type RoutingManagerAPI struct { + spec *loads.Document + context *middleware.Context + handlers map[string]map[string]http.Handler + formats strfmt.Registry + customConsumers map[string]runtime.Consumer + customProducers map[string]runtime.Producer + defaultConsumes string + defaultProduces string + Middleware func(middleware.Builder) http.Handler + + // BasicAuthenticator generates a runtime.Authenticator from the supplied basic auth function. + // It has a default implementation in the security package, however you can replace it for your particular usage. + BasicAuthenticator func(security.UserPassAuthentication) runtime.Authenticator + // APIKeyAuthenticator generates a runtime.Authenticator from the supplied token auth function. + // It has a default implementation in the security package, however you can replace it for your particular usage. + APIKeyAuthenticator func(string, string, security.TokenAuthentication) runtime.Authenticator + // BearerAuthenticator generates a runtime.Authenticator from the supplied bearer token auth function. + // It has a default implementation in the security package, however you can replace it for your particular usage. + BearerAuthenticator func(string, security.ScopedTokenAuthentication) runtime.Authenticator + + // JSONConsumer registers a consumer for a "application/json" mime type + JSONConsumer runtime.Consumer + + // JSONProducer registers a producer for a "application/json" mime type + JSONProducer runtime.Producer + + // RouteAddRouteHandler sets the operation handler for the add route operation + RouteAddRouteHandler route.AddRouteHandler + // RouteDeleteRouteByIDHandler sets the operation handler for the delete route by id operation + RouteDeleteRouteByIDHandler route.DeleteRouteByIDHandler + // HandleGetHandlesHandler sets the operation handler for the get handles operation + HandleGetHandlesHandler handle.GetHandlesHandler + // HealthGetHealthHandler sets the operation handler for the get health operation + HealthGetHealthHandler health.GetHealthHandler + // RouteGetRouteByIDHandler sets the operation handler for the get route by id operation + RouteGetRouteByIDHandler route.GetRouteByIDHandler + // RouteGetRoutesHandler sets the operation handler for the get routes operation + RouteGetRoutesHandler route.GetRoutesHandler + // HandleProvideXappHandleHandler sets the operation handler for the provide xapp handle operation + HandleProvideXappHandleHandler handle.ProvideXappHandleHandler + // RouteUpdateRouteByIDHandler sets the operation handler for the update route by id operation + RouteUpdateRouteByIDHandler route.UpdateRouteByIDHandler + // RouteUpdateRouteHandler sets the operation handler for the update route operation + RouteUpdateRouteHandler route.UpdateRouteHandler + + // ServeError is called when an error is received, there is a default handler + // but you can set your own with this + ServeError func(http.ResponseWriter, *http.Request, error) + + // ServerShutdown is called when the HTTP(S) server is shut down and done + // handling all active connections and does not accept connections any more + ServerShutdown func() + + // Custom command line argument groups with their descriptions + CommandLineOptionsGroups []swag.CommandLineOptionsGroup + + // User defined logger function. + Logger func(string, ...interface{}) +} + +// SetDefaultProduces sets the default produces media type +func (o *RoutingManagerAPI) SetDefaultProduces(mediaType string) { + o.defaultProduces = mediaType +} + +// SetDefaultConsumes returns the default consumes media type +func (o *RoutingManagerAPI) SetDefaultConsumes(mediaType string) { + o.defaultConsumes = mediaType +} + +// SetSpec sets a spec that will be served for the clients. +func (o *RoutingManagerAPI) SetSpec(spec *loads.Document) { + o.spec = spec +} + +// DefaultProduces returns the default produces media type +func (o *RoutingManagerAPI) DefaultProduces() string { + return o.defaultProduces +} + +// DefaultConsumes returns the default consumes media type +func (o *RoutingManagerAPI) DefaultConsumes() string { + return o.defaultConsumes +} + +// Formats returns the registered string formats +func (o *RoutingManagerAPI) Formats() strfmt.Registry { + return o.formats +} + +// RegisterFormat registers a custom format validator +func (o *RoutingManagerAPI) RegisterFormat(name string, format strfmt.Format, validator strfmt.Validator) { + o.formats.Add(name, format, validator) +} + +// Validate validates the registrations in the RoutingManagerAPI +func (o *RoutingManagerAPI) Validate() error { + var unregistered []string + + if o.JSONConsumer == nil { + unregistered = append(unregistered, "JSONConsumer") + } + + if o.JSONProducer == nil { + unregistered = append(unregistered, "JSONProducer") + } + + if o.RouteAddRouteHandler == nil { + unregistered = append(unregistered, "route.AddRouteHandler") + } + + if o.RouteDeleteRouteByIDHandler == nil { + unregistered = append(unregistered, "route.DeleteRouteByIDHandler") + } + + if o.HandleGetHandlesHandler == nil { + unregistered = append(unregistered, "handle.GetHandlesHandler") + } + + if o.HealthGetHealthHandler == nil { + unregistered = append(unregistered, "health.GetHealthHandler") + } + + if o.RouteGetRouteByIDHandler == nil { + unregistered = append(unregistered, "route.GetRouteByIDHandler") + } + + if o.RouteGetRoutesHandler == nil { + unregistered = append(unregistered, "route.GetRoutesHandler") + } + + if o.HandleProvideXappHandleHandler == nil { + unregistered = append(unregistered, "handle.ProvideXappHandleHandler") + } + + if o.RouteUpdateRouteByIDHandler == nil { + unregistered = append(unregistered, "route.UpdateRouteByIDHandler") + } + + if o.RouteUpdateRouteHandler == nil { + unregistered = append(unregistered, "route.UpdateRouteHandler") + } + + if len(unregistered) > 0 { + return fmt.Errorf("missing registration: %s", strings.Join(unregistered, ", ")) + } + + return nil +} + +// ServeErrorFor gets a error handler for a given operation id +func (o *RoutingManagerAPI) ServeErrorFor(operationID string) func(http.ResponseWriter, *http.Request, error) { + return o.ServeError +} + +// AuthenticatorsFor gets the authenticators for the specified security schemes +func (o *RoutingManagerAPI) AuthenticatorsFor(schemes map[string]spec.SecurityScheme) map[string]runtime.Authenticator { + + return nil + +} + +// Authorizer returns the registered authorizer +func (o *RoutingManagerAPI) Authorizer() runtime.Authorizer { + + return nil + +} + +// ConsumersFor gets the consumers for the specified media types +func (o *RoutingManagerAPI) ConsumersFor(mediaTypes []string) map[string]runtime.Consumer { + + result := make(map[string]runtime.Consumer) + for _, mt := range mediaTypes { + switch mt { + + case "application/json": + result["application/json"] = o.JSONConsumer + + } + + if c, ok := o.customConsumers[mt]; ok { + result[mt] = c + } + } + return result + +} + +// ProducersFor gets the producers for the specified media types +func (o *RoutingManagerAPI) ProducersFor(mediaTypes []string) map[string]runtime.Producer { + + result := make(map[string]runtime.Producer) + for _, mt := range mediaTypes { + switch mt { + + case "application/json": + result["application/json"] = o.JSONProducer + + } + + if p, ok := o.customProducers[mt]; ok { + result[mt] = p + } + } + return result + +} + +// HandlerFor gets a http.Handler for the provided operation method and path +func (o *RoutingManagerAPI) HandlerFor(method, path string) (http.Handler, bool) { + if o.handlers == nil { + return nil, false + } + um := strings.ToUpper(method) + if _, ok := o.handlers[um]; !ok { + return nil, false + } + if path == "/" { + path = "" + } + h, ok := o.handlers[um][path] + return h, ok +} + +// Context returns the middleware context for the routing manager API +func (o *RoutingManagerAPI) Context() *middleware.Context { + if o.context == nil { + o.context = middleware.NewRoutableContext(o.spec, o, nil) + } + + return o.context +} + +func (o *RoutingManagerAPI) initHandlerCache() { + o.Context() // don't care about the result, just that the initialization happened + + if o.handlers == nil { + o.handlers = make(map[string]map[string]http.Handler) + } + + if o.handlers["POST"] == nil { + o.handlers["POST"] = make(map[string]http.Handler) + } + o.handlers["POST"]["/routes"] = route.NewAddRoute(o.context, o.RouteAddRouteHandler) + + if o.handlers["DELETE"] == nil { + o.handlers["DELETE"] = make(map[string]http.Handler) + } + o.handlers["DELETE"]["/routes/{route-id}"] = route.NewDeleteRouteByID(o.context, o.RouteDeleteRouteByIDHandler) + + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/handles"] = handle.NewGetHandles(o.context, o.HandleGetHandlesHandler) + + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/health"] = health.NewGetHealth(o.context, o.HealthGetHealthHandler) + + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/routes/{route-id}"] = route.NewGetRouteByID(o.context, o.RouteGetRouteByIDHandler) + + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/routes"] = route.NewGetRoutes(o.context, o.RouteGetRoutesHandler) + + if o.handlers["POST"] == nil { + o.handlers["POST"] = make(map[string]http.Handler) + } + o.handlers["POST"]["/handles/xapp-handle"] = handle.NewProvideXappHandle(o.context, o.HandleProvideXappHandleHandler) + + if o.handlers["PUT"] == nil { + o.handlers["PUT"] = make(map[string]http.Handler) + } + o.handlers["PUT"]["/routes/{route-id}"] = route.NewUpdateRouteByID(o.context, o.RouteUpdateRouteByIDHandler) + + if o.handlers["PUT"] == nil { + o.handlers["PUT"] = make(map[string]http.Handler) + } + o.handlers["PUT"]["/routes"] = route.NewUpdateRoute(o.context, o.RouteUpdateRouteHandler) + +} + +// Serve creates a http handler to serve the API over HTTP +// can be used directly in http.ListenAndServe(":8000", api.Serve(nil)) +func (o *RoutingManagerAPI) Serve(builder middleware.Builder) http.Handler { + o.Init() + + if o.Middleware != nil { + return o.Middleware(builder) + } + return o.context.APIHandler(builder) +} + +// Init allows you to just initialize the handler cache, you can then recompose the middleware as you see fit +func (o *RoutingManagerAPI) Init() { + if len(o.handlers) == 0 { + o.initHandlerCache() + } +} + +// RegisterConsumer allows you to add (or override) a consumer for a media type. +func (o *RoutingManagerAPI) RegisterConsumer(mediaType string, consumer runtime.Consumer) { + o.customConsumers[mediaType] = consumer +} + +// RegisterProducer allows you to add (or override) a producer for a media type. +func (o *RoutingManagerAPI) RegisterProducer(mediaType string, producer runtime.Producer) { + o.customProducers[mediaType] = producer +} diff --git a/pkg/restapi/server.go b/pkg/restapi/server.go new file mode 100644 index 0000000..6ddd381 --- /dev/null +++ b/pkg/restapi/server.go @@ -0,0 +1,541 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// ================================================================================== +// Unless otherwise specified, all software contained herein is licensed +// under the Apache License, Version 2.0 (the "Software License"); +// you may not use this software except in compliance with the Software +// License. You may obtain a copy of the Software License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the Software License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the Software License for the specific language governing permissions +// and limitations under the Software License. +// +// ================================================================================== +// +// Unless otherwise specified, all documentation contained herein is licensed +// under the Creative Commons License, Attribution 4.0 Intl. (the +// "Documentation License"); you may not use this documentation except in +// compliance with the Documentation License. You may obtain a copy of the +// Documentation License at +// +// https://creativecommons.org/licenses/by/4.0/ +// +// Unless required by applicable law or agreed to in writing, documentation +// distributed under the Documentation License is distributed on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +// implied. See the Documentation License for the specific language governing +// permissions and limitations under the Documentation License. +// ================================================================================== +// +// + +package restapi + +import ( + "context" + "crypto/tls" + "crypto/x509" + "errors" + "fmt" + "io/ioutil" + "log" + "net" + "net/http" + "os" + "os/signal" + "strconv" + "sync" + "sync/atomic" + "syscall" + "time" + + "github.com/go-openapi/runtime/flagext" + "github.com/go-openapi/swag" + flags "github.com/jessevdk/go-flags" + "golang.org/x/net/netutil" + + "routing-manager/pkg/restapi/operations" +) + +const ( + schemeHTTP = "http" + schemeHTTPS = "https" + schemeUnix = "unix" +) + +var defaultSchemes []string + +func init() { + defaultSchemes = []string{ + schemeHTTP, + } +} + +// NewServer creates a new api routing manager server but does not configure it +func NewServer(api *operations.RoutingManagerAPI) *Server { + s := new(Server) + + s.shutdown = make(chan struct{}) + s.api = api + s.interrupt = make(chan os.Signal, 1) + return s +} + +// ConfigureAPI configures the API and handlers. +func (s *Server) ConfigureAPI() { + if s.api != nil { + s.handler = configureAPI(s.api) + } +} + +// ConfigureFlags configures the additional flags defined by the handlers. Needs to be called before the parser.Parse +func (s *Server) ConfigureFlags() { + if s.api != nil { + configureFlags(s.api) + } +} + +// Server for the routing manager API +type Server struct { + EnabledListeners []string `long:"scheme" description:"the listeners to enable, this can be repeated and defaults to the schemes in the swagger spec"` + CleanupTimeout time.Duration `long:"cleanup-timeout" description:"grace period for which to wait before killing idle connections" default:"10s"` + GracefulTimeout time.Duration `long:"graceful-timeout" description:"grace period for which to wait before shutting down the server" default:"15s"` + MaxHeaderSize flagext.ByteSize `long:"max-header-size" description:"controls the maximum number of bytes the server will read parsing the request header's keys and values, including the request line. It does not limit the size of the request body." default:"1MiB"` + + SocketPath flags.Filename `long:"socket-path" description:"the unix socket to listen on" default:"/var/run/routing-manager.sock"` + domainSocketL net.Listener + + Host string `long:"host" description:"the IP to listen on" default:"localhost" env:"HOST"` + Port int `long:"port" description:"the port to listen on for insecure connections, defaults to a random value" env:"PORT"` + ListenLimit int `long:"listen-limit" description:"limit the number of outstanding requests"` + KeepAlive time.Duration `long:"keep-alive" description:"sets the TCP keep-alive timeouts on accepted connections. It prunes dead TCP connections ( e.g. closing laptop mid-download)" default:"3m"` + ReadTimeout time.Duration `long:"read-timeout" description:"maximum duration before timing out read of the request" default:"30s"` + WriteTimeout time.Duration `long:"write-timeout" description:"maximum duration before timing out write of the response" default:"60s"` + httpServerL net.Listener + + TLSHost string `long:"tls-host" description:"the IP to listen on for tls, when not specified it's the same as --host" env:"TLS_HOST"` + TLSPort int `long:"tls-port" description:"the port to listen on for secure connections, defaults to a random value" env:"TLS_PORT"` + TLSCertificate flags.Filename `long:"tls-certificate" description:"the certificate to use for secure connections" env:"TLS_CERTIFICATE"` + TLSCertificateKey flags.Filename `long:"tls-key" description:"the private key to use for secure connections" env:"TLS_PRIVATE_KEY"` + TLSCACertificate flags.Filename `long:"tls-ca" description:"the certificate authority file to be used with mutual tls auth" env:"TLS_CA_CERTIFICATE"` + TLSListenLimit int `long:"tls-listen-limit" description:"limit the number of outstanding requests"` + TLSKeepAlive time.Duration `long:"tls-keep-alive" description:"sets the TCP keep-alive timeouts on accepted connections. It prunes dead TCP connections ( e.g. closing laptop mid-download)"` + TLSReadTimeout time.Duration `long:"tls-read-timeout" description:"maximum duration before timing out read of the request"` + TLSWriteTimeout time.Duration `long:"tls-write-timeout" description:"maximum duration before timing out write of the response"` + httpsServerL net.Listener + + api *operations.RoutingManagerAPI + handler http.Handler + hasListeners bool + shutdown chan struct{} + shuttingDown int32 + interrupted bool + interrupt chan os.Signal +} + +// Logf logs message either via defined user logger or via system one if no user logger is defined. +func (s *Server) Logf(f string, args ...interface{}) { + if s.api != nil && s.api.Logger != nil { + s.api.Logger(f, args...) + } else { + log.Printf(f, args...) + } +} + +// Fatalf logs message either via defined user logger or via system one if no user logger is defined. +// Exits with non-zero status after printing +func (s *Server) Fatalf(f string, args ...interface{}) { + if s.api != nil && s.api.Logger != nil { + s.api.Logger(f, args...) + os.Exit(1) + } else { + log.Fatalf(f, args...) + } +} + +// SetAPI configures the server with the specified API. Needs to be called before Serve +func (s *Server) SetAPI(api *operations.RoutingManagerAPI) { + if api == nil { + s.api = nil + s.handler = nil + return + } + + s.api = api + s.api.Logger = log.Printf + s.handler = configureAPI(api) +} + +func (s *Server) hasScheme(scheme string) bool { + schemes := s.EnabledListeners + if len(schemes) == 0 { + schemes = defaultSchemes + } + + for _, v := range schemes { + if v == scheme { + return true + } + } + return false +} + +// Serve the api +func (s *Server) Serve() (err error) { + if !s.hasListeners { + if err = s.Listen(); err != nil { + return err + } + } + + // set default handler, if none is set + if s.handler == nil { + if s.api == nil { + return errors.New("can't create the default handler, as no api is set") + } + + s.SetHandler(s.api.Serve(nil)) + } + + wg := new(sync.WaitGroup) + once := new(sync.Once) + signalNotify(s.interrupt) + go handleInterrupt(once, s) + + servers := []*http.Server{} + wg.Add(1) + go s.handleShutdown(wg, &servers) + + if s.hasScheme(schemeUnix) { + domainSocket := new(http.Server) + domainSocket.MaxHeaderBytes = int(s.MaxHeaderSize) + domainSocket.Handler = s.handler + if int64(s.CleanupTimeout) > 0 { + domainSocket.IdleTimeout = s.CleanupTimeout + } + + configureServer(domainSocket, "unix", string(s.SocketPath)) + + servers = append(servers, domainSocket) + wg.Add(1) + s.Logf("Serving routing manager at unix://%s", s.SocketPath) + go func(l net.Listener) { + defer wg.Done() + if err := domainSocket.Serve(l); err != nil && err != http.ErrServerClosed { + s.Fatalf("%v", err) + } + s.Logf("Stopped serving routing manager at unix://%s", s.SocketPath) + }(s.domainSocketL) + } + + if s.hasScheme(schemeHTTP) { + httpServer := new(http.Server) + httpServer.MaxHeaderBytes = int(s.MaxHeaderSize) + httpServer.ReadTimeout = s.ReadTimeout + httpServer.WriteTimeout = s.WriteTimeout + httpServer.SetKeepAlivesEnabled(int64(s.KeepAlive) > 0) + if s.ListenLimit > 0 { + s.httpServerL = netutil.LimitListener(s.httpServerL, s.ListenLimit) + } + + if int64(s.CleanupTimeout) > 0 { + httpServer.IdleTimeout = s.CleanupTimeout + } + + httpServer.Handler = s.handler + + configureServer(httpServer, "http", s.httpServerL.Addr().String()) + + servers = append(servers, httpServer) + wg.Add(1) + s.Logf("Serving routing manager at http://%s", s.httpServerL.Addr()) + go func(l net.Listener) { + defer wg.Done() + if err := httpServer.Serve(l); err != nil && err != http.ErrServerClosed { + s.Fatalf("%v", err) + } + s.Logf("Stopped serving routing manager at http://%s", l.Addr()) + }(s.httpServerL) + } + + if s.hasScheme(schemeHTTPS) { + httpsServer := new(http.Server) + httpsServer.MaxHeaderBytes = int(s.MaxHeaderSize) + httpsServer.ReadTimeout = s.TLSReadTimeout + httpsServer.WriteTimeout = s.TLSWriteTimeout + httpsServer.SetKeepAlivesEnabled(int64(s.TLSKeepAlive) > 0) + if s.TLSListenLimit > 0 { + s.httpsServerL = netutil.LimitListener(s.httpsServerL, s.TLSListenLimit) + } + if int64(s.CleanupTimeout) > 0 { + httpsServer.IdleTimeout = s.CleanupTimeout + } + httpsServer.Handler = s.handler + + // Inspired by https://blog.bracebin.com/achieving-perfect-ssl-labs-score-with-go + httpsServer.TLSConfig = &tls.Config{ + // Causes servers to use Go's default ciphersuite preferences, + // which are tuned to avoid attacks. Does nothing on clients. + PreferServerCipherSuites: true, + // Only use curves which have assembly implementations + // https://github.com/golang/go/tree/master/src/crypto/elliptic + CurvePreferences: []tls.CurveID{tls.CurveP256}, + // Use modern tls mode https://wiki.mozilla.org/Security/Server_Side_TLS#Modern_compatibility + NextProtos: []string{"http/1.1", "h2"}, + // https://www.owasp.org/index.php/Transport_Layer_Protection_Cheat_Sheet#Rule_-_Only_Support_Strong_Protocols + MinVersion: tls.VersionTLS12, + // These ciphersuites support Forward Secrecy: https://en.wikipedia.org/wiki/Forward_secrecy + CipherSuites: []uint16{ + tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, + tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, + tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, + tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, + tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305, + tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305, + }, + } + + // build standard config from server options + if s.TLSCertificate != "" && s.TLSCertificateKey != "" { + httpsServer.TLSConfig.Certificates = make([]tls.Certificate, 1) + httpsServer.TLSConfig.Certificates[0], err = tls.LoadX509KeyPair(string(s.TLSCertificate), string(s.TLSCertificateKey)) + if err != nil { + return err + } + } + + if s.TLSCACertificate != "" { + // include specified CA certificate + caCert, caCertErr := ioutil.ReadFile(string(s.TLSCACertificate)) + if caCertErr != nil { + return caCertErr + } + caCertPool := x509.NewCertPool() + ok := caCertPool.AppendCertsFromPEM(caCert) + if !ok { + return fmt.Errorf("cannot parse CA certificate") + } + httpsServer.TLSConfig.ClientCAs = caCertPool + httpsServer.TLSConfig.ClientAuth = tls.RequireAndVerifyClientCert + } + + // call custom TLS configurator + configureTLS(httpsServer.TLSConfig) + + if len(httpsServer.TLSConfig.Certificates) == 0 { + // after standard and custom config are passed, this ends up with no certificate + if s.TLSCertificate == "" { + if s.TLSCertificateKey == "" { + s.Fatalf("the required flags `--tls-certificate` and `--tls-key` were not specified") + } + s.Fatalf("the required flag `--tls-certificate` was not specified") + } + if s.TLSCertificateKey == "" { + s.Fatalf("the required flag `--tls-key` was not specified") + } + // this happens with a wrong custom TLS configurator + s.Fatalf("no certificate was configured for TLS") + } + + // must have at least one certificate or panics + httpsServer.TLSConfig.BuildNameToCertificate() + + configureServer(httpsServer, "https", s.httpsServerL.Addr().String()) + + servers = append(servers, httpsServer) + wg.Add(1) + s.Logf("Serving routing manager at https://%s", s.httpsServerL.Addr()) + go func(l net.Listener) { + defer wg.Done() + if err := httpsServer.Serve(l); err != nil && err != http.ErrServerClosed { + s.Fatalf("%v", err) + } + s.Logf("Stopped serving routing manager at https://%s", l.Addr()) + }(tls.NewListener(s.httpsServerL, httpsServer.TLSConfig)) + } + + wg.Wait() + return nil +} + +// Listen creates the listeners for the server +func (s *Server) Listen() error { + if s.hasListeners { // already done this + return nil + } + + if s.hasScheme(schemeHTTPS) { + // Use http host if https host wasn't defined + if s.TLSHost == "" { + s.TLSHost = s.Host + } + // Use http listen limit if https listen limit wasn't defined + if s.TLSListenLimit == 0 { + s.TLSListenLimit = s.ListenLimit + } + // Use http tcp keep alive if https tcp keep alive wasn't defined + if int64(s.TLSKeepAlive) == 0 { + s.TLSKeepAlive = s.KeepAlive + } + // Use http read timeout if https read timeout wasn't defined + if int64(s.TLSReadTimeout) == 0 { + s.TLSReadTimeout = s.ReadTimeout + } + // Use http write timeout if https write timeout wasn't defined + if int64(s.TLSWriteTimeout) == 0 { + s.TLSWriteTimeout = s.WriteTimeout + } + } + + if s.hasScheme(schemeUnix) { + domSockListener, err := net.Listen("unix", string(s.SocketPath)) + if err != nil { + return err + } + s.domainSocketL = domSockListener + } + + if s.hasScheme(schemeHTTP) { + listener, err := net.Listen("tcp", net.JoinHostPort(s.Host, strconv.Itoa(s.Port))) + if err != nil { + return err + } + + h, p, err := swag.SplitHostPort(listener.Addr().String()) + if err != nil { + return err + } + s.Host = h + s.Port = p + s.httpServerL = listener + } + + if s.hasScheme(schemeHTTPS) { + tlsListener, err := net.Listen("tcp", net.JoinHostPort(s.TLSHost, strconv.Itoa(s.TLSPort))) + if err != nil { + return err + } + + sh, sp, err := swag.SplitHostPort(tlsListener.Addr().String()) + if err != nil { + return err + } + s.TLSHost = sh + s.TLSPort = sp + s.httpsServerL = tlsListener + } + + s.hasListeners = true + return nil +} + +// Shutdown server and clean up resources +func (s *Server) Shutdown() error { + if atomic.CompareAndSwapInt32(&s.shuttingDown, 0, 1) { + close(s.shutdown) + } + return nil +} + +func (s *Server) handleShutdown(wg *sync.WaitGroup, serversPtr *[]*http.Server) { + // wg.Done must occur last, after s.api.ServerShutdown() + // (to preserve old behaviour) + defer wg.Done() + + <-s.shutdown + + servers := *serversPtr + + ctx, cancel := context.WithTimeout(context.TODO(), s.GracefulTimeout) + defer cancel() + + shutdownChan := make(chan bool) + for i := range servers { + server := servers[i] + go func() { + var success bool + defer func() { + shutdownChan <- success + }() + if err := server.Shutdown(ctx); err != nil { + // Error from closing listeners, or context timeout: + s.Logf("HTTP server Shutdown: %v", err) + } else { + success = true + } + }() + } + + // Wait until all listeners have successfully shut down before calling ServerShutdown + success := true + for range servers { + success = success && <-shutdownChan + } + if success { + s.api.ServerShutdown() + } +} + +// GetHandler returns a handler useful for testing +func (s *Server) GetHandler() http.Handler { + return s.handler +} + +// SetHandler allows for setting a http handler on this server +func (s *Server) SetHandler(handler http.Handler) { + s.handler = handler +} + +// UnixListener returns the domain socket listener +func (s *Server) UnixListener() (net.Listener, error) { + if !s.hasListeners { + if err := s.Listen(); err != nil { + return nil, err + } + } + return s.domainSocketL, nil +} + +// HTTPListener returns the http listener +func (s *Server) HTTPListener() (net.Listener, error) { + if !s.hasListeners { + if err := s.Listen(); err != nil { + return nil, err + } + } + return s.httpServerL, nil +} + +// TLSListener returns the https listener +func (s *Server) TLSListener() (net.Listener, error) { + if !s.hasListeners { + if err := s.Listen(); err != nil { + return nil, err + } + } + return s.httpsServerL, nil +} + +func handleInterrupt(once *sync.Once, s *Server) { + once.Do(func() { + for _ = range s.interrupt { + if s.interrupted { + s.Logf("Server already shutting down") + continue + } + s.interrupted = true + s.Logf("Shutting down... ") + if err := s.Shutdown(); err != nil { + s.Logf("HTTP server Shutdown: %v", err) + } + } + }) +} + +func signalNotify(interrupt chan<- os.Signal) { + signal.Notify(interrupt, syscall.SIGINT, syscall.SIGTERM) +} diff --git a/pkg/rpe/rmr.go b/pkg/rpe/rmr.go index ca16772..1c644b9 100644 --- a/pkg/rpe/rmr.go +++ b/pkg/rpe/rmr.go @@ -26,18 +26,38 @@ package rpe import ( - "rtmgr" "strconv" + "routing-manager/pkg/rtmgr" ) +type Rmr struct { + Rpe +} + +type RmrPub struct { + Rmr +} + +type RmrPush struct { + Rmr +} + +func NewRmrPub() *RmrPub { + instance := new(RmrPub) + return instance +} + +func NewRmrPush() *RmrPush { + instance := new(RmrPush) + return instance +} + /* Produces the raw route message consumable by RMR */ -func generateRMRPolicies(eps rtmgr.Endpoints, key string) *[]string { - rtmgr.Logger.Debug("Invoked rmr.generateRMRPolicies") - rtmgr.Logger.Debug("args: %v", eps) +func (r *Rmr) generateRMRPolicies(eps rtmgr.Endpoints, key string) *[]string { rawrt := []string{key + "newrt|start\n"} - rt := getRouteTable(eps) + rt := r.getRouteTable(eps) for _, rte := range *rt { rawrte := key + "rte|" + rte.MessageType for _, tx := range rte.TxList { @@ -64,14 +84,16 @@ func generateRMRPolicies(eps rtmgr.Endpoints, key string) *[]string { rawrt = append(rawrt, rawrte+"\n") } rawrt = append(rawrt, key+"newrt|end\n") - rtmgr.Logger.Debug("rmr.generateRMRPolicies returns: %v", rawrt) + rtmgr.Logger.Debug("rmr.GeneratePolicies returns: %v", rawrt) return &rawrt } -func generateRMRPubPolicies(eps rtmgr.Endpoints) *[]string { - return generateRMRPolicies(eps, "00000 ") +func (r *RmrPub) GeneratePolicies(eps rtmgr.Endpoints) *[]string { + rtmgr.Logger.Debug("Invoked rmr.GeneratePolicies, args: %v: ", eps) + return r.generateRMRPolicies(eps, "00000 ") } -func generateRMRPushPolicies(eps rtmgr.Endpoints) *[]string { - return generateRMRPolicies(eps, "") +func (r *RmrPush) GeneratePolicies(eps rtmgr.Endpoints) *[]string { + rtmgr.Logger.Debug("Invoked rmr.GeneratePolicies, args: %v: ", eps) + return r.generateRMRPolicies(eps, "") } diff --git a/pkg/rpe/rmr_test.go b/pkg/rpe/rmr_test.go new file mode 100644 index 0000000..bdbeff4 --- /dev/null +++ b/pkg/rpe/rmr_test.go @@ -0,0 +1,60 @@ +/* +================================================================================== + Copyright (c) 2019 AT&T Intellectual Property. + Copyright (c) 2019 Nokia + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +================================================================================== +*/ +/* + Mnemonic: nngpub_test.go + Abstract: + Date: 25 April 2019 +*/ +package rpe + +import ( + "routing-manager/pkg/rtmgr" + "routing-manager/pkg/stub" + "testing" +) + +func resetTestDataset(testdata []rtmgr.Endpoint) { + rtmgr.Eps = make(map[string]*rtmgr.Endpoint) + for _, endpoint := range stub.ValidEndpoints { + ep := endpoint + rtmgr.Eps[ep.Uuid] = &ep + } +} + +/* +RmrPub.GeneratePolicies() method is tested for happy path case +*/ +func TestRmrPubGeneratePolicies(t *testing.T) { + var rmrpub = RmrPub{} + resetTestDataset(stub.ValidEndpoints) + + rawrt := rmrpub.GeneratePolicies(rtmgr.Eps) + t.Log(rawrt) +} + +/* +RmrPush.GeneratePolicies() method is tested for happy path case +*/ +func TestRmrPushGeneratePolicies(t *testing.T) { + var rmrpush = RmrPush{} + resetTestDataset(stub.ValidEndpoints) + + rawrt := rmrpush.GeneratePolicies(rtmgr.Eps) + t.Log(rawrt) +} diff --git a/pkg/rpe/rpe.go b/pkg/rpe/rpe.go index 636a439..af3716c 100644 --- a/pkg/rpe/rpe.go +++ b/pkg/rpe/rpe.go @@ -26,49 +26,39 @@ package rpe import ( "errors" - "fmt" - "rtmgr" + "routing-manager/pkg/rtmgr" ) var ( SupportedRpes = []*RpeEngineConfig{ &RpeEngineConfig{ - RpeEngine{ - Name: "rmrpub", - Version: "pubsub", - Protocol: "rmruta", - }, - generatePolicies(generateRMRPubPolicies), - true, + Name: "rmrpub", + Version: "pubsub", + Protocol: "rmruta", + Instance: NewRmrPub(), + IsAvailable: true, }, &RpeEngineConfig{ - RpeEngine{ - Name: "rmrpush", - Version: "push", - Protocol: "rmruta", - }, - generatePolicies(generateRMRPushPolicies), - true, + Name: "rmrpush", + Version: "pubsush", + Protocol: "rmruta", + Instance: NewRmrPush(), + IsAvailable: true, }, } ) -func ListRpes() { - fmt.Printf("RPE:\n") +func GetRpe(rpeName string) (RpeEngine, error) { for _, rpe := range SupportedRpes { - if rpe.IsAvailable { - rtmgr.Logger.Info(rpe.Engine.Name + "/" + rpe.Engine.Version) + if rpe.Name == rpeName && rpe.IsAvailable { + return rpe.Instance, nil } } + return nil, errors.New("SBI:" + rpeName + " is not supported or still not a available") } -func GetRpe(rpeName string) (*RpeEngineConfig, error) { - for _, rpe := range SupportedRpes { - if rpe.Engine.Name == rpeName && rpe.IsAvailable { - return rpe, nil - } - } - return nil, errors.New("SBI:" + rpeName + " is not supported or still not a available") +type Rpe struct { + } /* @@ -77,7 +67,7 @@ Returns the Tx EndpointList map where the key is the messge type and also return Endpoint object's message type already transcoded to integer id */ -func getRouteRxTxLists(eps rtmgr.Endpoints) (*map[string]rtmgr.EndpointList, *map[string]map[string]rtmgr.EndpointList) { +func (r *Rpe) getRouteRxTxLists(eps rtmgr.Endpoints) (*map[string]rtmgr.EndpointList, *map[string]map[string]rtmgr.EndpointList) { txlist := make(map[string]rtmgr.EndpointList) rxgroups := make(map[string]map[string]rtmgr.EndpointList) for _, ep := range eps { @@ -100,8 +90,8 @@ func getRouteRxTxLists(eps rtmgr.Endpoints) (*map[string]rtmgr.EndpointList, *ma Gets the raw xapp list and creates a route table for Returns the array of route table entries */ -func getRouteTable(eps rtmgr.Endpoints) *rtmgr.RouteTable { - tx, rx := getRouteRxTxLists(eps) +func (r *Rpe) getRouteTable(eps rtmgr.Endpoints) *rtmgr.RouteTable { + tx, rx := r.getRouteRxTxLists(eps) var rt rtmgr.RouteTable for _, messagetype := range rtmgr.MESSAGETYPES { if _, ok := (*tx)[messagetype]; !ok { diff --git a/pkg/rpe/types.go b/pkg/rpe/types.go index b227c0e..8dfcaca 100644 --- a/pkg/rpe/types.go +++ b/pkg/rpe/types.go @@ -24,18 +24,18 @@ package rpe -import "rtmgr" +import "routing-manager/pkg/rtmgr" type generatePolicies func(rtmgr.Endpoints) *[]string -type RpeEngine struct { +type RpeEngineConfig struct { Name string Version string - Protocol string + Protocol string + Instance RpeEngine + IsAvailable bool } -type RpeEngineConfig struct { - Engine RpeEngine - GeneratePolicies generatePolicies - IsAvailable bool +type RpeEngine interface { + GeneratePolicies(rtmgr.Endpoints) *[]string } diff --git a/pkg/rtmgr/rtmgr.go b/pkg/rtmgr/rtmgr.go index 9dd956e..beb22bf 100644 --- a/pkg/rtmgr/rtmgr.go +++ b/pkg/rtmgr/rtmgr.go @@ -26,6 +26,8 @@ package rtmgr import ( "github.com/jcelliott/lumber" + "errors" + "strings" ) var ( @@ -51,22 +53,66 @@ var ( "RIC_E2_MANAGER_HC_RESPONSE": "10008", "RIC_CONTROL_XAPP_CONFIG_REQUEST": "100000", "RIC_CONTROL_XAPP_CONFIG_RESPONSE": "100001", + "RIC_SUB_REQ": "12010", + "RIC_SUB_RESP": "12011", + "RIC_SUB_FAILURE": "12012", + "RIC_SUB_DEL_REQ": "12020", + "RIC_SUB_DEL_RESP": "12021", + "RIC_SUB_DEL_FAILURE": "12022", + "RIC_SERVICE_UPDATE": "12030", + "RIC_SERVICE_UPDATE_ACK": "12031", + "RIC_SERVICE_UPDATE_FAILURE": "12032", + "RIC_CONTROL_REQ": "12040", + "RIC_CONTROL_ACK": "12041", + "RIC_CONTROL_FAILURE": "12042", + "RIC_INDICATION": "12050", + "RIC_SERVICE_QUERY": "12060", + "RIC_X2_SETUP_REQ": "10060", + "RIC_X2_SETUP_RESP": "10061", + "RIC_X2_SETUP_FAILURE": "10062", + "RIC_X2_RESET": "10070", + "RIC_ENDC_X2_SETUP_REQ": "10360", + "RIC_ENDC_X2_SETUP_RESP": "10361", + "RIC_ENDC_X2_SETUP_FAILURE": "10362", + "RIC_ENDC_CONF_UPDATE": "10370", + "RIC_ENDC_CONF_UPDATE_ACK": "10371", + "RIC_ENDC_CONF_UPDATE_FAILURE": "10372", + "RIC_RES_STATUS_REQ": "10090", + "RIC_RES_STATUS_RESP": "10091", + "RIC_RES_STATUS_FAILURE": "10092", + "RIC_ENB_CONF_UPDATE": "10080", + "RIC_ENB_CONF_UPDATE_ACK": "10081", + "RIC_ENB_CONF_UPDATE_FAILURE": "10082", + "RIC_ENB_LOAD_INFORMATION": "10020", + "RIC_GNB_STATUS_INDICATION": "10450", + "RIC_RESOURCE_STATUS_UPDATE": "10100", + "RIC_ERROR_INDICATION": "10030", + "DC_ADM_INT_CONTROL": "20000", + "DC_ADM_INT_CONTROL_ACK": "20001", } + Logger = lumber.NewConsoleLogger(lumber.INFO) - Eps Endpoints + Eps Endpoints ) -func SetLogLevel(loglevel string) { - switch loglevel { +func SetLogLevel(loglevel string) error{ + switch strings.ToUpper(loglevel) { case "INFO": Logger.Level(lumber.INFO) + return nil case "WARN": Logger.Level(lumber.WARN) + return nil case "ERROR": Logger.Level(lumber.ERROR) + return nil case "DEBUG": Logger.Info("debugmode") Logger.Level(lumber.DEBUG) + return nil + default: + Logger.Error("Invalid log mode, setting info") + Logger.Level(lumber.INFO) + return errors.New("Invalid log level, setting info") } } - diff --git a/pkg/rtmgr/rtmgr_test.go b/pkg/rtmgr/rtmgr_test.go new file mode 100644 index 0000000..ad6c504 --- /dev/null +++ b/pkg/rtmgr/rtmgr_test.go @@ -0,0 +1,46 @@ +/* +================================================================================== + Copyright (c) 2019 AT&T Intellectual Property. + Copyright (c) 2019 Nokia + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +================================================================================== +*/ +/* + Mnemonic: rtmgr_test.go + Abstract: + Date: 14 May 2019 +*/ + +package rtmgr + +import ( + "testing" +) + +func TestSetLogLevel(t *testing.T) { + modes_ok := []string{"info","warn","debug","error"} + modes_nok := []string{"inValId","LogLEVEL","PRoviDeD"} + for _, value := range(modes_ok) { + if SetLogLevel(value) != nil { + t.Error("Invalid log level: " + value) + } + } + + for _, value := range(modes_nok) { + if SetLogLevel(value) == nil { + t.Error("Invalid log level: " + value) + } + } +} + diff --git a/pkg/sbi/nngpub.go b/pkg/sbi/nngpub.go index c48a40f..4c299fc 100644 --- a/pkg/sbi/nngpub.go +++ b/pkg/sbi/nngpub.go @@ -17,7 +17,7 @@ ================================================================================== */ /* - Mnemonic: nngpub.go + Mnemonic: NngPub.go Abstract: mangos (NNG) Pub/Sub SBI implementation Date: 12 March 2019 */ @@ -26,52 +26,88 @@ package sbi import ( "errors" - "nanomsg.org/go/mangos/v2" "nanomsg.org/go/mangos/v2/protocol/pub" _ "nanomsg.org/go/mangos/v2/transport/all" - "rtmgr" + "routing-manager/pkg/rtmgr" "strconv" ) -var socket mangos.Socket +type NngPub struct { + Sbi + socket NngSocket + NewSocket CreateNewNngSocketHandler +} -func createNngPubEndpointSocket(ep *rtmgr.Endpoint) error { - return nil +func NewNngPub() *NngPub { + instance := new(NngPub) + instance.NewSocket = createNewPubSocket + return instance } -func destroyNngPubEndpointSocket(ep *rtmgr.Endpoint) error { - return nil +func createNewPubSocket() (NngSocket, error) { + rtmgr.Logger.Debug("Invoked createNewPubSocket()") + s, err := pub.NewSocket() + if err != nil { + return nil, errors.New("can't create new pub socket due to: " + err.Error()) + } + return s, nil } -/* -Creates the NNG publication channel -*/ -func openNngPub(ip string) error { +func (c *NngPub) Initialize(ip string) error { + rtmgr.Logger.Debug("Invoked sbi.Initialize("+ ip +")") var err error - if socket, err = pub.NewSocket(); err != nil { - return errors.New("can't get new pub socket due to:" + err.Error()) + c.socket, err = c.NewSocket() + if err != nil { + return errors.New("create socket error due to: " + err.Error()) + } + if err = c.listen(ip); err != nil { + return errors.New("can't listen on socket due to: " + err.Error()) } + return nil +} + +func (c *NngPub) Terminate() error { + rtmgr.Logger.Debug("Invoked sbi.Terminate()") + return c.closeSocket() +} + +func (c *NngPub) AddEndpoint(ep *rtmgr.Endpoint) error { + return nil +} + +func (c *NngPub) DeleteEndpoint(ep *rtmgr.Endpoint) error { + return nil +} + +func (c *NngPub) UpdateEndpoints(xapps *[]rtmgr.XApp) { + c.updateEndpoints(xapps, c) +} + +func (c *NngPub) listen(ip string) error { + rtmgr.Logger.Debug("Start listening on: " + ip) uri := DEFAULT_NNG_PUBSUB_SOCKET_PREFIX + ip + ":" + strconv.Itoa(DEFAULT_NNG_PUBSUB_SOCKET_NUMBER) rtmgr.Logger.Info("publishing on: " + uri) - if err = socket.Listen(uri); err != nil { - return errors.New("can't publish on socket " + uri + " due to:" + err.Error()) + if err := c.socket.(NngSocket).Listen(uri); err != nil { + return errors.New("can't publish on socket " + uri + " due to: " + err.Error()) } return nil } -func closeNngPub() error { - if err := socket.Close(); err != nil { - return errors.New("can't close socket due to:" + err.Error()) +func (c *NngPub) closeSocket() error { + rtmgr.Logger.Debug("Close NngPub Socket") + if err := c.socket.(NngSocket).Close(); err != nil { + return errors.New("can't close socket due to: " + err.Error()) } return nil } -func publishAll(policies *[]string) error { +func (c *NngPub) DistributeAll(policies *[]string) error { + rtmgr.Logger.Debug("Invoked: sbi.DistributeAll(), args: %v",(*policies)) for _, pe := range *policies { - if err := socket.Send([]byte(pe)); err != nil { + if err := c.socket.(NngSocket).Send([]byte(pe)); err != nil { return errors.New("Unable to send policy entry due to: " + err.Error()) } } - rtmgr.Logger.Info("NNG PUB: OK (# of Entries:" + strconv.Itoa(len((*policies))) + ")") + rtmgr.Logger.Info("NNG PUB: OK (# of Entries: " + strconv.Itoa(len((*policies))) + ")") return nil } diff --git a/pkg/sbi/nngpub_test.go b/pkg/sbi/nngpub_test.go new file mode 100644 index 0000000..b9f8669 --- /dev/null +++ b/pkg/sbi/nngpub_test.go @@ -0,0 +1,217 @@ +/* +================================================================================== + Copyright (c) 2019 AT&T Intellectual Property. + Copyright (c) 2019 Nokia + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +================================================================================== +*/ +/* + Mnemonic: nngpub_test.go + Abstract: + Date: 25 April 2019 +*/ +package sbi + +import ( + "errors" + "routing-manager/pkg/rtmgr" + "routing-manager/pkg/stub" + "testing" +) + +/* +Returns an error free Socket instance +*/ +func createNewStubPubSocket() (NngSocket, error) { + socket := stub.MangosSocket{} + return socket, nil +} + +/* +Returns a SocketError +*/ +func createNewStubPubSocketError() (NngSocket, error) { + return nil, errors.New("stub generated Create Socket error") +} + +/* +Returns a Socket which always generates error on Close() +*/ +func createNewStubPubSocketCloseError() (NngSocket, error) { + socket := stub.MangosSocket{} + socket.GenerateSocketCloseError = true + return socket, nil +} + +/* +Returns a Socket which always generates error on Listen() +*/ +func createNewStubPubSocketListenError() (NngSocket, error) { + socket := stub.MangosSocket{} + socket.GenerateSocketListenError = true + return socket, nil +} + +/* +Returns a Socket which always generates error on Send() +*/ +func createNewStubPubSocketSendError() (NngSocket, error) { + socket := stub.MangosSocket{} + socket.GenerateSocketSendError = true + return socket, nil +} + +/* +Resets the EndpointList according to argumnets +*/ +func resetTestPubDataset(instance NngPub, testdata []rtmgr.Endpoint) { + rtmgr.Eps = make(map[string]*rtmgr.Endpoint) + for _, endpoint := range testdata { + ep := endpoint + ep.Socket, _ = instance.NewSocket() + rtmgr.Eps[ep.Uuid] = &ep + } +} + +/* +nngPub.Initialize() method is tested for happy path case +*/ +func TestNngPubInitialize(t *testing.T) { + var nngpub = NngPub{} + nngpub.NewSocket = createNewStubPubSocket + + err := nngpub.Initialize("") + if err != nil { + t.Errorf("nngPub.Initialize() was incorrect, got: %v, want: %v.", err, nil) + } +} + +/* +nngPub.Initialize() is tested for Socket creating error case +*/ +func TestNngPubInitializeWithSocketError(t *testing.T) { + var nngpub = NngPub{} + nngpub.NewSocket = createNewStubPubSocketError + + err := nngpub.Initialize("") + if err == nil { + t.Errorf("nngPub.Initialize() was incorrect, got: %v, want: %v.", nil, "error") + } +} + +/* +nngPub.Initialize() is tested for Socket listening error case +*/ +func TestNngPubInitializeWithSocketListenError(t *testing.T) { + var nngpub = NngPub{} + nngpub.NewSocket = createNewStubPubSocketListenError + + err := nngpub.Initialize("") + if err == nil { + t.Errorf("nngPub.Initialize() was incorrect, got: %v, want: %v.", nil, "error") + } +} + +/* +nngPub.Terminate() method is empty, nothing to be tested +*/ +func TestNngPubTerminate(t *testing.T) { + var nngpub = NngPub{} + nngpub.NewSocket = createNewStubPubSocket + nngpub.Initialize("") + + err := nngpub.Terminate() + if err != nil { + t.Errorf("nngPub.Terminate() was incorrect, got: %v, want: %v.", err, nil) + } +} + +/* +nngPub.Terminate() is tested for Socket closing error case +*/ +func TestNngPubTerminateWithSocketCloseError(t *testing.T) { + var nngpub = NngPub{} + nngpub.NewSocket = createNewStubPubSocketCloseError + nngpub.Initialize("") + + err := nngpub.Terminate() + if err == nil { + t.Errorf("nngPub.Terminate() was incorrect, got: %v, want: %v.", nil, "error") + } +} + +/* +nngPub.UpdateEndpoints() is testd against stub.ValidXapps dataset +*/ +func TestNngPubUpdateEndpoints(t *testing.T) { + var nngpub = NngPub{} + nngpub.NewSocket = createNewStubPubSocket + nngpub.Initialize("") + rtmgr.Eps = make(rtmgr.Endpoints) + + nngpub.UpdateEndpoints(stub.ValidXapps) + if rtmgr.Eps == nil { + t.Errorf("nngPub.UpdateEndpoints() result was incorrect, got: %v, want: %v.", nil, "rtmgr.Endpoints") + } +} + +/* +nngPub.AddEndpoint() method is empty, nothing to be tested +*/ +func TestNngPubAddEndpoint(t *testing.T) { + var nngpub = NngPub{} + nngpub.NewSocket = createNewStubPubSocket + + _ = nngpub.AddEndpoint(new(rtmgr.Endpoint)) +} + +/* +nngPub.DeleteEndpoint() method is empty, nothing to be tested +*/ +func TestNngPubDeleteEndpoint(t *testing.T) { + var nngpub = NngPub{} + nngpub.NewSocket = createNewStubPubSocket + + _ = nngpub.DeleteEndpoint(new(rtmgr.Endpoint)) +} + +/* +nngPub.DistributeAll() is tested for happy path case +*/ +func TestNngPubDistributeAll(t *testing.T) { + var nngpub = NngPub{} + nngpub.NewSocket = createNewStubPubSocket + nngpub.Initialize("") + resetTestPubDataset(nngpub, stub.ValidEndpoints) + + err := nngpub.DistributeAll(stub.ValidPolicies) + if err != nil { + t.Errorf("nngPub.DistributeAll(policies) was incorrect, got: %v, want: %v.", err, nil) + } +} + +/* +nngPub.DistributeAll() is tested for Sending error case +*/ +func TestNngPubDistributeAllSocketSendError(t *testing.T) { + var nngpub = NngPub{} + nngpub.NewSocket = createNewStubPubSocketSendError + nngpub.Initialize("") + resetTestPubDataset(nngpub, stub.ValidEndpoints) + + err := nngpub.DistributeAll(stub.ValidPolicies) + if err == nil { + t.Errorf("nngPub.DistributeAll(policies) was incorrect, got: %v, want: %v.", nil, "error") + } +} diff --git a/pkg/sbi/nngpush.go b/pkg/sbi/nngpush.go index 01bde0c..19a0b8b 100644 --- a/pkg/sbi/nngpush.go +++ b/pkg/sbi/nngpush.go @@ -29,87 +29,117 @@ import ( "nanomsg.org/go/mangos/v2" "nanomsg.org/go/mangos/v2/protocol/push" _ "nanomsg.org/go/mangos/v2/transport/all" - "rtmgr" + "routing-manager/pkg/rtmgr" "strconv" ) -func openNngPush(ip string) error { - return nil +type NngPush struct { + Sbi + NewSocket CreateNewNngSocketHandler } -func closeNngPush() error { - return nil +func NewNngPush() *NngPush { + instance := new(NngPush) + instance.NewSocket = createNewPushSocket + return instance } -func createNngPushEndpointSocket(ep *rtmgr.Endpoint) error { - rtmgr.Logger.Debug("Invoked sbi.createNngPushEndpointSocket") - rtmgr.Logger.Debug("args: %v", (*ep)) - s, err := push.NewSocket() +func createNewPushSocket() (NngSocket, error) { + rtmgr.Logger.Debug("Invoked: createNewPushSocket()") + socket, err := push.NewSocket() if err != nil { - return errors.New("can't open push socket for endpoint: " + ep.Name +" due to:" + err.Error()) + return nil, errors.New("can't create new push socket due to:" + err.Error()) } - s.SetPipeEventHook(pipeEventHandler) - ep.Socket = s - dial(ep) - return nil -} - -func destroyNngPushEndpointSocket(ep *rtmgr.Endpoint) error { - rtmgr.Logger.Debug("Invoked sbi.destroyNngPushEndpointSocket") - rtmgr.Logger.Debug("args: %v", (*ep)) - if err:= ep.Socket.(mangos.Socket).Close(); err != nil { - return errors.New("can't close push socket of endpoint:" + ep.Uuid + " due to:" + err.Error()) - } - return nil + socket.SetPipeEventHook(pipeEventHandler) + return socket, nil } func pipeEventHandler(event mangos.PipeEvent, pipe mangos.Pipe) { + rtmgr.Logger.Debug("Invoked: pipeEventHandler()") for _, ep := range rtmgr.Eps { uri := DEFAULT_NNG_PIPELINE_SOCKET_PREFIX + ep.Ip + ":" + strconv.Itoa(DEFAULT_NNG_PIPELINE_SOCKET_NUMBER) if uri == pipe.Address() { switch event { case 1: ep.IsReady = true - rtmgr.Logger.Debug("Endpoint " + uri + " successfully registered") + rtmgr.Logger.Debug("Endpoint " + uri + " successfully attached") default: ep.IsReady = false - rtmgr.Logger.Debug("Endpoint " + uri + " has been deregistered") + rtmgr.Logger.Debug("Endpoint " + uri + " has been detached") } } } } +func (c *NngPush) Initialize(ip string) error { + return nil +} + +func (c *NngPush) Terminate() error { + return nil +} + +func (c *NngPush) AddEndpoint(ep *rtmgr.Endpoint) error { + var err error + var socket NngSocket + rtmgr.Logger.Debug("Invoked sbi.AddEndpoint") + rtmgr.Logger.Debug("args: %v", (*ep)) + socket, err = c.NewSocket() + if err != nil { + return errors.New("can't add new socket to endpoint:" + ep.Uuid + " due to: " + err.Error()) + } + ep.Socket = socket + err = c.dial(ep) + if err != nil { + return errors.New("can't dial to endpoint:" + ep.Uuid + " due to: " + err.Error()) + } + return nil +} + +func (c *NngPush) DeleteEndpoint(ep *rtmgr.Endpoint) error { + rtmgr.Logger.Debug("Invoked sbi. DeleteEndpoint") + rtmgr.Logger.Debug("args: %v", (*ep)) + if err:= ep.Socket.(NngSocket).Close(); err != nil { + return errors.New("can't close push socket of endpoint:" + ep.Uuid + " due to: " + err.Error()) + } + return nil +} + +func (c *NngPush) UpdateEndpoints(xapps *[]rtmgr.XApp) { + c.updateEndpoints(xapps, c) +} + /* NOTE: Asynchronous dial starts a goroutine which keep maintains the connection to the given endpoint */ -func dial(ep *rtmgr.Endpoint) { +func (c *NngPush) dial(ep *rtmgr.Endpoint) error { rtmgr.Logger.Debug("Dialing to endpoint: " + ep.Uuid) uri := DEFAULT_NNG_PIPELINE_SOCKET_PREFIX + ep.Ip + ":" + strconv.Itoa(DEFAULT_NNG_PIPELINE_SOCKET_NUMBER) options := make(map[string]interface{}) options[mangos.OptionDialAsynch] = true - if err := ep.Socket.(mangos.Socket).DialOptions(uri, options); err != nil { - rtmgr.Logger.Error("can't dial on push socket to " + uri + " due to:" + err.Error()) + if err := ep.Socket.(NngSocket).DialOptions(uri, options); err != nil { + return errors.New("can't dial on push socket to " + uri + " due to: " + err.Error()) } + return nil } -func pushAll(policies *[]string) error { - rtmgr.Logger.Debug("Invoked: sbi.pushAll") +func (c *NngPush) DistributeAll(policies *[]string) error { + rtmgr.Logger.Debug("Invoked: sbi.DistributeAll") rtmgr.Logger.Debug("args: %v", (*policies)) for _, ep := range rtmgr.Eps { if ep.IsReady { - go send(ep, policies) + go c.send(ep, policies) } else { - rtmgr.Logger.Warn("Endpoint " + ep.Uuid + "is not ready") + rtmgr.Logger.Warn("Endpoint " + ep.Uuid + " is not ready") } } return nil } -func send(ep *rtmgr.Endpoint, policies *[]string) { - rtmgr.Logger.Debug("Invoked: sbi.pushAll") +func (c *NngPush) send(ep *rtmgr.Endpoint, policies *[]string) { rtmgr.Logger.Debug("Push policy to endpoint: "+ ep.Uuid) for _, pe := range *policies { - if err := ep.Socket.(mangos.Socket).Send([]byte(pe)); err != nil { + if err := ep.Socket.(NngSocket).Send([]byte(pe)); err != nil { rtmgr.Logger.Error("Unable to send policy entry due to: " + err.Error()) } } diff --git a/pkg/sbi/nngpush_test.go b/pkg/sbi/nngpush_test.go new file mode 100644 index 0000000..fb52ab5 --- /dev/null +++ b/pkg/sbi/nngpush_test.go @@ -0,0 +1,224 @@ +/* +================================================================================== + Copyright (c) 2019 AT&T Intellectual Property. + Copyright (c) 2019 Nokia + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +================================================================================== +*/ +/* + Mnemonic: nngpush_test.go + Abstract: + Date: 3 May 2019 +*/ +package sbi + +import ( + "errors" + "routing-manager/pkg/rtmgr" + "routing-manager/pkg/stub" + "testing" +) + +/* +Returns an error free Socket instance +*/ +func createNewStubPushSocket() (NngSocket, error) { + socket := stub.MangosSocket{} + return socket, nil +} + +/* +Returns a SocketError +*/ +func createNewStubPushSocketError() (NngSocket, error) { + return nil, errors.New("stub generated Create Socket error") +} + +/* +Returns a Socket which always generates error on Close() +*/ +func createNewStubPushSocketCloseError() (NngSocket, error) { + socket := stub.MangosSocket{} + socket.GenerateSocketCloseError = true + return socket, nil +} + +/* +Returns a Socket which always generates error on Send() +*/ +func createNewStubPushSocketSendError() (NngSocket, error) { + socket := stub.MangosSocket{} + socket.GenerateSocketSendError = true + return socket, nil +} + +/* +Returns a Socket which always generates error on Dial() +*/ +func createNewStubPushSocketDialError() (NngSocket, error) { + socket := stub.MangosSocket{} + socket.GenerateSocketDialError = true + return socket, nil +} + +/* +Resets the EndpointList according to argumnets +*/ +func resetTestPushDataset(instance NngPush, testdata []rtmgr.Endpoint) { + rtmgr.Eps = make(map[string]*rtmgr.Endpoint) + for _, endpoint := range testdata { + ep := endpoint + ep.Socket, _ = instance.NewSocket() + rtmgr.Eps[ep.Uuid] = &ep + } +} + +/* +nngpush.Initialize() method is empty, nothing to be tested +*/ +func TestNngPushInitialize(t *testing.T) { + var nngpush = NngPush{} + nngpush.NewSocket = createNewStubPushSocket + + _ = nngpush.Initialize("") +} + +/* +nngpush.Terminate() method is empty, nothing to be tested +*/ +func TestNngPushTerminate(t *testing.T) { + var nngpush = NngPush{} + nngpush.NewSocket = createNewStubPushSocket + + _ = nngpush.Terminate() +} + +/* +nngpush.UpdateEndpoints() is testd against stub.ValidXapps dataset +*/ +func TestNngPushUpdateEndpoints(t *testing.T) { + var nngpush = NngPush{} + nngpush.NewSocket = createNewStubPushSocket + rtmgr.Eps = make(rtmgr.Endpoints) + + nngpush.UpdateEndpoints(stub.ValidXapps) + if rtmgr.Eps == nil { + t.Errorf("nngpush.UpdateEndpoints() result was incorrect, got: %v, want: %v.", nil, "rtmgr.Endpoints") + } +} + +/* +nngpush.AddEndpoint() is tested for happy path case +*/ +func TestNngPushAddEndpoint(t *testing.T) { + var err error + var nngpush = NngPush{} + nngpush.NewSocket = createNewStubPushSocket + resetTestPushDataset(nngpush, stub.ValidEndpoints) + + err = nngpush.AddEndpoint(rtmgr.Eps["10.0.0.1:0"]) + if err != nil { + t.Errorf("nngpush.AddEndpoint() return was incorrect, got: %v, want: %v.", err, "nil") + } + if rtmgr.Eps["10.0.0.1:0"].Socket == nil { + t.Errorf("nngpush.AddEndpoint() was incorrect, got: %v, want: %v.", nil, "Socket") + } +} + +/* +nngpush.AddEndpoint() is tested for Socket creating error case +*/ +func TestNngPushAddEndpointWithSocketError(t *testing.T) { + var err error + var nngpush = NngPush{} + nngpush.NewSocket = createNewStubPushSocketError + resetTestPushDataset(nngpush, stub.ValidEndpoints) + + err = nngpush.AddEndpoint(rtmgr.Eps["10.0.0.1:0"]) + if err == nil { + t.Errorf("nngpush.AddEndpoint() was incorrect, got: %v, want: %v.", nil, "error") + } + if rtmgr.Eps["10.0.0.1:0"].Socket != nil { + t.Errorf("nngpush.AddEndpoint() was incorrect, got: %v, want: %v.", rtmgr.Eps["10.0.0.1:0"].Socket, nil) + } +} + +/* +nngpush.AddEndpoint() is tested for Dialing error case +*/ +func TestNngPushAddEndpointWithSocketDialError(t *testing.T) { + var err error + var nngpush = NngPush{} + nngpush.NewSocket = createNewStubPushSocketDialError + resetTestPushDataset(nngpush, stub.ValidEndpoints) + + err = nngpush.AddEndpoint(rtmgr.Eps["10.0.0.1:0"]) + if err == nil { + t.Errorf("nngpush.AddEndpoint() was incorrect, got: %v, want: %v.", nil, "error") + } +} + +/* +nngpush.DistributeAll() is tested for happy path case +*/ +func TestNngPushDistributeAll(t *testing.T) { + var err error + var nngpush = NngPush{} + nngpush.NewSocket = createNewStubPushSocket + resetTestPushDataset(nngpush, stub.ValidEndpoints) + + err = nngpush.DistributeAll(stub.ValidPolicies) + if err != nil { + t.Errorf("nngpush.DistributeAll(policies) was incorrect, got: %v, want: %v.", err, "nil") + } +} + +/* +nngpush.DistributeAll() is tested for Sending error case +*/ +func TestNngPushDistributeAllSocketSendError(t *testing.T) { + var err error + var nngpush = NngPush{} + nngpush.NewSocket = createNewStubPushSocketSendError + resetTestPushDataset(nngpush, stub.ValidEndpoints) + + err = nngpush.DistributeAll(stub.ValidPolicies) + if err != nil { + t.Errorf("nngpush.DistributeAll(policies) was incorrect, got: %v, want: %v.", err, "nil") + } +} + +func TestNngPushDeleteEndpoint(t *testing.T) { + var err error + var nngpush = NngPush{} + nngpush.NewSocket = createNewStubPushSocket + resetTestPushDataset(nngpush, stub.ValidEndpoints) + + err = nngpush.DeleteEndpoint(rtmgr.Eps["10.0.0.1:0"]) + if err != nil { + t.Errorf("nngpush.DeleteEndpoint() was incorrect, got: %v, want: %v.", err, "nil") + } +} + +func TestNngPushDeleteEndpointWithSocketCloseError(t *testing.T) { + var err error + var nngpush = NngPush{} + nngpush.NewSocket = createNewStubPushSocketCloseError + resetTestPushDataset(nngpush, stub.ValidEndpoints) + + err = nngpush.DeleteEndpoint(rtmgr.Eps["10.1.1.1:0"]) + if err == nil { + t.Errorf("nngpush.DeleteEndpoint() was incorrect, got: %v, want: %v.", nil, "error") + } +} diff --git a/pkg/sbi/sbi.go b/pkg/sbi/sbi.go index 83b3790..1180391 100644 --- a/pkg/sbi/sbi.go +++ b/pkg/sbi/sbi.go @@ -27,9 +27,8 @@ package sbi import ( "errors" - "fmt" - "rtmgr" "strconv" + "routing-manager/pkg/rtmgr" ) const DEFAULT_NNG_PUBSUB_SOCKET_PREFIX = "tcp://" @@ -40,56 +39,39 @@ const DEFAULT_NNG_PIPELINE_SOCKET_NUMBER = 4561 var ( SupportedSbis = []*SbiEngineConfig{ &SbiEngineConfig{ - SbiEngine{ - Name: "nngpub", - Version: "v1", - Protocol: "nngpubsub", - }, - openSocket(openNngPub), - closeSocket(closeNngPub), - createEndpointSocket(createNngPubEndpointSocket), - destroyEndpointSocket(createNngPubEndpointSocket), - distributeAll(publishAll), - true, - }, + Name: "nngpush", + Version: "v1", + Protocol: "nngpipeline", + Instance: NewNngPush(), + IsAvailable: true, + }, &SbiEngineConfig{ - SbiEngine{ - Name: "nngpush", - Version: "v1", - Protocol: "nngpipeline", - }, - openSocket(openNngPush), - closeSocket(closeNngPush), - createEndpointSocket(createNngPushEndpointSocket), - destroyEndpointSocket(destroyNngPushEndpointSocket), - distributeAll(pushAll), - true, - }, + Name: "nngpub", + Version: "v1", + Protocol: "nngpubsub", + Instance: NewNngPub(), + IsAvailable: true, + }, } ) -func ListSbis() { - fmt.Printf("SBI:\n") +func GetSbi(sbiName string) (SbiEngine, error) { for _, sbi := range SupportedSbis { - if sbi.IsAvailable { - rtmgr.Logger.Info(sbi.Engine.Name + "/" + sbi.Engine.Version) + if sbi.Name == sbiName && sbi.IsAvailable { + return sbi.Instance, nil } } + return nil, errors.New("SBI:" + sbiName + " is not supported or still not available") } -func GetSbi(sbiName string) (*SbiEngineConfig, error) { - for _, sbi := range SupportedSbis { - if (*sbi).Engine.Name == sbiName && (*sbi).IsAvailable { - return sbi, nil - } - } - return nil, errors.New("SBI:" + sbiName + " is not supported or still not available") +type Sbi struct { + } -func pruneEndpointList(sbii *SbiEngineConfig) { +func (s *Sbi) pruneEndpointList(sbii SbiEngine) { for _, ep := range rtmgr.Eps { if !ep.Keepalive { - sbii.DestroyEndpointSocket(ep) + sbii.DeleteEndpoint(ep) delete(rtmgr.Eps, ep.Uuid) } else { rtmgr.Eps[ep.Uuid].Keepalive = false @@ -97,7 +79,7 @@ func pruneEndpointList(sbii *SbiEngineConfig) { } } -func UpdateEndpointList(xapps *[]rtmgr.XApp, sbii *SbiEngineConfig) { +func (s *Sbi) updateEndpoints(xapps *[]rtmgr.XApp, sbii SbiEngine) { for _, xapp := range *xapps { for _, instance := range xapp.Instances { uuid := instance.Ip + ":" + strconv.Itoa(int(instance.Port)) @@ -116,7 +98,7 @@ func UpdateEndpointList(xapps *[]rtmgr.XApp, sbii *SbiEngineConfig) { false, true, } - if err := sbii.CreateEndpointSocket(ep); err != nil { + if err := sbii.AddEndpoint(ep); err != nil { rtmgr.Logger.Error("can't create socket for endpoint: " + ep.Name + " due to:" + err.Error()) continue } @@ -124,5 +106,5 @@ func UpdateEndpointList(xapps *[]rtmgr.XApp, sbii *SbiEngineConfig) { } } } - pruneEndpointList(sbii) + s.pruneEndpointList(sbii) } diff --git a/pkg/sbi/sbi_test.go b/pkg/sbi/sbi_test.go new file mode 100644 index 0000000..5c7e848 --- /dev/null +++ b/pkg/sbi/sbi_test.go @@ -0,0 +1,51 @@ +/* +================================================================================== + Copyright (c) 2019 AT&T Intellectual Property. + Copyright (c) 2019 Nokia + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +================================================================================== +*/ +/* + Mnemonic: sbi_test.go + Abstract: + Date: 25 April 2019 +*/ +package sbi + +import ( + "testing" + "reflect" + "errors" +) + +func TestGetSbi(t *testing.T) { + var errtype = errors.New("") + var sbitype = new(NngPub) + var invalids = []string{"nngpus", ""} + + sbii, err := GetSbi("nngpub") + if err != nil { + t.Errorf("GetSbi(nngpub) was incorrect, got: %v, want: %v.", reflect.TypeOf(err), nil) + } + if reflect.TypeOf(sbii) != reflect.TypeOf(sbitype) { + t.Errorf("GetSbi(nngpub) was incorrect, got: %v, want: %v.", reflect.TypeOf(sbii), reflect.TypeOf(sbitype)) + } + + for _, arg := range invalids { + _, err := GetSbi(arg) + if err == nil { + t.Errorf("GetSbi("+arg+") was incorrect, got: %v, want: %v.", reflect.TypeOf(err), reflect.TypeOf(errtype)) + } + } +} diff --git a/pkg/sbi/types.go b/pkg/sbi/types.go index f971ff5..cdf9b67 100644 --- a/pkg/sbi/types.go +++ b/pkg/sbi/types.go @@ -24,27 +24,30 @@ package sbi -import "rtmgr" +import "routing-manager/pkg/rtmgr" -type distributeAll func(*[]string) error -type openSocket func(string) error -type closeSocket func() error -type createEndpointSocket func(*rtmgr.Endpoint) error -type destroyEndpointSocket func(*rtmgr.Endpoint) error - - -type SbiEngine struct { +type SbiEngineConfig struct { Name string Version string - Protocol string + Protocol string + Instance SbiEngine + IsAvailable bool } -type SbiEngineConfig struct { - Engine SbiEngine - OpenSocket openSocket - CloseSocket closeSocket - CreateEndpointSocket createEndpointSocket - DestroyEndpointSocket destroyEndpointSocket - DistributeAll distributeAll - IsAvailable bool +type SbiEngine interface { + Initialize(string) error + Terminate() error + DistributeAll(*[]string) error + AddEndpoint(*rtmgr.Endpoint) error + DeleteEndpoint(*rtmgr.Endpoint) error + UpdateEndpoints(*[]rtmgr.XApp) } + +type NngSocket interface { + Listen(string) error + Send([]byte) error + Close() error + DialOptions(string, map[string]interface{}) error +} + +type CreateNewNngSocketHandler func() (NngSocket,error) diff --git a/pkg/sdl/file.go b/pkg/sdl/file.go index 11c3350..80f5368 100644 --- a/pkg/sdl/file.go +++ b/pkg/sdl/file.go @@ -29,7 +29,7 @@ import ( "errors" "io/ioutil" "os" - "rtmgr" + "routing-manager/pkg/rtmgr" ) /* @@ -37,9 +37,18 @@ Reads the content of the rt.json file Parses the JSON content and loads each xApp entry into an xApp object Returns an array os xApp object */ -func fileReadAll(file string) (*[]rtmgr.XApp, error) { - rtmgr.Logger.Debug("Invoked file.fileReadAll") - rtmgr.Logger.Debug("file.fileReadAll opens file: " + file) + +type File struct { + Sdl +} + +func NewFile() *File { + instance := new(File) + return instance +} + +func (f *File) ReadAll(file string) (*[]rtmgr.XApp, error) { + rtmgr.Logger.Debug("Invoked sdl.ReadAll("+ file +")") var xapps *[]rtmgr.XApp jsonFile, err := os.Open(file) if err != nil { @@ -50,6 +59,10 @@ func fileReadAll(file string) (*[]rtmgr.XApp, error) { if err != nil { return nil, errors.New("cannot read the file due to: " + err.Error()) } + if string(byteValue) == "{}" { + // empty XApp list + return nil, nil + } err = json.Unmarshal(byteValue, &xapps) if err != nil { return nil, errors.New("cannot parse data due to: " + err.Error()) @@ -58,10 +71,14 @@ func fileReadAll(file string) (*[]rtmgr.XApp, error) { return xapps, nil } -func fileWriteAll(file string, xapps *[]rtmgr.XApp) error { - rtmgr.Logger.Debug("Invoked file.fileWriteAll") +func (f *File) WriteAll(file string, xapps *[]rtmgr.XApp) error { + rtmgr.Logger.Debug("Invoked sdl.WriteAll") rtmgr.Logger.Debug("file.fileWriteAll writes into file: " + file) rtmgr.Logger.Debug("file.fileWriteAll writes data: %v", (*xapps)) + if xapps == nil { + ioutil.WriteFile(file, []byte("{}"), 0644) + return nil + } byteValue, err := json.Marshal(xapps) if err != nil { return errors.New("cannot convert data due to: " + err.Error()) diff --git a/pkg/sdl/sdl.go b/pkg/sdl/sdl.go index 198b05a..b6e0bde 100644 --- a/pkg/sdl/sdl.go +++ b/pkg/sdl/sdl.go @@ -26,49 +26,36 @@ package sdl import ( "errors" - "fmt" - "rtmgr" ) var ( SupportedSdls = []*SdlEngineConfig{ &SdlEngineConfig{ - SdlEngine{ - Name: "file", - Version: "v1", - Protocol: "rawfile", - }, - readAll(fileReadAll), - writeAll(fileWriteAll), - true, + Name: "file", + Version: "v1", + Protocol: "rawfile", + Instance: NewFile(), + IsAvailable: true, }, &SdlEngineConfig{ - SdlEngine{ - Name: "redis", - Version: "v1", - Protocol: "nsdl", - }, - readAll(nil), - writeAll(nil), - false, + Name: "redis", + Version: "v1", + Protocol: "ndsl", + Instance: nil, + IsAvailable: false, }, } ) -func ListSdls() { - fmt.Printf("SDL:\n") +func GetSdl(sdlName string) (SdlEngine, error) { for _, sdl := range SupportedSdls { - if sdl.IsAvailable { - rtmgr.Logger.Info(sdl.Engine.Name + "/" + sdl.Engine.Version) + if sdl.Name == sdlName && sdl.IsAvailable { + return sdl.Instance, nil } } + return nil, errors.New("SDL:" + sdlName + " is not supported or still not a available") } -func GetSdl(sdlName string) (*SdlEngineConfig, error) { - for _, sdl := range SupportedSdls { - if sdl.Engine.Name == sdlName && sdl.IsAvailable { - return sdl, nil - } - } - return nil, errors.New("SDL:" + sdlName + " is not supported or still not a available") +type Sdl struct { + } diff --git a/pkg/sdl/sdl_test.go b/pkg/sdl/sdl_test.go new file mode 100644 index 0000000..b787c60 --- /dev/null +++ b/pkg/sdl/sdl_test.go @@ -0,0 +1,52 @@ +/* +================================================================================== + Copyright (c) 2019 AT&T Intellectual Property. + Copyright (c) 2019 Nokia + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +================================================================================== +*/ +/* + Mnemonic: nngpub_test.go + Abstract: + Date: 25 April 2019 +*/ +package sdl + +import ( + "routing-manager/pkg/stub" + "testing" +) + +/* +RmrPub.GeneratePolicies() method is tested for happy path case +*/ +func TestFileWriteAll(t *testing.T) { + var err error + var file = File{} + + err = file.WriteAll("ut.rt", stub.ValidXapps) + t.Log(err) +} + +/* +RmrPush.GeneratePolicies() method is tested for happy path case +*/ +func TestFileReadAll(t *testing.T) { + var err error + var file = File{} + + data, err := file.ReadAll("ut.rt") + t.Log(data) + t.Log(err) +} diff --git a/pkg/sdl/types.go b/pkg/sdl/types.go index 961c88e..5f86d07 100644 --- a/pkg/sdl/types.go +++ b/pkg/sdl/types.go @@ -23,20 +23,20 @@ */ package sdl -import "rtmgr" +import "routing-manager/pkg/rtmgr" type readAll func(string) (*[]rtmgr.XApp, error) type writeAll func(string, *[]rtmgr.XApp) error -type SdlEngine struct { +type SdlEngineConfig struct { Name string Version string - Protocol string + Protocol string + Instance SdlEngine + IsAvailable bool } -type SdlEngineConfig struct { - Engine SdlEngine - ReadAll readAll - WriteAll writeAll - IsAvailable bool +type SdlEngine interface { + ReadAll(string) (*[]rtmgr.XApp, error) + WriteAll(string,*[]rtmgr.XApp,) error } diff --git a/pkg/stub/mangos.go b/pkg/stub/mangos.go new file mode 100644 index 0000000..915a66d --- /dev/null +++ b/pkg/stub/mangos.go @@ -0,0 +1,321 @@ +/* +================================================================================== + Copyright (c) 2019 AT&T Intellectual Property. + Copyright (c) 2019 Nokia + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +================================================================================== +*/ +/* + Mnemonic: mangos.go + Abstract: + Date: 3 May 2019 +*/ + +package stub + +import "errors" + +type MangosMessage struct { + Header []byte + Body []byte + Pipe MangosPipe + bbuf []byte + hbuf []byte + bsize int + pool interface {} +} + +type MangosProtocolInfo struct { + Self uint16 + Peer uint16 + SelfName string + PeerName string +} + +// Mangos Listener Stub + +type MangosListener struct { + +} + +func (l MangosListener) Listen() error { + return nil +} + +func (l MangosListener) Close() error { + return nil +} + +func (l MangosListener) Address() string { + return "" +} + +func (l MangosListener) SetOption(s string, i interface{}) error { + return nil +} + +func (l MangosListener) GetOption(s string) (interface{},error) { + return nil, nil +} + +// Mangos Dialer Stub + +type MangosDialer struct { + } + +func (d MangosDialer) Open() error { + return nil +} + +func (d MangosDialer) Close() error { + return nil +} + +func (d MangosDialer) Address() string { + return "" +} + +func (d MangosDialer) SetOption(s string, i interface{}) error { + return nil +} + +func (d MangosDialer) GetOption(s string) (interface{},error) { + return nil, nil +} + +// Mangos Context Stub + +type MangosContext struct { + +} + +func (c MangosContext) Close() error { + return nil +} + +func (c MangosContext) SetOption(s string, i interface{}) error { + return nil +} + +func (c MangosContext) GetOption(s string) (interface{},error) { + return nil, nil +} + +func (c MangosContext) Send(b []byte) error { + return nil +} + +func (c MangosContext) Recv() ([]byte, error) { + return make([]byte,0), nil +} + +func (c MangosContext) SendMsg(*MangosMessage) error { + return nil +} + +func (c MangosContext) RecvMsg() (*MangosMessage, error) { + return nil, nil +} + +// Mangos Pipe Stub + +type MangosPipe struct { + +} + +func (p MangosPipe) ID() uint32 { + return 0 +} + +func (p MangosPipe) Listener() MangosListener { + return MangosListener{} +} + +func (p MangosPipe) Dialer() MangosDialer { + return MangosDialer{} +} + +func (p MangosPipe) Close() error { + return nil +} + +func (p MangosPipe) Address() string { + return "" +} + +func (p MangosPipe) GetOption(s string) (interface{},error) { + return nil, nil +} + +// Mangos PipeEventHook Stub + +type PipeEventHook func(int, MangosPipe) + +// Mangos Socket Stub + +type MangosSocket struct { + GenerateSocketCloseError bool + GenerateSocketSendError bool + GenerateSocketDialError bool + GenerateSocketListenError bool +} + +func (s MangosSocket) Info() MangosProtocolInfo { + return MangosProtocolInfo{} +} + +func (s MangosSocket) Close() error { + if s.GenerateSocketCloseError { + return errors.New("stub generated Socket Close error") + } + return nil +} + +func (s MangosSocket) Send(b []byte) error { + if s.GenerateSocketSendError { + return errors.New("stub generated Socket Send error") + } + return nil +} + +func (s MangosSocket) Recv() ([]byte, error) { + return make([]byte,0), nil +} + +func (s MangosSocket) SendMsg(*MangosMessage) error { + return nil +} + +func (s MangosSocket) RecvMsg() (*MangosMessage, error) { + return nil, nil +} + +func (s MangosSocket) Dial(t string) error { + if s.GenerateSocketDialError { + return errors.New("stub generated Socket Dial error") + } + return nil +} + +func (s MangosSocket) DialOptions(t string, m map[string]interface{}) error { + if err := s.Dial(t); err != nil { + return err + } + return nil +} + +func (s MangosSocket) NewDialer(t string, m map[string]interface{}) (MangosDialer, error) { + return MangosDialer{}, nil +} + +func (s MangosSocket) Listen(t string) error { + if s.GenerateSocketListenError { + return errors.New("stub generated Socket Listen error") + } + return nil +} + +func (s MangosSocket) ListenOptions(t string, m map[string]interface{}) error { + return nil +} + +func (s MangosSocket) NewListener(t string, m map[string]interface{}) (MangosListener, error) { + return MangosListener{}, nil +} + +func (s MangosSocket) SetOption(t string, i interface{}) error { + return nil +} + +func (s MangosSocket) GetOption(t string) (interface{},error) { + return nil, nil +} + +func (s MangosSocket) OpenContext() (MangosContext, error) { + return MangosContext{}, nil +} + +func (s MangosSocket) SetPipeEventHook(p PipeEventHook) PipeEventHook { + return nil +} + +// Mangos ProtocolPipe Stub + +type MangosProtocolPipe struct { + +} + +func (p MangosProtocolPipe) ID() uint32 { + return 0 +} + +func (p MangosProtocolPipe) Close() error { + return nil +} + +func (p MangosProtocolPipe) SendMsg(m *MangosMessage) error { + return nil +} + +func (p MangosProtocolPipe) RecvMsg() *MangosMessage { + return nil +} + +// Mangos ProtocolContext Stub + +type MangosProtocolContext struct { + +} + +func (p MangosProtocolContext) Close() error { + return nil +} + +func (p MangosProtocolContext) SendMsg(m *MangosMessage) error { + return nil +} + +func (p MangosProtocolContext) RecvMsg() (*MangosMessage, error) { + return nil, nil +} + +func (p MangosProtocolContext) GetOption(s string) (interface{}, error) { + return nil, nil +} + +func (p MangosProtocolContext) SetOption(s string, i interface{}) error { + return nil +} + +// Mangos ProtocolBase Stub + +type MangosProtocolBase struct { + MangosProtocolContext +} + +func (p MangosProtocolBase) Info() MangosProtocolInfo { + return MangosProtocolInfo{} +} + +func (p MangosProtocolBase) AddPipe(t MangosProtocolPipe) error { + return nil +} + +func (p MangosProtocolBase) RemovePipe(MangosProtocolPipe) { + +} + +func (p MangosProtocolBase) OpenContext() (MangosProtocolContext, error) { + return MangosProtocolContext{}, nil +} diff --git a/pkg/stub/stub.go b/pkg/stub/stub.go new file mode 100644 index 0000000..e5fccb3 --- /dev/null +++ b/pkg/stub/stub.go @@ -0,0 +1,43 @@ +/* +================================================================================== + Copyright (c) 2019 AT&T Intellectual Property. + Copyright (c) 2019 Nokia + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +================================================================================== +*/ +/* + Mnemonic: stub.go + Abstract: + Date: 27 April 2019 +*/ + +package stub + +import "routing-manager/pkg/rtmgr" + +var ValidXapps = &[]rtmgr.XApp{ + rtmgr.XApp{Name: "app1", Status: "", Version: "", Instances: []rtmgr.XAppInstance{rtmgr.XAppInstance{Name: "instance1", Status: "unknown", Ip: "10.0.0.1", Port: 0, TxMessages: []string{"HandoverPreparation", "HandoverCancel"}, RxMessages: []string{"HandoverPreparation", "HandoverCancel"}}}}, + rtmgr.XApp{Name: "app2", Status: "", Version: "", Instances: []rtmgr.XAppInstance{rtmgr.XAppInstance{Name: "instance2", Status: "unknown", Ip: "192.168.0.1", Port: 0, TxMessages: []string{"HandoverCancel", "HandoverPreparation"}, RxMessages: []string{"HandoverPreparation", "HandoverCancel"}}}}, + rtmgr.XApp{Name: "app3", Status: "", Version: "", Instances: []rtmgr.XAppInstance{rtmgr.XAppInstance{Name: "instance2", Status: "unknown", Ip: "10.1.1.1", Port: 0, TxMessages: []string{"X2Setup"}, RxMessages: []string{"Reset", "UEContextRelease"}}}}, + rtmgr.XApp{Name: "app4", Status: "", Version: "", Instances: []rtmgr.XAppInstance{rtmgr.XAppInstance{Name: "instance2", Status: "unknown", Ip: "10.2.2.1", Port: 0, TxMessages: []string{"Reset", "UEContextRelease"}, RxMessages: []string{"", ""}}}}, +} + +var ValidEndpoints = []rtmgr.Endpoint{ + rtmgr.Endpoint{Uuid: "10.0.0.1:0", Name: "i1", XAppType: "app1", Ip: "", Port: 0, TxMessages: []string{"", ""}, RxMessages: []string{"", ""}, Socket: nil, IsReady: true, Keepalive: true}, + rtmgr.Endpoint{Uuid: "192.168.0.1:0", Name: "i2", XAppType: "app2", Ip: "", Port: 0, TxMessages: []string{"", ""}, RxMessages: []string{"", ""}, Socket: nil, IsReady: false, Keepalive: false}, + rtmgr.Endpoint{Uuid: "10.1.1.1:0", Name: "i3", XAppType: "app3", Ip: "", Port: 0, TxMessages: []string{"", ""}, RxMessages: []string{"", ""}, Socket: nil, IsReady: true, Keepalive: false}, + rtmgr.Endpoint{Uuid: "10.2.2.1:0", Name: "i4", XAppType: "app4", Ip: "", Port: 0, TxMessages: []string{"", ""}, RxMessages: []string{"", ""}, Socket: nil, IsReady: false, Keepalive: true}, +} + +var ValidPolicies = &[]string{"", ""} diff --git a/test/data/xapps.json b/test/data/xapps.json new file mode 100644 index 0000000..49db5c5 --- /dev/null +++ b/test/data/xapps.json @@ -0,0 +1,45 @@ +{ + "id": 1, + "event": "whatever", + "data-version": 0, + "data": + "[{ + \"name\": \"xapp-01\", + \"status\": \"unknown\", + \"version\": \"1.2.3\", + \"instances\": [{ + \"name\": \"xapp-01-instance-01\", + \"status\": \"pending\", + \"ip\": \"10.244.0.51\", + \"port\": 4560, + \"txMessages\": [\"ControlIndication\", \"HandoverPreparation\"], + \"rxMessages\": [\"LoadIndication\", \"Reset\"] + },{ + \"name\": \"xapp-01-instance-02\", + \"status\": \"pending\", + \"ip\": \"10.244.0.52\", + \"port\": 4560, + \"txMessages\": [\"ControlIndication\", \"HandoverPreparation\"], + \"rxMessages\": [\"LoadIndication\", \"Reset\"] + }] + },{ + \"name\": \"xapp-02\", + \"status\": \"unknown\", + \"version\": \"1.2.3\", + \"instances\": [{ + \"name\": \"xapp-02-instance-01\", + \"status\": \"pending\", + \"ip\": \"10.244.0.53\", + \"port\": 4560, + \"txMessages\": [\"ControlIndication\", \"HandoverPreparation\"], + \"rxMessages\": [\"LoadIndication\", \"Reset\"] + },{ + \"name\": \"xapp-02-instance-01\", + \"status\": \"pending\", + \"ip\": \"10.244.0.54\", + \"port\": 4560, + \"txMessages\": [\"ControlIndication\", \"HandoverPreparation\"], + \"rxMessages\": [\"LoadIndication\", \"Reset\"] + }] + }]" +} \ No newline at end of file diff --git a/test/docker/xmgr.build/Dockerfile b/test/docker/xmgr.build/Dockerfile index ac8d2b9..8856f84 100644 --- a/test/docker/xmgr.build/Dockerfile +++ b/test/docker/xmgr.build/Dockerfile @@ -22,4 +22,6 @@ # FROM node +COPY middleware.js middleware.js + RUN npm install -g json-server diff --git a/test/docker/xmgr.build/middleware.js b/test/docker/xmgr.build/middleware.js new file mode 100644 index 0000000..217fb4d --- /dev/null +++ b/test/docker/xmgr.build/middleware.js @@ -0,0 +1,10 @@ +module.exports = function (req, res, next) { + if (req.method === 'POST') { + // Converts POST to GET and move payload to query params + // This way it will make JSON Server that it's GET request + req.method = 'GET' + req.query = req.body + } + // Continue to JSON Server router + next() +} diff --git a/test/kubernetes/xapp-tx/xapp-tx.yaml b/test/kubernetes/xapp-tx/xapp-tx.yaml index ea02211..ae104b3 100644 --- a/test/kubernetes/xapp-tx/xapp-tx.yaml +++ b/test/kubernetes/xapp-tx/xapp-tx.yaml @@ -41,12 +41,12 @@ spec: args: - /run_test-tx.sh ports: - - containerPort: 4555 + - containerPort: 4561 env: - name: NAME value: "RM" - name: PORT - value: "tcp:4555" + value: "tcp:4561" - name: RATE value: "10" - name: RMR_RTG_SVC diff --git a/test/kubernetes/xmgr/xmgr-cfg.yaml b/test/kubernetes/xmgr/xmgr-cfg.yaml index a12c824..caac0e8 100644 --- a/test/kubernetes/xmgr/xmgr-cfg.yaml +++ b/test/kubernetes/xmgr/xmgr-cfg.yaml @@ -29,73 +29,79 @@ data: xmgrdata: | { "xapps": - [{ - "name": "admin", - "status": "unknown", - "version": "1.2.3", - "instances": [{ - "name": "admin-01", - "status": "pending", - "ip": "10.244.1.19", - "port": 4561, - "txMessages": ["HandoverPreparation","HandoverCancel"], - "rxMessages": [] - }, - { - "name": "admin-02", - "status": "pending", - "ip": "10.244.3.16", - "port": 4555, - "txMessages": ["HandoverPreparation","HandoverCancel"], - "rxMessages": [] - } - ] - }, + [ + { + "name": "admin", + "status": "unknown", + "version": "1.2.3", + "instances": [{ + "name": "admin-01", + "status": "pending", + "ip": "10.244.1.19", + "port": 4561, + "txMessages": ["HandoverPreparation","HandoverCancel"], + "rxMessages": [] + }, + { + "name": "admin-02", + "status": "pending", + "ip": "10.244.3.16", + "port": 4555, + "txMessages": ["HandoverPreparation","HandoverCancel"], + "rxMessages": [] + } + ] + }, + { + "name": "xapp", + "status": "unknown", + "version": "1.2.3", + "instances": [{ + "name": "xapp-01", + "status": "pending", + "ip": "192.168.2.1", + "port": 32300, + "txMessages": ["X2Setup","Reset"], + "rxMessages": ["HandoverPreparation","HandoverCancel"] + }, + { + "name": "xapp-02", + "status": "pending", + "ip": "192.168.2.2", + "port": 32300, + "txMessages": ["X2Setup","Reset"], + "rxMessages": ["HandoverPreparation","HandoverCancel"] + } + ] + }, + { + "name": "e2t", + "status": "unknown", + "version": "1.2.3", + "instances": [{ + "name": "e2t-01", + "status": "pending", + "ip": "192.168.3.1", + "port": 32300, + "txMessages": [], + "rxMessages": ["HandoverPreparation","HandoverCancel","X2Setup","Reset"] + }, + { + "name": "e2t-02", + "status": "pending", + "ip": "192.168.3.2", + "port": 32300, + "txMessages": [], + "rxMessages": ["HandoverPreparation","HandoverCancel","X2Setup","Reset"] + } + ] + } + ], + "subscriptions": { - "name": "xapp", - "status": "unknown", - "version": "1.2.3", - "instances": [{ - "name": "xapp-01", - "status": "pending", - "ip": "192.168.2.1", - "port": 32300, - "txMessages": ["X2Setup","Reset"], - "rxMessages": ["HandoverPreparation","HandoverCancel"] - }, - { - "name": "xapp-02", - "status": "pending", - "ip": "192.168.2.2", - "port": 32300, - "txMessages": ["X2Setup","Reset"], - "rxMessages": ["HandoverPreparation","HandoverCancel"] - } - ] - }, - { - "name": "e2t", - "status": "unknown", - "version": "1.2.3", - "instances": [{ - "name": "e2t-01", - "status": "pending", - "ip": "192.168.3.1", - "port": 32300, - "txMessages": [], - "rxMessages": ["HandoverPreparation","HandoverCancel","X2Setup","Reset"] - }, - { - "name": "e2t-02", - "status": "pending", - "ip": "192.168.3.2", - "port": 32300, - "txMessages": [], - "rxMessages": ["HandoverPreparation","HandoverCancel","X2Setup","Reset"] - } - ] + "id": "1ILBltYYzEGzWRrVPZKmuUmhwcc", + "version": 0, + "eventType": "all" } - - ] } diff --git a/test/kubernetes/xmgr/xmgr-dep.yaml b/test/kubernetes/xmgr/xmgr-dep.yaml index 768bae7..4884615 100644 --- a/test/kubernetes/xmgr/xmgr-dep.yaml +++ b/test/kubernetes/xmgr/xmgr-dep.yaml @@ -43,6 +43,7 @@ spec: - -w - --host=0.0.0.0 - /db/xapps.json + - --middlewares=middleware.js ports: - containerPort: 3000 volumeMounts: