-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
178 lines (151 loc) · 4.17 KB
/
main.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
package main
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"log"
"os"
"os/signal"
"syscall"
"time"
"github.com/flanksource/batch-runner/pkg"
commonsContext "github.com/flanksource/commons/context"
"github.com/flanksource/commons/logger"
"github.com/flanksource/gomplate/v3"
"github.com/spf13/cobra"
"gocloud.dev/pubsub"
_ "gocloud.dev/pubsub/awssnssqs"
_ "gocloud.dev/pubsub/azuresb"
_ "gocloud.dev/pubsub/gcppubsub"
_ "gocloud.dev/pubsub/kafkapubsub"
_ "gocloud.dev/pubsub/mempubsub"
_ "gocloud.dev/pubsub/natspubsub"
_ "gocloud.dev/pubsub/rabbitpubsub"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"sigs.k8s.io/yaml"
)
var rootCmd = &cobra.Command{
Use: "queue-consumer",
Short: "Consumes messages from a queue",
Run: run,
}
func run(cmd *cobra.Command, args []string) {
// Create context that can be cancelled
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
configPath := "config.yaml"
configData, err := os.ReadFile(configPath)
if err != nil {
log.Fatalf("Error reading config file: %v", err)
}
var config pkg.Config
if err := yaml.Unmarshal(configData, &config); err != nil {
log.Fatalf("Error parsing config file: %v", err)
}
logger.Infof("Config: %+v", logger.Pretty(config))
url, err := config.BuildURL()
if err != nil {
log.Fatalf("Error building URL: %v", err)
}
// Setup signal handling for graceful shutdown
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
logger.Infof("Receiving messages from %s", url)
// Open subscription using URL from config
subscription, err := pubsub.OpenSubscription(ctx, url)
if err != nil {
log.Fatalf("Failed to open subscription: %v", err)
}
client, _, err := pkg.NewClient()
if err != nil {
log.Fatalf("Failed to create Kubernetes client: %v", err)
}
// Process messages until signal received
go func() {
for {
msg, err := subscription.Receive(ctx)
if err != nil {
if ctx.Err() == context.Canceled {
return
}
logger.Errorf("Error receiving message: %v", err)
time.Sleep(5 * time.Second)
continue
}
ctx := commonsContext.NewContext(context.TODO())
ctx.Logger = logger.StandardLogger().Named(msg.LoggableID)
ctx.Infof("Received message: %v", msg.Metadata)
// Decode base64
decoded, err := base64.StdEncoding.DecodeString(string(msg.Body))
if err != nil {
decoded = msg.Body
}
// Unmarshal to map
var data map[string]any
if err := json.Unmarshal(decoded, &data); err != nil {
logger.Errorf("Error unmarshaling JSON: %v", err)
msg.Ack()
continue
}
ctx.Debugf("input=%s", logger.Pretty(data))
data["msg"] = msg
templater := gomplate.StructTemplater{
Values: data,
DelimSets: []gomplate.Delims{{Left: "{{", Right: "}}"}},
ValueFunctions: true,
}
if config.Pod != nil {
var pod = *config.Pod
if err := templater.Walk(&pod); err != nil {
logger.Errorf("Error templating Pod: %v", err)
msg.Ack()
continue
}
ctx.Tracef("pod=%s", logger.Pretty(pod))
p, err := client.CoreV1().Pods(pod.Namespace).Create(ctx, &pod, metav1.CreateOptions{})
if err != nil {
ctx.Errorf("Error creating Pod: %v", err)
// this could be a temp issue
if msg.Nackable() {
msg.Nack()
}
continue
}
ctx.Infof("Created %s", p.UID)
msg.Ack()
} else if config.Job != nil {
var job = *config.Job
if err := templater.Walk(&job); err != nil {
logger.Errorf("Error templating Pod: %v", err)
msg.Ack()
continue
}
ctx.Tracef("job=%s", logger.Pretty(job))
p, err := client.BatchV1().Jobs(job.Namespace).Create(ctx, &job, metav1.CreateOptions{})
if err != nil {
ctx.Errorf("Error creating job: %v", err)
// this could be a temp issue
if msg.Nackable() {
msg.Nack()
}
continue
}
ctx.Infof("Created %s", p.UID)
msg.Ack()
} else {
ctx.Errorf("Invalid config, must specify either a job or a pod")
}
}
}()
// Wait for signal
<-sigChan
fmt.Println("\nShutting down...")
}
func main() {
logger.BindFlags(rootCmd.Flags())
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}