├── .gitignore ├── .travis.yml ├── LICENSE ├── Makefile ├── README.md ├── _example ├── httpserver │ ├── main.go │ ├── plugin.json │ └── plugins │ │ ├── plugin1 │ │ ├── build.sh │ │ └── main.go │ │ └── plugin2 │ │ ├── build.sh │ │ └── main.go └── test │ ├── main.go │ └── plugins │ ├── plugin1 │ ├── build.sh │ └── main.go │ └── plugin2 │ ├── build.sh │ └── main.go ├── load.go ├── load_test.go ├── log ├── default_logger.go ├── dummy_logger.go └── logger.go ├── plugin.go ├── plugin_test.go └── plugin_test.json /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.dll 4 | *.so 5 | *.dylib 6 | 7 | # Test binary, build with `go test -c` 8 | *.test 9 | 10 | # Output of the go coverage tool, specifically when used with LiteIDE 11 | *.out 12 | 13 | # Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736 14 | .glide/ 15 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | 3 | 4 | go: 5 | - 1.9.x 6 | - 1.8.x 7 | 8 | before_script: 9 | - go get -t -v github.com/smallnest/glean/... 10 | 11 | script: 12 | - go build . 13 | 14 | notifications: 15 | email: 16 | recipients: smallnest@gmail.com 17 | on_success: change 18 | on_failure: always -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | WORKDIR=`pwd` 2 | 3 | default: build 4 | 5 | install: 6 | go get github.com/smallnest/gclean 7 | 8 | vet: 9 | go vet . 10 | 11 | tools: 12 | go get -u honnef.co/go/tools/cmd/staticcheck 13 | go get -u honnef.co/go/tools/cmd/gosimple 14 | go get -u honnef.co/go/tools/cmd/unused 15 | go get -u github.com/gordonklaus/ineffassign 16 | go get -u github.com/fzipp/gocyclo 17 | go get -u github.com/golang/lint/golint 18 | 19 | lint: 20 | golint ./... 21 | 22 | staticcheck: 23 | staticcheck -ignore "$(shell cat .checkignore)" . 24 | 25 | gosimple: 26 | # gosimple -ignore "$(shell cat .gosimpleignore)" . 27 | gosimple . 28 | 29 | unused: 30 | unused . 31 | 32 | gocyclo: 33 | @ gocyclo -over 20 $(shell find . -name "*.go" |egrep -v "pb\.go|_test\.go") 34 | 35 | check: staticcheck gosimple unused gocyclo 36 | 37 | doc: 38 | godoc -http=:6060 39 | 40 | deps: 41 | go list -f '{{ join .Deps "\n"}}' . |grep "/" | grep -v "github.com/smallnest/glean"| grep "\." | sort |uniq 42 | 43 | fmt: 44 | go fmt . 45 | 46 | build: 47 | go build . 48 | 49 | test: 50 | go test -v . 51 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Glean 2 | 3 | *A go plugin framework that can reload variables and functions from plugins automatically.* 4 | 5 | 6 | [![License](https://img.shields.io/:license-apache-2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) [![GoDoc](https://godoc.org/github.com/smallnest/glean?status.png)](http://godoc.org/github.com/smallnest/glean) [![travis](https://travis-ci.org/smallnest/glean.svg?branch=master)](https://travis-ci.org/smallnest/glean) [![Go Report Card](https://goreportcard.com/badge/github.com/smallnest/glean)](https://goreportcard.com/report/github.com/smallnest/glean) 7 | 8 | 9 | ## Installation 10 | 11 | ```sh 12 | go get -u github.com/smallnest/glean 13 | ``` 14 | 15 | ## Feature 16 | 17 | - load symbol and you don't worry about errors 18 | - load/reload exported variables and funtions from plugins 19 | - watch plugins' changes and reload pointer of variables and function in applications 20 | 21 | **Notice** glean only can reload functions or variables that can be addresses. 22 | 23 | ## Examples 24 | 25 | see [Examples](https://github.com/smallnest/glean/tree/master/_example) 26 | 27 | Let's look the httpserver example to learn how to use glean. 28 | 29 | ### httpserver 30 | 31 | httpserver is a very very simple http server. 32 | 33 | A simple http server is just like this: 34 | 35 | ```go 36 | var FooHandler = func(w http.ResponseWriter, r *http.Request) { 37 | fmt.Fprint(w, "Hello, world") 38 | } 39 | 40 | http.Handle("/foo", fooHandler) 41 | 42 | log.Fatal(http.ListenAndServe(":9988", nil)) 43 | ``` 44 | 45 | Our goal is to replace fooHandler with latest code dynamically (hot fix). 46 | 47 | ```go 48 | var FooHandler = func(w http.ResponseWriter, r *http.Request) { 49 | fmt.Fprint(w, "Hello, gp") 50 | } 51 | ``` 52 | 53 | No need to restart this server. 54 | 55 | **step1:** build the two plugin 56 | 57 | enter `_example/httpserver/plugins/plugin1` and `_example/httpserver/plugins/plugin2`, and run the `build.sh` to generate the so file. 58 | 59 | Currently plugin supports linux and MacOS. 60 | 61 | **step2:** modify the server implementation 62 | 63 | ```go 64 | package main 65 | 66 | import ( 67 | "log" 68 | "net/http" 69 | 70 | "github.com/smallnest/glean" 71 | ) 72 | 73 | func main() { 74 | g := glean.New("plugin.json") 75 | err := g.LoadConfig() 76 | if err != nil { 77 | panic(err) 78 | } 79 | 80 | var fooHandler func(w http.ResponseWriter, r *http.Request) 81 | 82 | err = g.ReloadAndWatch("FooHandlerID", &fooHandler) 83 | 84 | if err != nil { 85 | panic(err) 86 | } 87 | 88 | http.HandleFunc("/foo", WarpFuncPtr(&fooHandler)) 89 | 90 | log.Fatal(http.ListenAndServe(":9988", nil)) 91 | } 92 | 93 | func WarpFuncPtr(fn *func(w http.ResponseWriter, r *http.Request)) func(w http.ResponseWriter, r *http.Request) { 94 | return func(w http.ResponseWriter, r *http.Request) { 95 | (*fn)(w, r) 96 | } 97 | } 98 | ``` 99 | 100 | Firstly create the Glean instance and load config from given file. 101 | And then use `ReloadAndWatch` to load fooHandler and begin to watch its changes. 102 | At last use WarpFuncPtr to wrap fooHandler as a HandleFunc. 103 | 104 | Run `go run main.go` to start this server, use a browser to visit "http://locakhost:9988/foo" and you will see `hello world` 105 | 106 | Change the config file `plugin.json` and replace `"file": "plugins/plugin1/plugin1.so"` with : 107 | 108 | ``` 109 | "file": "plugins/plugin2/plugin2.so", 110 | ``` 111 | 112 | Browser the prior location and you will see `hello gp`. 113 | -------------------------------------------------------------------------------- /_example/httpserver/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | "net/http" 6 | 7 | "github.com/smallnest/glean" 8 | ) 9 | 10 | func main() { 11 | g := glean.New("plugin.json") 12 | err := g.LoadConfig() 13 | if err != nil { 14 | panic(err) 15 | } 16 | 17 | var fooHandler func(w http.ResponseWriter, r *http.Request) 18 | 19 | err = g.ReloadAndWatch("FooHandlerID", &fooHandler) 20 | 21 | if err != nil { 22 | panic(err) 23 | } 24 | 25 | http.HandleFunc("/foo", WarpFuncPtr(&fooHandler)) 26 | 27 | log.Fatal(http.ListenAndServe(":9988", nil)) 28 | } 29 | 30 | func WarpFuncPtr(fn *func(w http.ResponseWriter, r *http.Request)) func(w http.ResponseWriter, r *http.Request) { 31 | return func(w http.ResponseWriter, r *http.Request) { 32 | (*fn)(w, r) 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /_example/httpserver/plugin.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "id": "FooHandlerID", 4 | "file": "plugins/plugin1/plugin1.so", 5 | "name": "FooHandler", 6 | "version": "1.0" 7 | } 8 | ] 9 | -------------------------------------------------------------------------------- /_example/httpserver/plugins/plugin1/build.sh: -------------------------------------------------------------------------------- 1 | go build -ldflags "-pluginpath=plugin/hot-$(uuidgen)" -buildmode=plugin -o plugin1.so main.go -------------------------------------------------------------------------------- /_example/httpserver/plugins/plugin1/main.go: -------------------------------------------------------------------------------- 1 | // Copyright 2009 smallnest. All rights reserved. 2 | // Use of this source code is governed by Apache License Version 2.0 3 | // license that can be found in the LICENSE file. 4 | 5 | package main 6 | 7 | import ( 8 | "fmt" 9 | "net/http" 10 | ) 11 | 12 | var FooHandler = func(w http.ResponseWriter, r *http.Request) { 13 | fmt.Fprint(w, "Hello, world") 14 | } 15 | -------------------------------------------------------------------------------- /_example/httpserver/plugins/plugin2/build.sh: -------------------------------------------------------------------------------- 1 | go build -ldflags "-pluginpath=plugin/hot-$(uuidgen)" -buildmode=plugin -o plugin2.so main.go -------------------------------------------------------------------------------- /_example/httpserver/plugins/plugin2/main.go: -------------------------------------------------------------------------------- 1 | // Copyright 2009 smallnest. All rights reserved. 2 | // Use of this source code is governed by Apache License Version 2.0 3 | // license that can be found in the LICENSE file. 4 | 5 | package main 6 | 7 | import ( 8 | "fmt" 9 | "net/http" 10 | ) 11 | 12 | var FooHandler = func(w http.ResponseWriter, r *http.Request) { 13 | fmt.Fprint(w, "Hello, gp") 14 | } 15 | -------------------------------------------------------------------------------- /_example/test/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "time" 6 | 7 | "github.com/smallnest/glean" 8 | "github.com/smallnest/logi" 9 | ) 10 | 11 | type AddFunc func(x, y int) int 12 | 13 | // test loading functions 14 | func testLoad() { 15 | var fn AddFunc 16 | 17 | err := glean.Reload("plugins/plugin1/plugin1.so", "Add", &fn) 18 | if err != nil { 19 | fmt.Println(err) 20 | } else { 21 | fmt.Printf("using plugin1: 1+2 = %d\n", fn(1, 2)) 22 | } 23 | 24 | err = glean.Reload("plugins/plugin2/plugin2.so", "Add", &fn) 25 | if err != nil { 26 | fmt.Println(err) 27 | } else { 28 | fmt.Printf("using plugin2: 1+2 = %d\n", fn(1, 2)) 29 | } 30 | 31 | // or 32 | 33 | f, err := glean.LoadSymbol("plugins/plugin1/p1.so", "Add") 34 | if err != nil { 35 | fmt.Println(err) 36 | } else { 37 | fn = f.(AddFunc) 38 | fmt.Printf("using plugin1: 1+2 = %d\n", fn(1, 2)) 39 | } 40 | 41 | f, err = glean.LoadSymbol("plugins/plugin2/p2.so", "Add") 42 | if err != nil { 43 | fmt.Println(err) 44 | } else { 45 | fn = f.(AddFunc) 46 | fmt.Printf("using plugin2: 1+2 = %d\n", fn(1, 2)) 47 | } 48 | 49 | } 50 | 51 | // load plugins that has the same location. 52 | func testReplacePlugin() { 53 | var fn AddFunc 54 | 55 | err := glean.Reload("plugins/plugin1/plugin1.so", "Add", &fn) 56 | if err != nil { 57 | fmt.Println(err) 58 | } else { 59 | fmt.Printf("using plugin1: 1+2 = %d\n", fn(1, 2)) 60 | } 61 | 62 | time.Sleep(time.Minute) 63 | 64 | err = glean.Reload("plugins/plugin1/plugin1.so", "Add", &fn) 65 | if err != nil { 66 | fmt.Println(err) 67 | } else { 68 | fmt.Printf("using plugin1: 1+2 = %d\n", fn(1, 2)) 69 | } 70 | 71 | } 72 | 73 | func main() { 74 | var v int 75 | 76 | logi.SetLogger(&logi.DummyLogger{}) 77 | 78 | err := glean.Reload("plugins/plugin1/plugin1.so", "V", &v) 79 | if err != nil { 80 | fmt.Println(err) 81 | } else { 82 | fmt.Printf("using plugin1: value = %d\n", v) 83 | } 84 | 85 | err = glean.Reload("plugins/plugin2/plugin2.so", "V", &v) 86 | if err != nil { 87 | fmt.Println(err) 88 | } else { 89 | fmt.Printf("using plugin2: value = %d\n", v) 90 | } 91 | 92 | // or 93 | 94 | vv, err := glean.LoadSymbol("plugins/plugin1/plugin1.so", "V") 95 | if err != nil { 96 | fmt.Println(err) 97 | } else { 98 | fmt.Printf("using plugin1: value = %v\n", *(vv.(*int))) 99 | } 100 | 101 | vv, err = glean.LoadSymbol("plugins/plugin2/plugin2.so", "V") 102 | if err != nil { 103 | fmt.Println(err) 104 | } else { 105 | fmt.Printf("using plugin2: value = %v\n", *(vv.(*int))) 106 | } 107 | 108 | } 109 | -------------------------------------------------------------------------------- /_example/test/plugins/plugin1/build.sh: -------------------------------------------------------------------------------- 1 | go build -ldflags "-pluginpath=plugin/hot-$(uuidgen)" -buildmode=plugin -o plugin1.so main.go -------------------------------------------------------------------------------- /_example/test/plugins/plugin1/main.go: -------------------------------------------------------------------------------- 1 | // Copyright 2009 smallnest. All rights reserved. 2 | // Use of this source code is governed by Apache License Version 2.0 3 | // license that can be found in the LICENSE file. 4 | 5 | package main 6 | 7 | import "C" 8 | 9 | var V = 10 10 | 11 | var v = 10 12 | 13 | func Add(x, y int) int { 14 | return x + y 15 | } 16 | -------------------------------------------------------------------------------- /_example/test/plugins/plugin2/build.sh: -------------------------------------------------------------------------------- 1 | go build -ldflags "-pluginpath=plugin/hot-$(uuidgen)" -buildmode=plugin -o plugin2.so main.go -------------------------------------------------------------------------------- /_example/test/plugins/plugin2/main.go: -------------------------------------------------------------------------------- 1 | // Copyright 2009 smallnest. All rights reserved. 2 | // Use of this source code is governed by Apache License Version 2.0 3 | // license that can be found in the LICENSE file. 4 | 5 | package main 6 | 7 | import "C" 8 | 9 | var V = 100 10 | 11 | var v = 10 12 | 13 | func Add(x, y int) int { 14 | return (x + y) * 10 15 | } 16 | -------------------------------------------------------------------------------- /load.go: -------------------------------------------------------------------------------- 1 | // Copyright 2009 smallnest. All rights reserved. 2 | // Use of this source code is governed by Apache License Version 2.0 3 | // license that can be found in the LICENSE file. 4 | 5 | package glean 6 | 7 | import ( 8 | "plugin" 9 | "reflect" 10 | "runtime" 11 | 12 | "github.com/smallnest/glean/log" 13 | ) 14 | 15 | // LoadSymbol loads a plugin and gets the symbol. 16 | // It encapsulates plugin.Open and plugin.Lookup methods to a convenient function. 17 | // so is file path of the plugin and name is the symbol. 18 | func LoadSymbol(so, name string) (interface{}, error) { 19 | p, err := plugin.Open(so) 20 | if err != nil { 21 | log.Errorf("failed to open %s: %v", so, err) 22 | return nil, err 23 | } 24 | v, err := p.Lookup(name) 25 | if err != nil { 26 | log.Errorf("failed to lookup %s: %v", name, err) 27 | return nil, err 28 | } 29 | 30 | return v, nil 31 | } 32 | 33 | // Reload loads a function or a variable from the plugin and replace passed function or variable. 34 | // If fails to load, the original function or variable won't be replaced. 35 | func Reload(so, name string, vPtr interface{}) error { 36 | var err error 37 | defer func() { 38 | if r := recover(); r != nil { 39 | if _, ok := r.(runtime.Error); ok { 40 | panic(r) 41 | } 42 | err = r.(error) 43 | } 44 | }() 45 | 46 | // a Symbol is a pointer to a variable or function. 47 | s, err := LoadSymbol(so, name) 48 | if err != nil { 49 | return err 50 | } 51 | 52 | vPtrV := reflect.ValueOf(vPtr) 53 | if vPtrV.Kind() != reflect.Ptr { 54 | return ErrMustBePointer 55 | } 56 | 57 | v := vPtrV.Elem() 58 | 59 | if !v.CanSet() { 60 | return ErrValueCanNotSet 61 | } 62 | 63 | v.Set(reflect.ValueOf(s).Elem()) 64 | return nil 65 | } 66 | 67 | // ReloadFromPlugin is like Reload but it loads a function or a variable from the given *plugin.Plugin. 68 | func ReloadFromPlugin(p *plugin.Plugin, name string, vPtr interface{}) error { 69 | var err error 70 | defer func() { 71 | if r := recover(); r != nil { 72 | if _, ok := r.(runtime.Error); ok { 73 | panic(r) 74 | } 75 | err = r.(error) 76 | } 77 | }() 78 | 79 | s, err := p.Lookup(name) 80 | if err != nil { 81 | return err 82 | } 83 | 84 | vPtrV := reflect.ValueOf(vPtr) 85 | if vPtrV.Kind() != reflect.Ptr { 86 | return ErrMustBePointer 87 | } 88 | 89 | v := vPtrV.Elem() 90 | if !v.CanSet() { 91 | return ErrValueCanNotSet 92 | } 93 | 94 | v.Set(reflect.ValueOf(s).Elem()) 95 | return nil 96 | } 97 | -------------------------------------------------------------------------------- /load_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2009 smallnest. All rights reserved. 2 | // Use of this source code is governed by Apache License Version 2.0 3 | // license that can be found in the LICENSE file. 4 | 5 | package glean 6 | 7 | import ( 8 | "plugin" 9 | "testing" 10 | 11 | "github.com/smallnest/glean/log" 12 | ) 13 | 14 | func TestLoadSymbol(t *testing.T) { 15 | log.SetDummyLogger() 16 | 17 | type args struct { 18 | so string 19 | name string 20 | } 21 | tests := []struct { 22 | name string 23 | args args 24 | want interface{} 25 | wantErr bool 26 | }{ 27 | { 28 | "Add", 29 | args{ 30 | "_example/test/plugins/plugin1/plugin1.so", 31 | "Add", 32 | }, 33 | nil, 34 | false, 35 | }, 36 | { 37 | "v", 38 | args{ 39 | "_example/test/plugins/plugin1/plugin1.so", 40 | "v", 41 | }, 42 | nil, 43 | true, 44 | }, 45 | { 46 | "nonExisted", 47 | args{ 48 | "_example/test/plugins/pluginabc/plugin1.so", 49 | "Add", 50 | }, 51 | nil, 52 | true, 53 | }, 54 | } 55 | for _, tt := range tests { 56 | t.Run(tt.name, func(t *testing.T) { 57 | got, err := LoadSymbol(tt.args.so, tt.args.name) 58 | if (err != nil) != tt.wantErr { 59 | t.Errorf("LoadSymbol() error = %v, wantErr %v", err, tt.wantErr) 60 | return 61 | } 62 | if tt.wantErr && got != nil { 63 | t.Errorf("LoadSymbol() want nil but got: %v", got) 64 | } 65 | }) 66 | } 67 | } 68 | 69 | func TestReload(t *testing.T) { 70 | var fn func(x, y int) int 71 | var v int 72 | 73 | type args struct { 74 | so string 75 | name string 76 | vPtr interface{} 77 | } 78 | tests := []struct { 79 | name string 80 | args args 81 | wantErr bool 82 | }{ 83 | { 84 | "Add", 85 | args{ 86 | "_example/test/plugins/plugin1/plugin1.so", 87 | "Add", 88 | &fn, 89 | }, 90 | false, 91 | }, 92 | { 93 | "V", 94 | args{ 95 | "_example/test/plugins/plugin1/plugin1.so", 96 | "V", 97 | &v, 98 | }, 99 | false, 100 | }, 101 | { 102 | "v", 103 | args{ 104 | "_example/test/plugins/plugin1/plugin1.so", 105 | "v", 106 | &v, 107 | }, 108 | true, 109 | }, 110 | { 111 | "nonExisted", 112 | args{ 113 | "_example/test/plugins/pluginabc/plugin1.so", 114 | "Add", 115 | &fn, 116 | }, 117 | true, 118 | }, 119 | } 120 | for _, tt := range tests { 121 | t.Run(tt.name, func(t *testing.T) { 122 | if err := Reload(tt.args.so, tt.args.name, tt.args.vPtr); (err != nil) != tt.wantErr { 123 | t.Errorf("Reload() error = %v, wantErr %v", err, tt.wantErr) 124 | } 125 | }) 126 | } 127 | } 128 | 129 | func TestReloadFromPlugin(t *testing.T) { 130 | var fn func(x, y int) int 131 | var v int 132 | 133 | p, err := plugin.Open("_example/test/plugins/plugin1/plugin1.so") 134 | if err != nil { 135 | t.Fatalf("failed to open: %v", err) 136 | } 137 | type args struct { 138 | p *plugin.Plugin 139 | name string 140 | vPtr interface{} 141 | } 142 | tests := []struct { 143 | name string 144 | args args 145 | wantErr bool 146 | }{ 147 | { 148 | "Add", 149 | args{ 150 | p, 151 | "Add", 152 | &fn, 153 | }, 154 | false, 155 | }, 156 | { 157 | "V", 158 | args{ 159 | p, 160 | "V", 161 | &v, 162 | }, 163 | false, 164 | }, 165 | { 166 | "v", 167 | args{ 168 | p, 169 | "v", 170 | &v, 171 | }, 172 | true, 173 | }, 174 | } 175 | for _, tt := range tests { 176 | t.Run(tt.name, func(t *testing.T) { 177 | if err := ReloadFromPlugin(tt.args.p, tt.args.name, tt.args.vPtr); (err != nil) != tt.wantErr { 178 | t.Errorf("ReloadFromPlugin() error = %v, wantErr %v", err, tt.wantErr) 179 | } 180 | }) 181 | } 182 | } 183 | -------------------------------------------------------------------------------- /log/default_logger.go: -------------------------------------------------------------------------------- 1 | package log 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "os" 7 | ) 8 | 9 | type defaultLogger struct { 10 | *log.Logger 11 | } 12 | 13 | func (l *defaultLogger) Debug(v ...interface{}) { 14 | l.Output(calldepth, header("DEBUG", fmt.Sprint(v...))) 15 | } 16 | 17 | func (l *defaultLogger) Debugf(format string, v ...interface{}) { 18 | l.Output(calldepth, header("DEBUG", fmt.Sprintf(format, v...))) 19 | } 20 | 21 | func (l *defaultLogger) Info(v ...interface{}) { 22 | l.Output(calldepth, header("INFO ", fmt.Sprint(v...))) 23 | } 24 | 25 | func (l *defaultLogger) Infof(format string, v ...interface{}) { 26 | l.Output(calldepth, header("INFO ", fmt.Sprintf(format, v...))) 27 | } 28 | 29 | func (l *defaultLogger) Warn(v ...interface{}) { 30 | l.Output(calldepth, header("WARN ", fmt.Sprint(v...))) 31 | } 32 | 33 | func (l *defaultLogger) Warnf(format string, v ...interface{}) { 34 | l.Output(calldepth, header("WARN ", fmt.Sprintf(format, v...))) 35 | } 36 | 37 | func (l *defaultLogger) Error(v ...interface{}) { 38 | l.Output(calldepth, header("ERROR", fmt.Sprint(v...))) 39 | } 40 | 41 | func (l *defaultLogger) Errorf(format string, v ...interface{}) { 42 | l.Output(calldepth, header("ERROR", fmt.Sprintf(format, v...))) 43 | } 44 | 45 | func (l *defaultLogger) Fatal(v ...interface{}) { 46 | l.Output(calldepth, header("FATAL", fmt.Sprint(v...))) 47 | os.Exit(1) 48 | } 49 | 50 | func (l *defaultLogger) Fatalf(format string, v ...interface{}) { 51 | l.Output(calldepth, header("FATAL", fmt.Sprintf(format, v...))) 52 | os.Exit(1) 53 | } 54 | 55 | func (l *defaultLogger) Panic(v ...interface{}) { 56 | l.Logger.Panic(v) 57 | } 58 | 59 | func (l *defaultLogger) Panicf(format string, v ...interface{}) { 60 | l.Logger.Panicf(format, v...) 61 | } 62 | 63 | func header(lvl, msg string) string { 64 | return fmt.Sprintf("%s: %s", lvl, msg) 65 | } 66 | -------------------------------------------------------------------------------- /log/dummy_logger.go: -------------------------------------------------------------------------------- 1 | package log 2 | 3 | type dummyLogger struct{} 4 | 5 | func (l *dummyLogger) Debug(v ...interface{}) { 6 | } 7 | 8 | func (l *dummyLogger) Debugf(format string, v ...interface{}) { 9 | } 10 | 11 | func (l *dummyLogger) Info(v ...interface{}) { 12 | } 13 | 14 | func (l *dummyLogger) Infof(format string, v ...interface{}) { 15 | } 16 | 17 | func (l *dummyLogger) Warn(v ...interface{}) { 18 | } 19 | 20 | func (l *dummyLogger) Warnf(format string, v ...interface{}) { 21 | } 22 | 23 | func (l *dummyLogger) Error(v ...interface{}) { 24 | } 25 | 26 | func (l *dummyLogger) Errorf(format string, v ...interface{}) { 27 | } 28 | 29 | func (l *dummyLogger) Fatal(v ...interface{}) { 30 | } 31 | 32 | func (l *dummyLogger) Fatalf(format string, v ...interface{}) { 33 | } 34 | 35 | func (l *dummyLogger) Panic(v ...interface{}) { 36 | } 37 | 38 | func (l *dummyLogger) Panicf(format string, v ...interface{}) { 39 | } 40 | -------------------------------------------------------------------------------- /log/logger.go: -------------------------------------------------------------------------------- 1 | package log 2 | 3 | import ( 4 | "log" 5 | "os" 6 | ) 7 | 8 | const ( 9 | calldepth = 3 10 | ) 11 | 12 | var l Logger = &defaultLogger{log.New(os.Stderr, "", log.LstdFlags|log.Lshortfile)} 13 | 14 | type Logger interface { 15 | Debug(v ...interface{}) 16 | Debugf(format string, v ...interface{}) 17 | 18 | Info(v ...interface{}) 19 | Infof(format string, v ...interface{}) 20 | 21 | Warn(v ...interface{}) 22 | Warnf(format string, v ...interface{}) 23 | 24 | Error(v ...interface{}) 25 | Errorf(format string, v ...interface{}) 26 | 27 | Fatal(v ...interface{}) 28 | Fatalf(format string, v ...interface{}) 29 | 30 | Panic(v ...interface{}) 31 | Panicf(format string, v ...interface{}) 32 | } 33 | 34 | func SetLogger(logger Logger) { 35 | l = logger 36 | } 37 | 38 | func SetDummyLogger() { 39 | l = &dummyLogger{} 40 | } 41 | 42 | func Debug(v ...interface{}) { 43 | l.Debug(v...) 44 | } 45 | func Debugf(format string, v ...interface{}) { 46 | l.Debugf(format, v...) 47 | } 48 | 49 | func Info(v ...interface{}) { 50 | l.Info(v...) 51 | } 52 | func Infof(format string, v ...interface{}) { 53 | l.Infof(format, v...) 54 | } 55 | 56 | func Warn(v ...interface{}) { 57 | l.Warn(v...) 58 | } 59 | func Warnf(format string, v ...interface{}) { 60 | l.Warnf(format, v...) 61 | } 62 | 63 | func Error(v ...interface{}) { 64 | l.Error(v...) 65 | } 66 | func Errorf(format string, v ...interface{}) { 67 | l.Errorf(format, v...) 68 | } 69 | 70 | func Fatal(v ...interface{}) { 71 | l.Fatal(v...) 72 | } 73 | func Fatalf(format string, v ...interface{}) { 74 | l.Fatalf(format, v...) 75 | } 76 | 77 | func Panic(v ...interface{}) { 78 | l.Panic(v...) 79 | } 80 | func Panicf(format string, v ...interface{}) { 81 | l.Panicf(format, v...) 82 | } 83 | -------------------------------------------------------------------------------- /plugin.go: -------------------------------------------------------------------------------- 1 | // Copyright 2009 smallnest. All rights reserved. 2 | // Use of this source code is governed by Apache License Version 2.0 3 | // license that can be found in the LICENSE file. 4 | 5 | package glean 6 | 7 | import ( 8 | "encoding/json" 9 | "errors" 10 | "io/ioutil" 11 | "plugin" 12 | "reflect" 13 | "sync" 14 | 15 | multierror "github.com/hashicorp/go-multierror" 16 | "github.com/smallnest/glean/log" 17 | fsnotify "gopkg.in/fsnotify.v1" 18 | ) 19 | 20 | var ( 21 | // ErrItemHasNotConfigured the plugin item has not been configured. 22 | ErrItemHasNotConfigured = errors.New("pluginItem is not configured") 23 | // ErrClosed glean instance has been closed. 24 | ErrClosed = errors.New("glean has been closed") 25 | // ErrValueCanNotSet the object can not be set. See https://golang.org/pkg/reflect/#Value.CanSet. 26 | ErrValueCanNotSet = errors.New("the object can't be addressable and can not be set") 27 | // ErrMustBePointer the object (function or variable) must be pointer. 28 | ErrMustBePointer = errors.New("the function or variable must be pointer") 29 | ) 30 | 31 | // PluginItem is a configured item that can be reloaded. 32 | type PluginItem struct { 33 | // File file path of this plugin. 34 | File string `json:"file"` 35 | // ID is an unique string for this item. 36 | ID string `json:"id"` 37 | // Name is name of the symbol. Notice id is unique but names may be duplicated in different plugins. 38 | Name string `json:"name"` 39 | // Version is version of the plugin for tracing and upgrade. 40 | Version string `json:"version"` 41 | // Cached points the opened plugin. 42 | Cached *plugin.Plugin `json:"-"` 43 | // v is the function or variable that can be reloaded. 44 | v interface{} 45 | } 46 | 47 | // Glean is a manager that manages all configured plugins and reloaded objects. 48 | type Glean struct { 49 | configFile string 50 | pluginItems []*PluginItem 51 | idMap map[string]*PluginItem 52 | watched map[string]bool 53 | mu sync.RWMutex 54 | done chan bool 55 | closed bool 56 | } 57 | 58 | // New returns a new Glean. 59 | func New(configFile string) *Glean { 60 | return &Glean{ 61 | configFile: configFile, 62 | watched: make(map[string]bool), 63 | idMap: make(map[string]*PluginItem), 64 | done: make(chan bool), 65 | } 66 | } 67 | 68 | // Close closes Glean and stop watching. 69 | func (g *Glean) Close() { 70 | g.mu.Lock() 71 | if !g.closed { 72 | g.closed = true 73 | close(g.done) 74 | g.pluginItems = []*PluginItem{} 75 | g.idMap = nil 76 | g.watched = nil 77 | } 78 | g.mu.Unlock() 79 | } 80 | 81 | // LoadConfig loads plugins from the configured file. 82 | func (g *Glean) LoadConfig() (err error) { 83 | buf, err := ioutil.ReadFile(g.configFile) 84 | if err != nil { 85 | log.Errorf("failed to load %s: %v", g.configFile, err) 86 | return err 87 | } 88 | 89 | g.mu.Lock() 90 | defer g.mu.Unlock() 91 | 92 | err = json.Unmarshal(buf, &(g.pluginItems)) 93 | if err != nil { 94 | log.Errorf("failed to unmarshal %s: %v", g.configFile, err) 95 | return err 96 | } 97 | 98 | // initial plugin 99 | for _, item := range g.pluginItems { 100 | pp, err := plugin.Open(item.File) 101 | if err != nil { 102 | log.Errorf("failed to load %s: %v", item.Name, err) 103 | return err 104 | } 105 | 106 | item.Cached = pp 107 | g.idMap[item.ID] = item 108 | } 109 | 110 | // watch changes 111 | err = g.startWatch() 112 | return 113 | } 114 | 115 | // start to watch changes of config changes 116 | func (g *Glean) startWatch() error { 117 | if g.closed { 118 | return ErrClosed 119 | } 120 | 121 | watcher, err := fsnotify.NewWatcher() 122 | if err != nil { 123 | log.Fatal(err) 124 | return err 125 | } 126 | 127 | err = watcher.Add(g.configFile) 128 | if err != nil { 129 | watcher.Close() 130 | log.Fatal(err) 131 | } 132 | 133 | go func() { 134 | watch: 135 | for { 136 | select { 137 | case event := <-watcher.Events: 138 | log.Info("watch event:", event) 139 | if event.Op&fsnotify.Write == fsnotify.Write || event.Op&fsnotify.Rename == fsnotify.Rename { 140 | log.Infof("config file %s is modified", event.Name) 141 | g.checkChanges() // the config file has been modified 142 | } 143 | case err := <-watcher.Errors: 144 | log.Errorf("watcher error: %v", err) 145 | case <-g.done: 146 | break watch 147 | } 148 | } 149 | }() 150 | 151 | return err 152 | } 153 | 154 | func (g *Glean) checkChanges() { 155 | buf, err := ioutil.ReadFile(g.configFile) 156 | if err != nil { 157 | log.Errorf("failed to load %s: %v", g.configFile, err) 158 | return 159 | } 160 | 161 | var latestPluginItems []*PluginItem 162 | 163 | err = json.Unmarshal(buf, &(latestPluginItems)) 164 | if err != nil { 165 | log.Errorf("failed to unmarshal %s: %v", g.configFile, err) 166 | return 167 | } 168 | 169 | g.mu.Lock() 170 | defer g.mu.Unlock() 171 | 172 | currentPluginItems := g.pluginItems 173 | added, changed, removed := diffPlugins(currentPluginItems, latestPluginItems) 174 | g.pluginItems = latestPluginItems 175 | 176 | for _, item := range removed { 177 | delete(g.idMap, item.ID) 178 | delete(g.watched, item.ID) 179 | } 180 | 181 | // update changed 182 | for _, item := range changed { 183 | pp, e := plugin.Open(item.File) 184 | if e != nil { 185 | log.Errorf("failed to load %s: %v", item.Name, e) 186 | err = multierror.Append(err, e) 187 | } 188 | item.Cached = pp 189 | item.v = g.idMap[item.ID].v 190 | g.idMap[item.ID] = item 191 | } 192 | 193 | // add added 194 | for _, item := range added { 195 | pp, e := plugin.Open(item.File) 196 | if e != nil { 197 | log.Errorf("failed to load %s: %v", item.Name, e) 198 | err = multierror.Append(err, e) 199 | } 200 | item.Cached = pp 201 | g.idMap[item.ID] = item 202 | } 203 | 204 | //reload all variables 205 | for _, item := range changed { 206 | watchID := g.watched[item.ID] 207 | 208 | if watchID { 209 | e := ReloadFromPlugin(item.Cached, item.Name, item.v) 210 | if e != nil { 211 | log.Errorf("failed to reload %s, %s from %s: %v", item.ID, item.Name, item.File, err) 212 | err = multierror.Append(err, e) 213 | } else { 214 | log.Infof("succeeded to reload %s, %s from %s", item.ID, item.Name, item.File) 215 | } 216 | } 217 | } 218 | } 219 | 220 | func diffPlugins(currentPluginItems, latestPluginItems []*PluginItem) (added, changed, removed []*PluginItem) { 221 | latestM := make(map[string]*PluginItem) 222 | for _, item := range latestPluginItems { 223 | latestM[item.ID] = item 224 | } 225 | 226 | currentM := make(map[string]*PluginItem) 227 | for _, item := range currentPluginItems { 228 | currentM[item.ID] = item 229 | } 230 | 231 | for _, item := range latestPluginItems { 232 | if i, exist := currentM[item.ID]; exist { 233 | if item.File != i.File { 234 | changed = append(changed, item) 235 | } 236 | } else { 237 | added = append(added, item) 238 | } 239 | } 240 | 241 | for _, item := range currentPluginItems { 242 | if _, exist := latestM[item.ID]; !exist { 243 | removed = append(removed, item) 244 | } 245 | } 246 | 247 | return 248 | } 249 | 250 | // Reload loads an variable or function from configured plugins. 251 | func (g *Glean) Reload(id string, vPtr interface{}) error { 252 | if g.closed { 253 | return ErrClosed 254 | } 255 | 256 | g.mu.RLock() 257 | item := g.idMap[id] 258 | g.mu.RUnlock() 259 | 260 | if item == nil { 261 | return ErrItemHasNotConfigured 262 | } 263 | 264 | return ReloadFromPlugin(item.Cached, item.Name, vPtr) 265 | } 266 | 267 | // Watch watches plugin changes and reload given function/variable automatically. 268 | func (g *Glean) Watch(id string, vPtr interface{}) { 269 | g.mu.Lock() 270 | g.watched[id] = true 271 | item := g.idMap[id] 272 | g.mu.Unlock() 273 | if item != nil { 274 | item.v = vPtr 275 | } 276 | } 277 | 278 | // ReloadAndWatch loads an variable or function from plugins and begin to watch. 279 | func (g *Glean) ReloadAndWatch(id string, vPtr interface{}) error { 280 | err := g.Reload(id, vPtr) 281 | if err != nil { 282 | return err 283 | } 284 | 285 | g.Watch(id, vPtr) 286 | 287 | return nil 288 | } 289 | 290 | // GetObjectByID gets the variable or function by ID. 291 | func (g *Glean) GetObjectByID(id string) (v interface{}) { 292 | g.mu.RLock() 293 | v = g.idMap[id].v 294 | g.mu.RUnlock() 295 | return v 296 | } 297 | 298 | // GetSymbolByID gets the variable or function by ID from cached plugin. 299 | func (g *Glean) GetSymbolByID(id string) (v interface{}, err error) { 300 | g.mu.RLock() 301 | v, err = g.idMap[id].Cached.Lookup(g.idMap[id].Name) 302 | g.mu.RUnlock() 303 | return v, err 304 | } 305 | 306 | // FindAllPlugins gets all IDs that implements interface t. 307 | func (g *Glean) FindAllPlugins(t reflect.Type) ([]string, error) { 308 | if t.Kind() != reflect.Interface { 309 | return nil, errors.New("parameter i is not an interface type") 310 | } 311 | 312 | var ids []string 313 | g.mu.RLock() 314 | defer g.mu.RUnlock() 315 | 316 | for id, item := range g.idMap { 317 | if item.v != nil { 318 | if reflect.TypeOf(item.v).Implements(t) { 319 | ids = append(ids, id) 320 | } 321 | } else { 322 | s, err := item.Cached.Lookup(item.Name) 323 | if err == nil && reflect.ValueOf(s).Elem().Type().Implements(t) { 324 | ids = append(ids, id) 325 | } 326 | } 327 | } 328 | 329 | return ids, nil 330 | } 331 | -------------------------------------------------------------------------------- /plugin_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2009 smallnest. All rights reserved. 2 | // Use of this source code is governed by Apache License Version 2.0 3 | // license that can be found in the LICENSE file. 4 | 5 | package glean 6 | 7 | import "testing" 8 | import "github.com/smallnest/glean/log" 9 | 10 | func TestGP_LoadConfig(t *testing.T) { 11 | log.SetDummyLogger() 12 | 13 | tests := []struct { 14 | name string 15 | g *Glean 16 | wantErr bool 17 | }{ 18 | { 19 | name: "normal", 20 | g: New("plugin_test.json"), 21 | wantErr: false, 22 | }, 23 | } 24 | for _, tt := range tests { 25 | t.Run(tt.name, func(t *testing.T) { 26 | if err := tt.g.LoadConfig(); (err != nil) != tt.wantErr { 27 | t.Errorf("Glean.LoadConfig() error = %v, wantErr %v", err, tt.wantErr) 28 | } 29 | 30 | var fn func(x, y int) int 31 | var v int 32 | 33 | err := tt.g.Reload("EF5A35EC-46EB-4E62-8251-78F1A49FA7DC", &fn) 34 | if err != nil { 35 | t.Errorf("failed to reload fn: %v", err) 36 | } 37 | 38 | err = tt.g.Reload("2E8FD057-99EC-41B9-8172-0EBF18F9A48D", &v) 39 | if err != nil { 40 | t.Errorf("failed to reload v: %v", err) 41 | } 42 | 43 | if v == 0 { 44 | t.Errorf("failed to load v. got %v", v) 45 | } else { 46 | t.Logf("got v: %v", v) 47 | } 48 | }) 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /plugin_test.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "id": "EF5A35EC-46EB-4E62-8251-78F1A49FA7DC", 4 | "file": "_example/test/plugins/plugin2/plugin2.so", 5 | "name": "Add", 6 | "version": "1.0" 7 | }, 8 | { 9 | "id": "2E8FD057-99EC-41B9-8172-0EBF18F9A48D", 10 | "file": "_example/test/plugins/plugin2/plugin2.so", 11 | "name": "V", 12 | "version": "1.0" 13 | } 14 | ] 15 | --------------------------------------------------------------------------------