1/*
2   Copyright The containerd Authors.
3
4   Licensed under the Apache License, Version 2.0 (the "License");
5   you may not use this file except in compliance with the License.
6   You may obtain a copy of the License at
7
8       http://www.apache.org/licenses/LICENSE-2.0
9
10   Unless required by applicable law or agreed to in writing, software
11   distributed under the License is distributed on an "AS IS" BASIS,
12   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   See the License for the specific language governing permissions and
14   limitations under the License.
15*/
16
17package server
18
19import (
20	"os"
21	"sync"
22
23	cni "github.com/containerd/go-cni"
24	"github.com/fsnotify/fsnotify"
25	"github.com/pkg/errors"
26	"github.com/sirupsen/logrus"
27)
28
29// cniNetConfSyncer is used to reload cni network conf triggered by fs change
30// events.
31type cniNetConfSyncer struct {
32	// only used for lastSyncStatus
33	sync.RWMutex
34	lastSyncStatus error
35
36	watcher   *fsnotify.Watcher
37	confDir   string
38	netPlugin cni.CNI
39	loadOpts  []cni.Opt
40}
41
42// newCNINetConfSyncer creates cni network conf syncer.
43func newCNINetConfSyncer(confDir string, netPlugin cni.CNI, loadOpts []cni.Opt) (*cniNetConfSyncer, error) {
44	watcher, err := fsnotify.NewWatcher()
45	if err != nil {
46		return nil, errors.Wrap(err, "failed to create fsnotify watcher")
47	}
48
49	if err := os.MkdirAll(confDir, 0700); err != nil {
50		return nil, errors.Wrapf(err, "failed to create cni conf dir=%s for watch", confDir)
51	}
52
53	if err := watcher.Add(confDir); err != nil {
54		return nil, errors.Wrapf(err, "failed to watch cni conf dir %s", confDir)
55	}
56
57	syncer := &cniNetConfSyncer{
58		watcher:   watcher,
59		confDir:   confDir,
60		netPlugin: netPlugin,
61		loadOpts:  loadOpts,
62	}
63
64	if err := syncer.netPlugin.Load(syncer.loadOpts...); err != nil {
65		logrus.WithError(err).Error("failed to load cni during init, please check CRI plugin status before setting up network for pods")
66		syncer.updateLastStatus(err)
67	}
68	return syncer, nil
69}
70
71// syncLoop monitors any fs change events from cni conf dir and tries to reload
72// cni configuration.
73func (syncer *cniNetConfSyncer) syncLoop() error {
74	for {
75		select {
76		case event, ok := <-syncer.watcher.Events:
77			if !ok {
78				logrus.Debugf("cni watcher channel is closed")
79				return nil
80			}
81			// Only reload config when receiving write/rename/remove
82			// events
83			//
84			// TODO(fuweid): Might only reload target cni config
85			// files to prevent no-ops.
86			if event.Op&(fsnotify.Chmod|fsnotify.Create) > 0 {
87				logrus.Debugf("ignore event from cni conf dir: %s", event)
88				continue
89			}
90			logrus.Debugf("receiving change event from cni conf dir: %s", event)
91
92			lerr := syncer.netPlugin.Load(syncer.loadOpts...)
93			if lerr != nil {
94				logrus.WithError(lerr).
95					Errorf("failed to reload cni configuration after receiving fs change event(%s)", event)
96			}
97			syncer.updateLastStatus(lerr)
98
99		case err := <-syncer.watcher.Errors:
100			if err != nil {
101				logrus.WithError(err).Error("failed to continue sync cni conf change")
102				return err
103			}
104		}
105	}
106}
107
108// lastStatus retrieves last sync status.
109func (syncer *cniNetConfSyncer) lastStatus() error {
110	syncer.RLock()
111	defer syncer.RUnlock()
112	return syncer.lastSyncStatus
113}
114
115// updateLastStatus will be called after every single cni load.
116func (syncer *cniNetConfSyncer) updateLastStatus(err error) {
117	syncer.Lock()
118	defer syncer.Unlock()
119	syncer.lastSyncStatus = err
120}
121
122// stop stops watcher in the syncLoop.
123func (syncer *cniNetConfSyncer) stop() error {
124	return syncer.watcher.Close()
125}
126