/
manager.go
254 lines (218 loc) · 8.2 KB
/
manager.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
/*
Copyright 2016-2018 Mirantis
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package manager
import (
"fmt"
"strings"
"time"
"github.com/golang/glog"
"k8s.io/client-go/tools/clientcmd"
"github.com/Mirantis/virtlet/pkg/api/virtlet.k8s/v1"
"github.com/Mirantis/virtlet/pkg/diag"
"github.com/Mirantis/virtlet/pkg/fs"
"github.com/Mirantis/virtlet/pkg/image"
"github.com/Mirantis/virtlet/pkg/imagetranslation"
"github.com/Mirantis/virtlet/pkg/libvirttools"
"github.com/Mirantis/virtlet/pkg/metadata"
"github.com/Mirantis/virtlet/pkg/metadata/types"
"github.com/Mirantis/virtlet/pkg/stream"
"github.com/Mirantis/virtlet/pkg/tapmanager"
"github.com/Mirantis/virtlet/pkg/utils"
)
const (
tapManagerConnectInterval = 200 * time.Millisecond
tapManagerAttemptCount = 50
streamerSocketPath = "/var/lib/libvirt/streamer.sock"
volumePoolName = "volumes"
virtletSharedFsDir = "/var/lib/virtlet/fs"
)
// VirtletManager wraps the Virtlet's Runtime and Image CRI services,
// as well as a gRPC server that provides access to them.
type VirtletManager struct {
config *v1.VirtletConfig
metadataStore metadata.Store
fdManager tapmanager.FDManager
diagSet *diag.Set
clientCfg clientcmd.ClientConfig
virtTool *libvirttools.VirtualizationTool
imageStore image.Store
runtimeService *VirtletRuntimeService
imageService *VirtletImageService
server *Server
}
// NewVirtletManager creates a new VirtletManager.
func NewVirtletManager(config *v1.VirtletConfig, fdManager tapmanager.FDManager, clientCfg clientcmd.ClientConfig, diagSet *diag.Set) *VirtletManager {
return &VirtletManager{config: config, fdManager: fdManager, diagSet: diagSet, clientCfg: clientCfg}
}
// Run sets up the environment for the runtime and image services and
// starts the gRPC listener. It doesn't return until the server is
// stopped or an error occurs.
func (v *VirtletManager) Run() error {
var err error
if v.fdManager == nil {
client := tapmanager.NewFDClient(*v.config.FDServerSocketPath)
for i := 0; i < tapManagerAttemptCount; i++ {
if err = client.IsRunning(); err == nil {
break
}
time.Sleep(tapManagerConnectInterval)
}
if err != nil {
return fmt.Errorf("failed to connect to tapmanager: %v", err)
}
v.fdManager = client
}
v.metadataStore, err = metadata.NewStore(*v.config.DatabasePath)
if err != nil {
return fmt.Errorf("failed to create metadata store: %v", err)
}
v.diagSet.RegisterDiagSource("metadata", metadata.GetMetadataDumpSource(v.metadataStore))
downloader := image.NewDownloader(*v.config.DownloadProtocol)
v.imageStore = image.NewFileStore(*v.config.ImageDir, downloader, nil)
v.imageStore.SetRefGetter(v.metadataStore.ImagesInUse)
var translator image.Translator
if !*v.config.SkipImageTranslation {
translator = imagetranslation.GetDefaultImageTranslator(*v.config.ImageTranslationConfigsDir, *v.config.EnableRegexpImageTranslation, v.clientCfg)
} else {
translator = imagetranslation.GetEmptyImageTranslator()
}
conn, err := libvirttools.NewConnection(*v.config.LibvirtURI)
if err != nil {
return fmt.Errorf("error establishing libvirt connection: %v", err)
}
v.diagSet.RegisterDiagSource("libvirt-xml", libvirttools.NewLibvirtDiagSource(conn, conn))
virtConfig := libvirttools.VirtualizationConfig{
DisableKVM: *v.config.DisableKVM,
EnableSriov: *v.config.EnableSriov,
CPUModel: *v.config.CPUModel,
VolumePoolName: volumePoolName,
SharedFilesystemPath: virtletSharedFsDir,
KubeletRootDir: *v.config.KubeletRootDir,
}
if *v.config.RawDevices != "" {
virtConfig.RawDevices = strings.Split(*v.config.RawDevices, ",")
}
var streamServer StreamServer
if !*v.config.DisableLogging {
s, err := stream.NewServer(streamerSocketPath, v.metadataStore, *v.config.StreamPort)
if err != nil {
return fmt.Errorf("couldn't create stream server: %v", err)
}
err = s.Start()
if err != nil {
glog.Warningf("Could not start stream server: %v", err)
}
streamServer = s
virtConfig.StreamerSocketPath = streamerSocketPath
}
volSrc := libvirttools.GetDefaultVolumeSource()
v.virtTool = libvirttools.NewVirtualizationTool(
conn, conn, v.imageStore, v.metadataStore, volSrc, virtConfig,
fs.RealFileSystem, utils.DefaultCommander)
runtimeService := NewVirtletRuntimeService(v.virtTool, v.metadataStore, v.fdManager, streamServer, v.imageStore, nil)
imageService := NewVirtletImageService(v.imageStore, translator, nil)
v.server = NewServer()
v.server.Register(runtimeService, imageService)
if err := v.recoverAndGC(); err != nil {
// we consider recover / gc errors non-fatal
glog.Warning(err)
}
glog.V(1).Infof("Starting server on socket %s", *v.config.CRISocketPath)
if err = v.server.Serve(*v.config.CRISocketPath); err != nil {
return fmt.Errorf("serving failed: %v", err)
}
return nil
}
// Stop stops the gRPC listener of the VirtletManager, if it's active.
func (v *VirtletManager) Stop() {
if v.server != nil {
v.server.Stop()
}
}
// recoverAndGC performs the initial actions during VirtletManager
// startup, including recovering network namespaces and performing
// garbage collection for both libvirt and the image store.
func (v *VirtletManager) recoverAndGC() error {
var errors []string
for _, err := range v.virtTool.GarbageCollect() {
errors = append(errors, fmt.Sprintf("* error performing libvirt GC: %v", err))
}
// recover network namespace after VM GC
for _, err := range v.recoverNetworkNamespaces() {
errors = append(errors, fmt.Sprintf("* error recovering VM network namespaces: %v", err))
}
if err := v.imageStore.GC(); err != nil {
errors = append(errors, fmt.Sprintf("* error during image GC: %v", err))
}
if len(errors) == 0 {
return nil
}
return fmt.Errorf("errors encountered during recover / GC:\n%s", strings.Join(errors, "\n"))
}
// recoverNetworkNamespaces recovers all the active VM network namespaces
// from previous Virtlet run by scanning the metadata store and starting
// dhcp server for each namespace that's still active
func (v *VirtletManager) recoverNetworkNamespaces() (allErrors []error) {
sandboxes, err := v.metadataStore.ListPodSandboxes(nil)
if err != nil {
allErrors = append(allErrors, err)
return
}
OUTER:
for _, s := range sandboxes {
psi, err := s.Retrieve()
if err != nil {
allErrors = append(allErrors, fmt.Errorf("can't retrieve PodSandboxInfo for sandbox id %q: %v", s.GetID(), err))
continue
}
if psi == nil {
allErrors = append(allErrors, fmt.Errorf("inconsistent database. Found pod %q sandbox but can not retrive its metadata", s.GetID()))
continue
}
// Don't recover if sandbox is not ready
if psi.State != types.PodSandboxState_SANDBOX_READY {
continue
}
haveRunningContainers := false
containers, err := v.metadataStore.ListPodContainers(s.GetID())
if err != nil {
allErrors = append(allErrors, fmt.Errorf("can't retrieve ContainerMetadata list for pod %q: %v", s.GetID(), err))
continue
}
for _, c := range containers {
ci, err := v.virtTool.ContainerInfo(c.GetID())
if err != nil {
allErrors = append(allErrors, fmt.Errorf("can't verify container status for container %q in pod %q: %v", c.GetID(), s.GetID(), err))
continue OUTER
}
if ci.State == types.ContainerState_CONTAINER_RUNNING {
haveRunningContainers = true
}
}
if err := v.fdManager.Recover(
s.GetID(),
tapmanager.RecoverPayload{
Description: &tapmanager.PodNetworkDesc{
PodID: s.GetID(),
PodNs: psi.Config.Namespace,
PodName: psi.Config.Name,
},
ContainerSideNetwork: psi.ContainerSideNetwork,
HaveRunningContainers: haveRunningContainers,
},
); err != nil {
allErrors = append(allErrors, fmt.Errorf("error recovering netns for %q pod: %v", s.GetID(), err))
}
}
return
}