-
Notifications
You must be signed in to change notification settings - Fork 6
/
load.go
96 lines (80 loc) · 2.02 KB
/
load.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
// Copyright 2009 smallnest. All rights reserved.
// Use of this source code is governed by Apache License Version 2.0
// license that can be found in the LICENSE file.
package glean
import (
"plugin"
"reflect"
"runtime"
"github.com/smallnest/glean/log"
)
// LoadSymbol loads a plugin and gets the symbol.
// It encapsulates plugin.Open and plugin.Lookup methods to a convenient function.
// so is file path of the plugin and name is the symbol.
func LoadSymbol(so, name string) (interface{}, error) {
p, err := plugin.Open(so)
if err != nil {
log.Errorf("failed to open %s: %v", so, err)
return nil, err
}
v, err := p.Lookup(name)
if err != nil {
log.Errorf("failed to lookup %s: %v", name, err)
return nil, err
}
return v, nil
}
// Reload loads a function or a variable from the plugin and replace passed function or variable.
// If fails to load, the original function or variable won't be replaced.
func Reload(so, name string, vPtr interface{}) error {
var err error
defer func() {
if r := recover(); r != nil {
if _, ok := r.(runtime.Error); ok {
panic(r)
}
err = r.(error)
}
}()
// a Symbol is a pointer to a variable or function.
s, err := LoadSymbol(so, name)
if err != nil {
return err
}
vPtrV := reflect.ValueOf(vPtr)
if vPtrV.Kind() != reflect.Ptr {
return ErrMustBePointer
}
v := vPtrV.Elem()
if !v.CanSet() {
return ErrValueCanNotSet
}
v.Set(reflect.ValueOf(s).Elem())
return nil
}
// ReloadFromPlugin is like Reload but it loads a function or a variable from the given *plugin.Plugin.
func ReloadFromPlugin(p *plugin.Plugin, name string, vPtr interface{}) error {
var err error
defer func() {
if r := recover(); r != nil {
if _, ok := r.(runtime.Error); ok {
panic(r)
}
err = r.(error)
}
}()
s, err := p.Lookup(name)
if err != nil {
return err
}
vPtrV := reflect.ValueOf(vPtr)
if vPtrV.Kind() != reflect.Ptr {
return ErrMustBePointer
}
v := vPtrV.Elem()
if !v.CanSet() {
return ErrValueCanNotSet
}
v.Set(reflect.ValueOf(s).Elem())
return nil
}