forked from pingcap/tidb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplugin.go
373 lines (343 loc) · 9.39 KB
/
plugin.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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
// Copyright 2019 PingCAP, Inc.
//
// 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,
// See the License for the specific language governing permissions and
// limitations under the License.
package plugin
import (
"context"
"path/filepath"
gplugin "plugin"
"strconv"
"strings"
"sync/atomic"
"unsafe"
"github.com/pingcap/errors"
"github.com/pingcap/tidb/sessionctx/variable"
)
// pluginGlobal holds all global variables for plugin.
var pluginGlobal copyOnWriteContext
// copyOnWriteContext wraps a context follow COW idiom.
type copyOnWriteContext struct {
tiPlugins unsafe.Pointer // *plugins
}
// plugins collects loaded plugins info.
type plugins struct {
plugins map[Kind][]Plugin
versions map[string]uint16
dyingPlugins []Plugin
}
// clone deep copies plugins info.
func (p *plugins) clone() *plugins {
np := &plugins{
plugins: make(map[Kind][]Plugin, len(p.plugins)),
versions: make(map[string]uint16, len(p.versions)),
}
for key, value := range p.plugins {
np.plugins[key] = append([]Plugin(nil), value...)
}
for key, value := range p.versions {
np.versions[key] = value
}
for key, value := range p.dyingPlugins {
np.dyingPlugins[key] = value
}
return np
}
// add adds a plugin to loaded plugin collection.
func (p plugins) add(plugin *Plugin) {
plugins, ok := p.plugins[plugin.Kind]
if !ok {
plugins = make([]Plugin, 0)
}
plugins = append(plugins, *plugin)
p.plugins[plugin.Kind] = plugins
p.versions[plugin.Name] = plugin.Version
}
// plugins got plugin in COW context.
func (p copyOnWriteContext) plugins() *plugins {
return (*plugins)(atomic.LoadPointer(&p.tiPlugins))
}
// Config presents the init configuration for plugin framework.
type Config struct {
Plugins []string
PluginDir string
GlobalSysVar *map[string]*variable.SysVar
PluginVarNames *[]string
SkipWhenFail bool
EnvVersion map[string]uint16
}
// Plugin presents a TiDB plugin.
type Plugin struct {
*Manifest
library *gplugin.Plugin
State State
Path string
}
type validateMode int
const (
initMode validateMode = iota
reloadMode
)
func (p *Plugin) validate(ctx context.Context, tiPlugins *plugins, mode validateMode) error {
if mode == reloadMode {
var oldPlugin *Plugin
for i, item := range tiPlugins.plugins[p.Kind] {
if item.Name == p.Name {
oldPlugin = &tiPlugins.plugins[p.Kind][i]
break
}
}
if oldPlugin == nil {
return errUnsupportedReloadPlugin.GenWithStackByArgs(p.Name)
}
if len(p.SysVars) != len(oldPlugin.SysVars) {
return errUnsupportedReloadPluginVar.GenWithStackByArgs("")
}
for varName, varVal := range p.SysVars {
if oldPlugin.SysVars[varName] == nil || *oldPlugin.SysVars[varName] != *varVal {
return errUnsupportedReloadPluginVar.GenWithStackByArgs(varVal)
}
}
}
if p.RequireVersion != nil {
for component, reqVer := range p.RequireVersion {
if ver, ok := tiPlugins.versions[component]; !ok || ver < reqVer {
return errRequireVersionCheckFail.GenWithStackByArgs(p.Name, component, reqVer, ver)
}
}
}
if p.SysVars != nil {
for varName := range p.SysVars {
if !strings.HasPrefix(varName, p.Name) {
return errInvalidPluginSysVarName.GenWithStackByArgs(p.Name, varName, p.Name)
}
}
}
if p.Manifest.Validate != nil {
if err := p.Manifest.Validate(ctx, p.Manifest); err != nil {
return err
}
}
return nil
}
// Init initializes the plugin and load plugin by config param.
// This method isn't thread-safe and must be called before any other plugin operation.
func Init(ctx context.Context, cfg Config) (err error) {
tiPlugins := &plugins{
plugins: make(map[Kind][]Plugin),
versions: make(map[string]uint16),
dyingPlugins: make([]Plugin, 0),
}
// Setup component version info for plugin running env.
for component, version := range cfg.EnvVersion {
tiPlugins.versions[component] = version
}
// Load plugin dl & manifest.
for _, pluginID := range cfg.Plugins {
var pName string
pName, _, err = ID(pluginID).Decode()
if err != nil {
err = errors.Trace(err)
return
}
// Check duplicate.
_, dup := tiPlugins.versions[pName]
if dup {
if cfg.SkipWhenFail {
continue
}
err = errDuplicatePlugin.GenWithStackByArgs(pluginID)
return
}
// Load dl.
var plugin Plugin
plugin, err = loadOne(cfg.PluginDir, ID(pluginID))
if err != nil {
if cfg.SkipWhenFail {
continue
}
return
}
tiPlugins.add(&plugin)
}
// Cross validate & Load plugins.
for kind := range tiPlugins.plugins {
for i := range tiPlugins.plugins[kind] {
if err = tiPlugins.plugins[kind][i].validate(ctx, tiPlugins, initMode); err != nil {
if cfg.SkipWhenFail {
tiPlugins.plugins[kind][i].State = Disable
err = nil
continue
}
return
}
p := tiPlugins.plugins[kind][i]
if err = p.OnInit(ctx, p.Manifest); err != nil {
if cfg.SkipWhenFail {
tiPlugins.plugins[kind][i].State = Disable
err = nil
continue
}
return
}
if cfg.GlobalSysVar != nil {
for key, value := range tiPlugins.plugins[kind][i].SysVars {
(*cfg.GlobalSysVar)[key] = value
if value.Scope != variable.ScopeSession && cfg.PluginVarNames != nil {
*cfg.PluginVarNames = append(*cfg.PluginVarNames, key)
}
}
}
tiPlugins.plugins[kind][i].State = Ready
}
}
pluginGlobal = copyOnWriteContext{tiPlugins: unsafe.Pointer(tiPlugins)}
err = nil
return
}
func loadOne(dir string, pluginID ID) (plugin Plugin, err error) {
plugin.Path = filepath.Join(dir, string(pluginID)+LibrarySuffix)
plugin.library, err = gplugin.Open(plugin.Path)
if err != nil {
err = errors.Trace(err)
return
}
manifestSym, err := plugin.library.Lookup(ManifestSymbol)
if err != nil {
err = errors.Trace(err)
return
}
manifest, ok := manifestSym.(func() *Manifest)
if !ok {
err = errInvalidPluginManifest.GenWithStackByArgs(string(pluginID))
return
}
pName, pVersion, err := pluginID.Decode()
if err != nil {
err = errors.Trace(err)
return
}
plugin.Manifest = manifest()
if plugin.Name != pName {
err = errInvalidPluginName.GenWithStackByArgs(string(pluginID), plugin.Name)
return
}
if strconv.Itoa(int(plugin.Version)) != pVersion {
err = errInvalidPluginVersion.GenWithStackByArgs(string(pluginID))
return
}
return
}
// Reload hot swap a old plugin with new version.
// Limit: loaded plugins shouldn't be unload and only be mark dying.
func Reload(ctx context.Context, cfg Config, pluginID ID) (err error) {
newPlugin, err := loadOne(cfg.PluginDir, pluginID)
if err != nil {
return
}
_, err = replace(ctx, cfg, newPlugin.Name, newPlugin)
return
}
func replace(ctx context.Context, cfg Config, name string, newPlugin Plugin) (replaced bool, err error) {
oldPlugins := pluginGlobal.plugins()
if oldPlugins.versions[name] == newPlugin.Version {
replaced = false
return
}
err = newPlugin.validate(ctx, oldPlugins, reloadMode)
if err != nil {
return
}
err = newPlugin.OnInit(ctx, newPlugin.Manifest)
if err != nil {
return
}
if cfg.GlobalSysVar != nil {
for key, value := range newPlugin.SysVars {
(*cfg.GlobalSysVar)[key] = value
}
}
for {
oldPlugins = pluginGlobal.plugins()
newPlugins := oldPlugins.clone()
replaced = true
tiPluginKind := newPlugins.plugins[newPlugin.Kind]
var oldPlugin *Plugin
for i, p := range tiPluginKind {
if p.Name == name {
oldPlugin = &tiPluginKind[i]
tiPluginKind = append(tiPluginKind[:i], tiPluginKind[i+1:]...)
}
}
if oldPlugin != nil {
oldPlugin.State = Dying
newPlugins.dyingPlugins = append(newPlugins.dyingPlugins, *oldPlugin)
err = oldPlugin.OnShutdown(ctx, oldPlugin.Manifest)
if err != nil {
// When shutdown failure, the plugin is in stranger state, so make it as Dying.
return
}
}
newPlugin.State = Ready
tiPluginKind = append(tiPluginKind, newPlugin)
newPlugins.plugins[newPlugin.Kind] = tiPluginKind
newPlugins.versions[newPlugin.Name] = newPlugin.Version
if atomic.CompareAndSwapPointer(&pluginGlobal.tiPlugins, unsafe.Pointer(oldPlugins), unsafe.Pointer(newPlugins)) {
return
}
}
}
// Shutdown cleanups all plugin resources.
// Notice: it just cleanups the resource of plugin, but cannot unload plugins(limited by go plugin).
func Shutdown(ctx context.Context) {
for {
tiPlugins := pluginGlobal.plugins()
for _, plugins := range tiPlugins.plugins {
for _, p := range plugins {
p.State = Dying
if err := p.OnShutdown(ctx, p.Manifest); err != nil {
}
}
}
if atomic.CompareAndSwapPointer(&pluginGlobal.tiPlugins, unsafe.Pointer(tiPlugins), nil) {
return
}
}
}
// Get finds and returns plugin by kind and name parameters.
func Get(kind Kind, name string) *Plugin {
plugins := pluginGlobal.plugins()
if plugins == nil {
return nil
}
for _, p := range plugins.plugins[kind] {
if p.Name == name {
return &p
}
}
return nil
}
// GetByKind finds and returns plugin by kind parameters.
func GetByKind(kind Kind) []Plugin {
plugins := pluginGlobal.plugins()
if plugins == nil {
return nil
}
return plugins.plugins[kind]
}
// GetAll finds and returns all plugins.
func GetAll() map[Kind][]Plugin {
plugins := pluginGlobal.plugins()
if plugins == nil {
return nil
}
return plugins.plugins
}