forked from hidevopsio/hiboot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
application.go
232 lines (197 loc) · 6.92 KB
/
application.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
// Copyright 2018 John Deng (hi.devops.io@gmail.com).
//
// 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.
// Package app provides abstract layer for cli/web application
package app
import (
"errors"
"fmt"
"github.com/kataras/iris/context"
"hidevops.io/hiboot/pkg/factory"
"hidevops.io/hiboot/pkg/factory/autoconfigure"
"hidevops.io/hiboot/pkg/factory/instantiate"
"hidevops.io/hiboot/pkg/log"
"hidevops.io/hiboot/pkg/system"
"hidevops.io/hiboot/pkg/utils/cmap"
"hidevops.io/hiboot/pkg/utils/io"
"os"
"reflect"
"strings"
"sync"
)
const (
// ApplicationContextName is the application context instance name
ApplicationContextName = "app.applicationContext"
)
// Application is the base application interface
type Application interface {
Initialize() error
SetProperty(name string, value ...interface{}) Application
GetProperty(name string) (value interface{}, ok bool)
SetAddCommandLineProperties(enabled bool) Application
Run()
}
// ApplicationContext is the alias interface of Application
type ApplicationContext interface {
RegisterController(controller interface{}) error
Use(handlers ...context.Handler)
GetProperty(name string) (value interface{}, ok bool)
GetInstance(params ...interface{}) (instance interface{})
}
// BaseApplication is the base application
type BaseApplication struct {
WorkDir string
configurations cmap.ConcurrentMap
instances cmap.ConcurrentMap
potatoes cmap.ConcurrentMap
configurableFactory factory.ConfigurableFactory
systemConfig *system.Configuration
postProcessor *postProcessor
properties cmap.ConcurrentMap
mu sync.Mutex
// SetAddCommandLineProperties
addCommandLineProperties bool
}
var (
configContainer []*factory.MetaData
componentContainer []*factory.MetaData
// ErrInvalidObjectType indicates that configuration type is invalid
ErrInvalidObjectType = errors.New("[app] invalid Configuration type, one of app.Configuration need to be embedded")
banner = `
______ ____________ _____
___ / / /__(_)__ /_______________ /_
__ /_/ /__ /__ __ \ __ \ __ \ __/
_ __ / _ / _ /_/ / /_/ / /_/ / /_ Hiboot Application Framework
/_/ /_/ /_/ /_.___/\____/\____/\__/ https://hidevops.io/hiboot
`
)
// PrintStartupMessages prints startup messages
func (a *BaseApplication) PrintStartupMessages() {
if !a.systemConfig.App.Banner.Disabled {
fmt.Print(banner)
}
}
// SetProperty set application property
// TODO: should set property from source by SetProperty or accept from program argument, e.g. myapp --app.profiles.active=dev
func (a *BaseApplication) SetProperty(name string, value ...interface{}) Application {
var val interface{}
if len(value) == 1 {
val = value[0]
} else {
val = value
}
kind := reflect.TypeOf(val).Kind()
if kind == reflect.String && strings.Contains(val.(string), ",") {
val = strings.SplitN(val.(string), ",", -1)
}
a.properties.Set(name, val)
return a
}
// GetProperty get application property
func (a *BaseApplication) GetProperty(name string) (value interface{}, ok bool) {
value, ok = a.properties.Get(name)
return
}
// Initialize init application
func (a *BaseApplication) Initialize() (err error) {
log.SetLevel(log.InfoLevel)
a.properties = cmap.New()
a.configurations = cmap.New()
a.instances = cmap.New()
// set add command line properties to true as default
a.SetAddCommandLineProperties(true)
return nil
}
// Initialize init application
func (a *BaseApplication) Build() {
a.mu.Lock()
defer a.mu.Unlock()
a.WorkDir = io.GetWorkDir()
// set custom properties from args
a.setCustomPropertiesFromArgs()
instantiateFactory := instantiate.NewInstantiateFactory(a.instances, componentContainer, a.properties)
// TODO: should set or get instance by passing object instantiateFactory
instantiateFactory.SetInstance(factory.InstantiateFactoryName, instantiateFactory)
instantiateFactory.AppendComponent(factory.InstantiateFactoryName, instantiateFactory)
configurableFactory := autoconfigure.NewConfigurableFactory(instantiateFactory, a.configurations)
instantiateFactory.SetInstance(factory.ConfigurableFactoryName, configurableFactory)
instantiateFactory.AppendComponent(factory.ConfigurableFactoryName, configurableFactory)
a.configurableFactory = configurableFactory
a.postProcessor = newPostProcessor(instantiateFactory)
a.systemConfig, _ = configurableFactory.BuildSystemConfig()
// set logging level
log.SetLevel(a.systemConfig.Logging.Level)
}
// SystemConfig returns application config
func (a *BaseApplication) setCustomPropertiesFromArgs() {
//log.Println(os.Args)
if a.addCommandLineProperties {
for _, val := range os.Args {
prefix := val[:2]
if prefix == "--" {
kv := val[2:]
kvPair := strings.Split(kv, "=")
a.SetProperty(kvPair[0], kvPair[1])
}
}
}
}
// SystemConfig returns application config
func (a *BaseApplication) SystemConfig() *system.Configuration {
return a.systemConfig
}
// BuildConfigurations get BuildConfigurations
func (a *BaseApplication) BuildConfigurations() {
// build configurations
a.configurableFactory.Build(configContainer)
// build components
a.configurableFactory.BuildComponents()
}
// ConfigurableFactory get ConfigurableFactory
func (a *BaseApplication) ConfigurableFactory() factory.ConfigurableFactory {
return a.configurableFactory
}
// AfterInitialization post initialization
func (a *BaseApplication) AfterInitialization(configs ...cmap.ConcurrentMap) {
// pass user's instances
a.postProcessor.Init()
a.postProcessor.AfterInitialization()
if a.addCommandLineProperties {
log.Info("Add command line properties is enabled")
} else {
log.Info("Add command line properties is disabled")
}
}
// RegisterController register controller by interface
func (a *BaseApplication) RegisterController(controller interface{}) error {
return nil
}
// Use use middleware handlers
func (a *BaseApplication) Use(handlers ...context.Handler) {
}
// SetAddCommandLineProperties set add command line properties to be enabled or disabled
func (a *BaseApplication) SetAddCommandLineProperties(enabled bool) Application {
a.addCommandLineProperties = enabled
return a
}
// Run run the application
func (a *BaseApplication) Run() {
log.Warn("application is not implemented!")
}
// GetInstance get application instance by name
func (a *BaseApplication) GetInstance(params ...interface{}) (instance interface{}) {
if a.configurableFactory != nil {
instance = a.configurableFactory.GetInstance(params...)
}
return
}