-
Notifications
You must be signed in to change notification settings - Fork 35
/
service.go
327 lines (296 loc) · 11.2 KB
/
service.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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
package endly
import (
"fmt"
_ "github.com/viant/endly/internal/unsafe"
"github.com/viant/endly/model/location"
"github.com/viant/endly/model/msg"
"github.com/viant/toolbox"
"github.com/viant/toolbox/data"
"reflect"
"sync"
"sync/atomic"
"time"
)
// AbstractService represenst an abstract service.
type (
AbstractService struct {
Service
*sync.RWMutex
routeByAction map[string]*Route
routeByRequest map[reflect.Type]*Route
actions []string
id string
state data.Map
}
Informer interface {
Info() string
}
)
// Mutex returns a mutex.
func (s *AbstractService) Mutex() *sync.RWMutex {
return s.RWMutex
}
// Register register action routes
func (s *AbstractService) Register(routes ...*Route) {
for _, route := range routes {
s.routeByAction[route.Action] = route
s.routeByRequest[reflect.TypeOf(route.RequestProvider())] = route
s.actions = append(s.actions, route.Action)
}
}
func (s *AbstractService) addRouteIfConvertible(request interface{}) *Route {
var requestType = reflect.TypeOf(request)
if requestType != nil {
for k, v := range s.routeByRequest {
if requestType.Kind() == reflect.Ptr && requestType.Elem().ConvertibleTo(k.Elem()) {
s.routeByRequest[requestType] = &Route{
Action: v.Action,
RequestInfo: v.RequestInfo,
ResponseInfo: v.ResponseInfo,
RequestProvider: v.RequestProvider,
ResponseProvider: v.ResponseProvider,
Handler: func(context *Context, convertibleRequest interface{}) (interface{}, error) {
var request = v.RequestProvider()
var requestValue = reflect.ValueOf(request)
var convertibleValue = reflect.ValueOf(convertibleRequest)
requestValue.Elem().Set(convertibleValue.Elem().Convert(k.Elem()))
return v.Handler(context, request)
},
}
return s.routeByRequest[requestType]
}
}
}
return nil
}
// Run returns a service action for supplied action
func (s *AbstractService) Run(context *Context, request interface{}) (response *ServiceResponse) {
response = &ServiceResponse{Status: "ok"}
startEvent := s.Begin(context, request)
var err error
defer func() {
s.End(context)(startEvent, response.Response)
if err != nil {
response.Err = err
response.Status = "error"
response.Error = fmt.Sprintf("%v", err)
}
}()
service, ok := s.routeByRequest[reflect.TypeOf(request)]
if !ok {
service = s.addRouteIfConvertible(request)
if service == nil {
err = NewError(s.ID(), fmt.Sprintf("%T", request), fmt.Errorf("failed to lookup service route: %T", request))
return response
}
}
if initializer, ok := request.(Initializer); ok {
if err = initializer.Init(); err != nil {
err = NewError(s.ID(), service.Action, fmt.Errorf("init %T failed: %v", request, err))
return response
}
}
if validator, ok := request.(Validator); ok {
if err = validator.Validate(); err != nil {
err = NewError(s.ID(), service.Action, fmt.Errorf("validation %T failed: %v", request, err))
return response
}
}
response.Response, err = service.Handler(context, request)
if err != nil {
var previous = err
err = NewError(s.ID(), service.Action, err)
if previous != err {
context.Publish(msg.NewErrorEvent(fmt.Sprintf("%v", err)))
}
response.Err = err
}
return response
}
// Route returns a service action route for supplied action
func (s *AbstractService) Route(action string) (*Route, error) {
if result, ok := s.routeByAction[action]; ok {
return result, nil
}
return nil, fmt.Errorf("unknown %v.%v service action", s.id, action)
}
// Sleep sleeps for provided time in ms
func (s *AbstractService) Sleep(context *Context, sleepTimeMs int) {
if sleepTimeMs == 0 {
return
}
sleepTime := time.Millisecond * time.Duration(sleepTimeMs)
if sleepTime < time.Minute {
if context.IsLoggingEnabled() {
context.Publish(msg.NewSleepEvent(sleepTimeMs))
}
time.Sleep(sleepTime)
return
}
startTime := time.Now()
for {
if context.IsLoggingEnabled() {
context.Publish(msg.NewSleepEvent(1000))
}
if time.Now().Sub(startTime) >= sleepTime {
break
}
time.Sleep(time.Second)
}
}
// GetHostname return host and ssh port
func (s *AbstractService) GetHostname(target *location.Resource) (string, int) {
if target == nil {
return "", 0
}
port := toolbox.AsInt(target.Port())
if port == 0 {
port = 22
}
hostname := target.Hostname()
return hostname, port
}
// Actions returns service actions
func (s *AbstractService) Actions() []string {
return s.actions
}
// Begin add starting event
func (s *AbstractService) Begin(context *Context, value interface{}) msg.Event {
return context.Publish(value)
}
// End adds finishing event.
func (s *AbstractService) End(context *Context) func(startEvent msg.Event, value interface{}) msg.Event {
return func(startEvent msg.Event, value interface{}) msg.Event {
return context.PublishWithStartEvent(value, startEvent)
}
}
// ID returns this service id.
func (s *AbstractService) ID() string {
return s.id
}
// State returns this service state map.
func (s *AbstractService) State() data.Map {
return s.state
}
func (s *AbstractService) RunInBackground(context *Context, handler func() error) (err error) {
wait := &sync.WaitGroup{}
wait.Add(1)
var done uint32 = 0
go func() {
for {
if atomic.LoadUint32(&done) == 1 {
break
}
s.Sleep(context, 2000)
}
}()
go func() {
defer wait.Done()
err = handler()
}()
wait.Wait()
atomic.StoreUint32(&done, 1)
return err
}
func (s *AbstractService) Info() string {
if description, ok := serviceDescriptor[s.id]; ok {
return description
}
return ""
}
// NewAbstractService creates a new abstract service.
func NewAbstractService(id string) *AbstractService {
return &AbstractService{
id: id,
actions: make([]string, 0),
RWMutex: &sync.RWMutex{},
state: data.NewMap(),
routeByAction: make(map[string]*Route),
routeByRequest: make(map[reflect.Type]*Route),
}
}
// NopRequest represent no operation to be deprecated
type NopRequest struct {
In interface{}
}
// nopService represents no operation nopService (deprecated, use workflow, nop instead)
type nopService struct {
*AbstractService
}
func (s *nopService) registerRoutes() {
s.Register(&Route{
Action: "nop",
RequestInfo: &ActionInfo{
Description: "no operation action, helper for separating action.Init as self descriptive steps",
},
RequestProvider: func() interface{} {
return &NopRequest{}
},
ResponseProvider: func() interface{} {
return struct{}{}
},
Handler: func(context *Context, request interface{}) (interface{}, error) {
if req, ok := request.(*NopRequest); ok {
return req.In, nil
}
return nil, fmt.Errorf("unsupported request type: %T", request)
},
})
}
// newNopService creates a new NoOperation nopService.
func newNopService() Service {
var result = &nopService{
AbstractService: NewAbstractService("nop"),
}
result.AbstractService.Service = result
result.registerRoutes()
return result
}
var serviceDescriptor = map[string]string{
"aws/apigateway": "Manages API endpoints that allow HTTP integration for AWS services.",
"aws/cloudwatch": "Monitors AWS resources and applications in real-time.",
"aws/cloudwatchevents": "Triggers AWS Lambda functions, streams, or notifications based on specific events.",
"aws/dynamodb": "Provides operations on DynamoDB databases including CRUD and table management.",
"aws/ec2": "Manages AWS EC2 instances including their lifecycle, configuration, and networking.",
"aws/iam": "Handles AWS Identity and Access Management for securely controlling access to AWS services.",
"aws/kinesis": "Offers operations for Amazon Kinesis handling real-time data streams.",
"aws/kms": "Manages keys and performs cryptographic operations using AWS Key Management Service.",
"aws/lambda": "Automates AWS Lambda functions deployment and management.",
"aws/logs": "Works with CloudWatch Logs for monitoring, storing, and accessing log data.",
"aws/rds": "Manages AWS relational database service instances including setup, operations, and scaling.",
"aws/s3": "Operates on Amazon S3 objects and buckets for storage management.",
"aws/ses": "Integrates with Amazon Simple Email Service for sending emails.",
"aws/sns": "Manages Amazon Simple Notification Service for pub/sub, notifications, and alerts.",
"aws/sqs": "Provides access to Amazon Simple Queue Service for message queuing.",
"aws/ssm": "Manages AWS System Manager for resource grouping, configuration, and automation.",
"gcp/bigquery": "Manages Google BigQuery operations for data querying and storage.",
"gcp/cloudfunctions": "Deploys and manages Google Cloud Functions.",
"gcp/cloudscheduler": "Manages cron jobs in Google Cloud.",
"gcp/compute": "Manages Google Compute Engine resources including VMs and networks.",
"gcp/container": "Operates Google Kubernetes Engine for deploying and managing containers.",
"gcp/kms": "Manages cryptographic keys in Google Cloud.",
"gcp/pubsub": "Handles interactions with Google Cloud Pub/Sub for asynchronous messaging services.",
"gcp/run": "Manages Google Cloud Run applications for containerized apps.",
"gcp/storage": "Provides operations on Google Cloud Storage for object storage management.",
"http/endpoint": "Manages HTTP services including endpoints and requests.",
"http/runner": "Manages HTTP request sending and handling.",
"rest/runner": "Executes RESTful requests.",
"docker": "Manages Docker containers, including lifecycle operations and image management.",
"dsunit": "Handles database operations for testing, including setups, assertions, and data management.",
"storage": "Manages file storage operations across different storage services including local and cloud.",
"secret": "Handles secrets management including secure storage and retrieval.",
"smtp": "Manages SMTP services for sending and receiving emails.",
"validator": "Provides data validation and log assertion functionalities.",
"version/control": "Manages version control operations including checkouts and commits.",
"webdriver": "Manages browser automation for testing web applications.",
"slack": "Integrates with Slack for messaging and notifications.",
"process": "Manages system processes including starting, stopping, and monitoring.",
"msg": "Handles message queuing and pub/sub operations.",
"migrator": "Automates the migration of collections and workflows.",
"sdk": "Manages software development kits within SSH sessions.",
"daemon": "Manages background services on host machines.",
"build": "Handles the build processes of applications according to specified parameters.",
"deployment": "Manages the deployment of applications to various environments.",
"udf": "Supports user-defined functions for specific operations or processes.",
"workflow": "Manages the execution and lifecycle of defined workflows.",
}