forked from aertje/cloud-tasks-emulator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
emulator.go
400 lines (317 loc) · 11.5 KB
/
emulator.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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
package main
import (
"context"
"flag"
"fmt"
"net"
"regexp"
"strings"
"sync"
tasks "google.golang.org/genproto/googleapis/cloud/tasks/v2"
v1 "google.golang.org/genproto/googleapis/iam/v1"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
"github.com/golang/protobuf/proto"
"github.com/golang/protobuf/ptypes/empty"
"google.golang.org/grpc"
)
// NewServer creates a new emulator server with its own task and queue bookkeeping
func NewServer() *Server {
return &Server{
qs: make(map[string]*Queue),
ts: make(map[string]*Task),
Options: ServerOptions{
HardResetOnPurgeQueue: false,
},
}
}
type ServerOptions struct {
HardResetOnPurgeQueue bool
}
// Server represents the emulator server
type Server struct {
qs map[string]*Queue
ts map[string]*Task
qsMux sync.Mutex
tsMux sync.Mutex
Options ServerOptions
}
func (s *Server) setQueue(queueName string, queue *Queue) {
s.qsMux.Lock()
defer s.qsMux.Unlock()
s.qs[queueName] = queue
}
func (s *Server) fetchQueue(queueName string) (*Queue, bool) {
s.qsMux.Lock()
defer s.qsMux.Unlock()
queue, ok := s.qs[queueName]
return queue, ok
}
func (s *Server) removeQueue(queueName string) {
s.setQueue(queueName, nil)
}
func (s *Server) setTask(taskName string, task *Task) {
s.tsMux.Lock()
defer s.tsMux.Unlock()
s.ts[taskName] = task
}
func (s *Server) fetchTask(taskName string) (*Task, bool) {
s.tsMux.Lock()
defer s.tsMux.Unlock()
task, ok := s.ts[taskName]
return task, ok
}
func (s *Server) removeTask(taskName string) {
s.setTask(taskName, nil)
}
func (s *Server) hardDeleteTask(taskName string) {
s.tsMux.Lock()
defer s.tsMux.Unlock()
delete(s.ts, taskName)
}
// ListQueues lists the existing queues
func (s *Server) ListQueues(ctx context.Context, in *tasks.ListQueuesRequest) (*tasks.ListQueuesResponse, error) {
// TODO: Implement pageing
var queueStates []*tasks.Queue
s.qsMux.Lock()
defer s.qsMux.Unlock()
for _, queue := range s.qs {
if queue != nil {
queueStates = append(queueStates, queue.state)
}
}
return &tasks.ListQueuesResponse{
Queues: queueStates,
}, nil
}
// GetQueue returns the requested queue
func (s *Server) GetQueue(ctx context.Context, in *tasks.GetQueueRequest) (*tasks.Queue, error) {
queue, ok := s.fetchQueue(in.GetName())
// Cloud responds with the same error message whether the queue was recently deleted or never existed
if !ok || queue == nil {
return nil, status.Errorf(codes.NotFound, "Queue does not exist. If you just created the queue, wait at least a minute for the queue to initialize.")
}
return queue.state, nil
}
// CreateQueue creates a new queue
func (s *Server) CreateQueue(ctx context.Context, in *tasks.CreateQueueRequest) (*tasks.Queue, error) {
queueState := in.GetQueue()
name := queueState.GetName()
nameMatched, _ := regexp.MatchString("projects/[A-Za-z0-9-]+/locations/[A-Za-z0-9-]+/queues/[A-Za-z0-9-]+", name)
if !nameMatched {
return nil, status.Errorf(codes.InvalidArgument, "Queue name must be formatted: \"projects/<PROJECT_ID>/locations/<LOCATION_ID>/queues/<QUEUE_ID>\"")
}
parent := in.GetParent()
parentMatched, _ := regexp.MatchString("projects/[A-Za-z0-9-]+/locations/[A-Za-z0-9-]+", parent)
if !parentMatched {
return nil, status.Errorf(codes.InvalidArgument, "Invalid resource field value in the request.")
}
queue, ok := s.fetchQueue(name)
if ok {
if queue != nil {
return nil, status.Errorf(codes.AlreadyExists, "Queue already exists")
}
return nil, status.Errorf(codes.FailedPrecondition, "The queue cannot be created because a queue with this name existed too recently.")
}
// Make a deep copy so that the original is frozen for the http response
queue, queueState = NewQueue(
name,
proto.Clone(queueState).(*tasks.Queue),
func(task *Task) {
s.removeTask(task.state.GetName())
},
)
s.setQueue(name, queue)
queue.Run()
return queueState, nil
}
// UpdateQueue updates an existing queue (not implemented yet)
func (s *Server) UpdateQueue(ctx context.Context, in *tasks.UpdateQueueRequest) (*tasks.Queue, error) {
return nil, status.Errorf(codes.Unimplemented, "Not yet implemented")
}
// DeleteQueue removes an existing queue.
func (s *Server) DeleteQueue(ctx context.Context, in *tasks.DeleteQueueRequest) (*empty.Empty, error) {
queue, ok := s.fetchQueue(in.GetName())
// Cloud responds with same error for recently deleted queue
if !ok || queue == nil {
return nil, status.Errorf(codes.NotFound, "Requested entity was not found.")
}
queue.Delete()
s.removeQueue(in.GetName())
return &empty.Empty{}, nil
}
// PurgeQueue purges the specified queue
func (s *Server) PurgeQueue(ctx context.Context, in *tasks.PurgeQueueRequest) (*tasks.Queue, error) {
queue, _ := s.fetchQueue(in.GetName())
if s.Options.HardResetOnPurgeQueue {
// Use the development environment behaviour - synchronously purge the queue and release all task names
queue.HardReset(s)
} else {
// Mirror production behaviour - spin off an asynchronous purge operation and return
queue.Purge()
}
return queue.state, nil
}
// PauseQueue pauses queue execution
func (s *Server) PauseQueue(ctx context.Context, in *tasks.PauseQueueRequest) (*tasks.Queue, error) {
queue, _ := s.fetchQueue(in.GetName())
queue.Pause()
return queue.state, nil
}
// ResumeQueue resumes a paused queue
func (s *Server) ResumeQueue(ctx context.Context, in *tasks.ResumeQueueRequest) (*tasks.Queue, error) {
queue, _ := s.fetchQueue(in.GetName())
queue.Resume()
return queue.state, nil
}
// GetIamPolicy doesn't do anything
func (s *Server) GetIamPolicy(ctx context.Context, in *v1.GetIamPolicyRequest) (*v1.Policy, error) {
return nil, status.Errorf(codes.Unimplemented, "Not yet implemented")
}
// SetIamPolicy doesn't do anything
func (s *Server) SetIamPolicy(ctx context.Context, in *v1.SetIamPolicyRequest) (*v1.Policy, error) {
return nil, status.Errorf(codes.Unimplemented, "Not yet implemented")
}
// TestIamPermissions doesn't do anything
func (s *Server) TestIamPermissions(ctx context.Context, in *v1.TestIamPermissionsRequest) (*v1.TestIamPermissionsResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "Not yet implemented")
}
// ListTasks lists the tasks in the specified queue
func (s *Server) ListTasks(ctx context.Context, in *tasks.ListTasksRequest) (*tasks.ListTasksResponse, error) {
// TODO: Implement pageing of some sort
queue, ok := s.fetchQueue(in.GetParent())
if !ok || queue == nil {
return nil, status.Errorf(codes.NotFound, "Queue does not exist. If you just created the queue, wait at least a minute for the queue to initialize.")
}
var taskStates []*tasks.Task
queue.tsMux.Lock()
defer queue.tsMux.Unlock()
for _, task := range queue.ts {
if task != nil {
taskStates = append(taskStates, task.state)
}
}
return &tasks.ListTasksResponse{
Tasks: taskStates,
}, nil
}
// GetTask returns the specified task
func (s *Server) GetTask(ctx context.Context, in *tasks.GetTaskRequest) (*tasks.Task, error) {
task, ok := s.fetchTask(in.GetName())
if !ok {
return nil, status.Errorf(codes.NotFound, "Task does not exist.")
}
if task == nil {
return nil, status.Errorf(codes.FailedPrecondition, "The task no longer exists, though a task with this name existed recently. The task either successfully completed or was deleted.")
}
return task.state, nil
}
// CreateTask creates a new task
func (s *Server) CreateTask(ctx context.Context, in *tasks.CreateTaskRequest) (*tasks.Task, error) {
queueName := in.GetParent()
queue, ok := s.fetchQueue(queueName)
if !ok {
return nil, status.Errorf(codes.NotFound, "Queue does not exist.")
}
if queue == nil {
return nil, status.Errorf(codes.FailedPrecondition, "The queue no longer exists, though a queue with this name existed recently.")
}
if in.Task.Name != "" {
// If a name is specified, it must be valid, it must be unique, and it must belong to this queue
if !isValidTaskName(in.Task.Name) {
return nil, status.Errorf(codes.InvalidArgument, `Task name must be formatted: "projects/<PROJECT_ID>/locations/<LOCATION_ID>/queues/<QUEUE_ID>/tasks/<TASK_ID>"`)
}
if !strings.HasPrefix(in.Task.Name, queueName+"/tasks/") {
return nil, status.Errorf(
codes.InvalidArgument,
"The queue name from request ('%s') must be the same as the queue name in the named task ('%s').",
in.Task.Name,
queueName,
)
}
if _, exists := s.fetchTask(in.Task.Name); exists {
return nil, status.Errorf(codes.AlreadyExists, "Requested entity already exists")
}
}
task, taskState := queue.NewTask(in.GetTask())
s.setTask(taskState.GetName(), task)
return taskState, nil
}
// DeleteTask removes an existing task
func (s *Server) DeleteTask(ctx context.Context, in *tasks.DeleteTaskRequest) (*empty.Empty, error) {
task, ok := s.fetchTask(in.GetName())
if !ok {
return nil, status.Errorf(codes.NotFound, "Task does not exist.")
}
if task == nil {
return nil, status.Errorf(codes.NotFound, "The task no longer exists, though a task with this name existed recently. The task either successfully completed or was deleted.")
}
// The removal of the task from the server struct is handled in the queue callback
task.Delete()
return &empty.Empty{}, nil
}
// RunTask executes an existing task immediately
func (s *Server) RunTask(ctx context.Context, in *tasks.RunTaskRequest) (*tasks.Task, error) {
task, ok := s.fetchTask(in.GetName())
if !ok {
return nil, status.Errorf(codes.NotFound, "Task does not exist.")
}
if task == nil {
return nil, status.Errorf(codes.NotFound, "The task no longer exists, though a task with this name existed recently. The task either successfully completed or was deleted.")
}
taskState := task.Run()
return taskState, nil
}
// arrayFlags used for parsing list of potentially repeated flags e.g. -queue $Q1 -queue $Q2
type arrayFlags []string
func (i *arrayFlags) String() string {
return strings.Join(*i, ", ")
}
func (i *arrayFlags) Set(value string) error {
*i = append(*i, value)
return nil
}
// Creates an initial queue on the emulator
func createInitialQueue(emulatorServer *Server, name string) {
print(fmt.Sprintf("Creating initial queue %s\n", name))
r := regexp.MustCompile("/queues/[A-Za-z0-9-]+$")
parentName := r.ReplaceAllString(name, "")
queue := &tasks.Queue{Name: name}
req := &tasks.CreateQueueRequest{
Parent: parentName,
Queue: queue,
}
_, err := emulatorServer.CreateQueue(context.TODO(), req)
if err != nil {
panic(err)
}
}
func main() {
var initialQueues arrayFlags
host := flag.String("host", "localhost", "The host name")
port := flag.String("port", "8123", "The port")
openidIssuer := flag.String("openid-issuer", "", "URL to serve the OpenID configuration on, if required")
hardResetOnPurgeQueue := flag.Bool("hard-reset-on-purge-queue", false, "Set to force the 'Purge Queue' call to perform a hard reset of all state (differs from production)")
flag.Var(&initialQueues, "queue", "A queue to create on startup (repeat as required)")
flag.Parse()
if *openidIssuer != "" {
srv, err := configureOpenIdIssuer(*openidIssuer)
if err != nil {
panic(err)
}
defer srv.Shutdown(context.Background())
}
lis, err := net.Listen("tcp", fmt.Sprintf("%v:%v", *host, *port))
if err != nil {
panic(err)
}
print(fmt.Sprintf("Starting cloud tasks emulator, listening on %v:%v\n", *host, *port))
grpcServer := grpc.NewServer()
emulatorServer := NewServer()
emulatorServer.Options.HardResetOnPurgeQueue = *hardResetOnPurgeQueue
tasks.RegisterCloudTasksServer(grpcServer, emulatorServer)
for i := 0; i < len(initialQueues); i++ {
createInitialQueue(emulatorServer, initialQueues[i])
}
grpcServer.Serve(lis)
}