forked from argoproj/gitops-engine
/
main.go
201 lines (185 loc) · 5.87 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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
package main
import (
"context"
"crypto/sha256"
"encoding/base64"
"fmt"
"io/ioutil"
"net/http"
"os"
"os/exec"
"path/filepath"
"strings"
"text/tabwriter"
"time"
"github.com/argoproj/pkg/kube/cli"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/client-go/tools/clientcmd"
"github.com/argoproj/gitops-engine/pkg/cache"
"github.com/argoproj/gitops-engine/pkg/engine"
"github.com/argoproj/gitops-engine/pkg/sync"
"github.com/argoproj/gitops-engine/pkg/utils/errors"
executil "github.com/argoproj/gitops-engine/pkg/utils/exec"
"github.com/argoproj/gitops-engine/pkg/utils/io"
"github.com/argoproj/gitops-engine/pkg/utils/kube"
)
const (
annotationGCMark = "gitops-agent.argoproj.io/gc-mark"
)
func main() {
if err := newCmd().Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
type resourceInfo struct {
gcMark string
}
type settings struct {
repoPath string
paths []string
}
func (s *settings) getGCMark(key kube.ResourceKey) string {
h := sha256.New()
_, _ = h.Write([]byte(fmt.Sprintf("%s/%s", s.repoPath, strings.Join(s.paths, ","))))
_, _ = h.Write([]byte(strings.Join([]string{key.Group, key.Kind, key.Name}, "/")))
return "sha256." + base64.RawURLEncoding.EncodeToString(h.Sum(nil))
}
func (s *settings) parseManifests() ([]*unstructured.Unstructured, string, error) {
cmd := exec.Command("git", "rev-parse", "HEAD")
cmd.Dir = s.repoPath
revision, err := executil.Run(cmd)
if err != nil {
return nil, "", err
}
var res []*unstructured.Unstructured
for i := range s.paths {
if err := filepath.Walk(filepath.Join(s.repoPath, s.paths[i]), func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
return nil
}
if ext := filepath.Ext(info.Name()); ext != ".json" && ext != ".yml" && ext != ".yaml" {
return nil
}
data, err := ioutil.ReadFile(path)
if err != nil {
return err
}
items, err := kube.SplitYAML(string(data))
if err != nil {
return fmt.Errorf("failed to parse %s: %v", path, err)
}
res = append(res, items...)
return nil
}); err != nil {
return nil, "", err
}
}
for i := range res {
annotations := res[i].GetAnnotations()
if annotations == nil {
annotations = make(map[string]string)
}
annotations[annotationGCMark] = s.getGCMark(kube.GetResourceKey(res[i]))
res[i].SetAnnotations(annotations)
}
return res, revision, nil
}
func newCmd() *cobra.Command {
var (
clientConfig clientcmd.ClientConfig
paths []string
resyncSeconds int
port int
prune bool
namespace string
namespaced bool
)
cmd := cobra.Command{
Use: "gitops REPO_PATH",
Run: func(cmd *cobra.Command, args []string) {
if len(args) < 1 {
cmd.HelpFunc()(cmd, args)
os.Exit(1)
}
s := settings{args[0], paths}
config, err := clientConfig.ClientConfig()
errors.CheckErrorWithCode(err, errors.ErrorCommandSpecific)
if namespace == "" {
namespace, _, err = clientConfig.Namespace()
errors.CheckErrorWithCode(err, errors.ErrorCommandSpecific)
}
var namespaces []string
if namespaced {
namespaces = []string{namespace}
}
clusterCache := cache.NewClusterCache(config,
cache.SetNamespaces(namespaces),
cache.SetPopulateResourceInfoHandler(func(un *unstructured.Unstructured, isRoot bool) (info interface{}, cacheManifest bool) {
// store gc mark of every resource
gcMark := un.GetAnnotations()[annotationGCMark]
info = &resourceInfo{gcMark: un.GetAnnotations()[annotationGCMark]}
// cache resources that has that mark to improve performance
cacheManifest = gcMark != ""
return
}),
)
gitOpsEngine := engine.NewEngine(config, clusterCache)
errors.CheckErrorWithCode(err, errors.ErrorCommandSpecific)
closer, err := gitOpsEngine.Run()
errors.CheckErrorWithCode(err, errors.ErrorCommandSpecific)
defer io.Close(closer)
resync := make(chan bool)
go func() {
ticker := time.NewTicker(time.Second * time.Duration(resyncSeconds))
for {
<-ticker.C
log.Infof("Synchronization triggered by timer")
resync <- true
}
}()
http.HandleFunc("/api/v1/sync", func(writer http.ResponseWriter, request *http.Request) {
log.Infof("Synchronization triggered by API call")
resync <- true
})
go func() {
errors.CheckErrorWithCode(http.ListenAndServe(fmt.Sprintf("0.0.0.0:%d", port), nil), errors.ErrorCommandSpecific)
}()
for ; true; <-resync {
target, revision, err := s.parseManifests()
if err != nil {
log.Warnf("failed to parse target state: %v", err)
continue
}
result, err := gitOpsEngine.Sync(context.Background(), target, func(r *cache.Resource) bool {
return r.Info.(*resourceInfo).gcMark == s.getGCMark(r.ResourceKey())
}, revision, namespace, sync.WithPrune(prune))
if err != nil {
log.Warnf("failed to synchronize cluster state: %v", err)
continue
}
w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
_, _ = fmt.Fprintf(w, "RESOURCE\tRESULT\n")
for _, res := range result {
_, _ = fmt.Fprintf(w, "%s\t%s\n", res.ResourceKey.String(), res.Message)
}
_ = w.Flush()
}
},
}
clientConfig = cli.AddKubectlFlagsToCmd(&cmd)
cmd.Flags().StringArrayVar(&paths, "path", []string{"."}, "Directory path with-in repository")
cmd.Flags().IntVar(&resyncSeconds, "resync-seconds", 300, "Resync duration in seconds.")
cmd.Flags().IntVar(&port, "port", 9001, "Port number.")
cmd.Flags().BoolVar(&prune, "prune", true, "Enables resource pruning.")
cmd.Flags().BoolVar(&namespaced, "namespaced", false, "Switches agent into namespaced mode.")
cmd.Flags().StringVar(&namespace, "default-namespace", "",
"The namespace that should be used if resource namespace is not specified. "+
"By default resources are installed into the same namespace where gitops-agent is installed.")
return &cmd
}