d94564976c3386d16e9bb7819bd67bf897aa49f6
[ealt-edge.git] / mecm / mepm / applcm / broker / pkg / handlers / handlers.go
1 /*
2  * Copyright 2020 Huawei Technologies Co., Ltd.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package handlers
17
18 import (
19         "broker/pkg/handlers/model"
20         "fmt"
21         "github.com/gorilla/mux"
22         "github.com/jinzhu/gorm"
23         _ "github.com/jinzhu/gorm/dialects/mysql"
24         "log"
25         "net/http"
26         "os"
27         "time"
28 )
29
30 const CreateAppInstance = "/ealtedge/mepm/app_lcm/v1/app_instances"
31 const InstantiateAppInstance = "/ealtedge/mepm/app_lcm/v1/app_instances/{appInstanceId}/instantiate"
32 const QueryAppInstanceInfo = "/ealtedge/mepm/app_lcm/v1/app_instances/{appInstanceId}"
33 const QueryAppLcmOperationStatus = "/ealtedge/mepm/app_lcm/v1/app_lcm_op_occs"
34 const TerminateAppIns = "/ealtedge/mepm/app_lcm/v1/app_instances/{appInstanceId}/terminate"
35 const DeleteAppInstanceIdentifier = "/ealtedge/mepm/app_lcm/v1/app_instances/{appInstanceId}"
36 const OnboardPackage = "/ealtedge/mepm/app_pkgm/v1/app_packages"
37 const QueryOnboardPackage = "/ealtedge/mepm/app_pkgm/v1/app_packages/{appPkgId}"
38
39 const PackageFolderPath = "/go/release/application/packages/"
40 const PackageArtifactPath = "/Artifacts/Deployment/"
41
42 type Handlers struct {
43         Router *mux.Router
44         logger *log.Logger
45         db     *gorm.DB
46 }
47
48 const DB_NAME = "applcmDB"
49
50 // Run the app on it's router
51 func (hdlr *Handlers) Run(host string) {
52         fmt.Println("Binding to port...: %d", host)
53         log.Fatal(http.ListenAndServe(host, hdlr.Router))
54 }
55
56 func createDatabase() *gorm.DB {
57         fmt.Println("creating Database...")
58
59         usrpswd := os.Getenv("MYSQL_USER") + ":" + os.Getenv("MYSQL_PASSWORD")
60         host := "@tcp(" + "dbhost" + ":3306)/"
61
62         db, err := gorm.Open("mysql", usrpswd + host)
63         if err != nil {
64                 fmt.Println("Database connect error", err.Error())
65         }
66 //      db = db.Exec("DROP DATABASE IF EXISTS " +  DB_NAME)
67 //      db = db.Exec("CREATE DATABASE "+ DB_NAME)
68         db.Exec("CREATE DATABASE  " + DB_NAME)
69         db.Exec("USE applcmDB")
70
71         //db.Close()
72         //db, err = gorm.Open("mysql", usrpswd + host + DB_NAME + "?charset=utf8&parseTime=True")
73         /*if err != nil {
74                 fmt.Println("Database connect error", err.Error())
75         } else {
76                 fmt.Println("Database connected successfully")
77         }*/
78         gorm.DefaultCallback.Create().Remove("mysql:set_identity_insert")
79
80         fmt.Println("Migrating models...")
81         db.AutoMigrate(&model.AppPackageInfo{})
82         db.AutoMigrate(&model.AppInstanceInfo{})
83         //db.LogMode(true)
84         return db
85 }
86
87 // Initialize initializes the app with predefined configuration
88 func (hdlr *Handlers) Initialize(logger *log.Logger) {
89         hdlr.Router = mux.NewRouter()
90
91         hdlr.logger = logger
92         hdlr.setRouters()
93         hdlr.db = createDatabase()
94 }
95
96 func (hdlr *Handlers) Logger(next http.HandlerFunc) http.HandlerFunc {
97         return func(w http.ResponseWriter, r *http.Request) {
98                 startTime := time.Now()
99                 defer hdlr.logger.Printf("request processed in %s\n", time.Now().Sub(startTime))
100                 next(w, r)
101         }
102 }
103
104 // setRouters sets the all required routers
105 func (hdlr *Handlers) setRouters() {
106         // Routing for handling the requests
107         hdlr.Post(OnboardPackage, hdlr.handleRequest(UploadFileHldr))
108         hdlr.Get(QueryOnboardPackage, hdlr.handleRequest(QueryAppPackageInfo))
109         hdlr.Post(CreateAppInstance, hdlr.handleRequest(CreateAppInstanceHldr))
110         hdlr.Delete(QueryOnboardPackage, hdlr.handleRequest(DeleteAppPackage))
111         hdlr.Post(InstantiateAppInstance, hdlr.handleRequest(InstantiateAppInstanceHldr))
112         hdlr.Get(QueryAppInstanceInfo, hdlr.handleRequest(QueryAppInstanceInfoHldr))
113         hdlr.Get(QueryAppLcmOperationStatus, hdlr.handleRequest(QueryAppLcmOperationStatusHldr))
114         hdlr.Post(TerminateAppIns, hdlr.handleRequest(TerminateAppInsHldr))
115         hdlr.Delete(DeleteAppInstanceIdentifier, hdlr.handleRequest(DeleteAppInstanceIdentifierHldr))
116 }
117
118 // Get wraps the router for GET method
119 func (hdlr *Handlers) Get(path string, f func(w http.ResponseWriter, r *http.Request)) {
120         hdlr.Router.HandleFunc(path, f).Methods("GET")
121 }
122
123 // Post wraps the router for POST method
124 func (hdlr *Handlers) Post(path string, f func(w http.ResponseWriter, r *http.Request)) {
125         hdlr.Router.HandleFunc(path, f).Methods("POST")
126 }
127
128 // Put wraps the router for PUT method
129 func (hdlr *Handlers) Put(path string, f func(w http.ResponseWriter, r *http.Request)) {
130         hdlr.Router.HandleFunc(path, f).Methods("PUT")
131 }
132
133 // Delete wraps the router for DELETE method
134 func (hdlr *Handlers) Delete(path string, f func(w http.ResponseWriter, r *http.Request)) {
135         hdlr.Router.HandleFunc(path, f).Methods("DELETE")
136 }
137
138 type RequestHandlerFunction func(db *gorm.DB, w http.ResponseWriter, r *http.Request)
139
140 func (hdlr *Handlers) handleRequest(handler RequestHandlerFunction) http.HandlerFunc {
141         return func(w http.ResponseWriter, r *http.Request) {
142                 handler(hdlr.db, w, r)
143         }
144 }