1
0
Fork 0
mirror of https://github.com/kyverno/kyverno.git synced 2025-03-07 00:17:13 +00:00
kyverno/pkg/policyStatus/main.go

91 lines
1.8 KiB
Go
Raw Normal View History

2020-02-25 20:55:07 +05:30
package policyStatus
import (
"sync"
"time"
"github.com/golang/glog"
"k8s.io/apimachinery/pkg/util/wait"
"github.com/nirmata/kyverno/pkg/client/clientset/versioned"
v1 "github.com/nirmata/kyverno/pkg/api/kyverno/v1"
)
2020-02-29 22:39:27 +05:30
type statusUpdater interface {
UpdateStatus(s *Sync)
}
type policyStore interface {
Get(policyName string) (*v1.ClusterPolicy, error)
}
2020-02-25 20:55:07 +05:30
type Sync struct {
2020-02-29 22:39:27 +05:30
Cache *cache
Listener chan statusUpdater
2020-02-25 20:55:07 +05:30
client *versioned.Clientset
2020-02-29 22:39:27 +05:30
PolicyStore policyStore
2020-02-25 20:55:07 +05:30
}
type cache struct {
2020-02-29 22:39:27 +05:30
Mutex sync.RWMutex
Data map[string]v1.PolicyStatus
2020-02-25 20:55:07 +05:30
}
2020-02-29 22:39:27 +05:30
func NewSync(c *versioned.Clientset, p policyStore) *Sync {
2020-02-25 20:55:07 +05:30
return &Sync{
2020-02-29 22:39:27 +05:30
Cache: &cache{
Mutex: sync.RWMutex{},
Data: make(map[string]v1.PolicyStatus),
2020-02-25 20:55:07 +05:30
},
client: c,
2020-02-29 22:39:27 +05:30
PolicyStore: p,
Listener: make(chan statusUpdater, 20),
2020-02-25 20:55:07 +05:30
}
}
2020-02-29 17:19:00 +05:30
func (s *Sync) Run(workers int, stopCh <-chan struct{}) {
2020-02-25 21:07:00 +05:30
for i := 0; i < workers; i++ {
2020-02-29 17:19:00 +05:30
go s.updateStatusCache(stopCh)
2020-02-25 21:07:00 +05:30
}
2020-02-29 17:19:00 +05:30
wait.Until(s.updatePolicyStatus, 2*time.Second, stopCh)
<-stopCh
2020-02-25 20:55:07 +05:30
}
2020-02-29 17:19:00 +05:30
func (s *Sync) updateStatusCache(stopCh <-chan struct{}) {
2020-02-25 20:55:07 +05:30
for {
select {
2020-02-29 22:39:27 +05:30
case statusUpdater := <-s.Listener:
statusUpdater.UpdateStatus(s)
2020-02-29 17:19:00 +05:30
case <-stopCh:
2020-02-25 20:55:07 +05:30
return
}
}
}
func (s *Sync) updatePolicyStatus() {
2020-02-29 22:39:27 +05:30
s.Cache.Mutex.Lock()
var nameToStatus = make(map[string]v1.PolicyStatus, len(s.Cache.Data))
for k, v := range s.Cache.Data {
2020-02-25 20:55:07 +05:30
nameToStatus[k] = v
}
2020-02-29 22:39:27 +05:30
s.Cache.Mutex.Unlock()
2020-02-25 20:55:07 +05:30
for policyName, status := range nameToStatus {
2020-02-29 22:39:27 +05:30
policy, err := s.PolicyStore.Get(policyName)
2020-02-25 20:55:07 +05:30
if err != nil {
continue
}
policy.Status = status
_, err = s.client.KyvernoV1().ClusterPolicies().UpdateStatus(policy)
if err != nil {
2020-02-29 22:39:27 +05:30
s.Cache.Mutex.Lock()
delete(s.Cache.Data, policyName)
s.Cache.Mutex.Unlock()
2020-02-25 20:55:07 +05:30
glog.V(4).Info(err)
}
}
}