manager.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. package plugins
  2. import (
  3. "archive/zip"
  4. "errors"
  5. "fmt"
  6. "github.com/emqx/kuiper/common"
  7. "io"
  8. "io/ioutil"
  9. "net/http"
  10. "net/url"
  11. "os"
  12. "path"
  13. "path/filepath"
  14. "strings"
  15. "sync"
  16. "unicode"
  17. )
  18. type Plugin struct {
  19. Name string `json:"name"`
  20. File string `json:"file"`
  21. Callback string `json:"callback"`
  22. }
  23. type PluginType int
  24. const (
  25. SOURCE PluginType = iota
  26. SINK
  27. FUNCTION
  28. )
  29. var (
  30. PluginTypes = []string{"sources", "sinks", "functions"}
  31. once sync.Once
  32. singleton *Manager
  33. )
  34. //Registry is append only because plugin cannot delete or reload. To delete a plugin, restart the server to reindex
  35. type Registry struct {
  36. sync.RWMutex
  37. internal [][]string
  38. }
  39. func (rr *Registry) Store(t PluginType, value string) {
  40. rr.Lock()
  41. rr.internal[t] = append(rr.internal[t], value)
  42. rr.Unlock()
  43. }
  44. func (rr *Registry) List(t PluginType) (values []string) {
  45. rr.RLock()
  46. result := rr.internal[t]
  47. rr.RUnlock()
  48. return result
  49. }
  50. //func (rr *Registry) Delete(t PluginType, value string) {
  51. // rr.Lock()
  52. // s := rr.internal[t]
  53. // for i, f := range s{
  54. // if f == value{
  55. // s[len(s)-1], s[i] = s[i], s[len(s)-1]
  56. // rr.internal[t] = s
  57. // break
  58. // }
  59. // }
  60. // rr.Unlock()
  61. //}
  62. type Manager struct {
  63. pluginDir string
  64. etcDir string
  65. registry *Registry
  66. }
  67. func NewPluginManager() (*Manager, error) {
  68. var err error
  69. once.Do(func() {
  70. dir, err := common.GetLoc("/plugins")
  71. if err != nil {
  72. err = fmt.Errorf("cannot find plugins folder: %s", err)
  73. return
  74. }
  75. etcDir, err := common.GetLoc("/etc")
  76. if err != nil {
  77. err = fmt.Errorf("cannot find etc folder: %s", err)
  78. return
  79. }
  80. plugins := make([][]string, 3)
  81. for i := 0; i < 3; i++ {
  82. names, err := findAll(PluginType(i), dir)
  83. if err != nil {
  84. err = fmt.Errorf("fail to find existing plugins: %s", err)
  85. return
  86. }
  87. plugins[i] = names
  88. }
  89. registry := &Registry{internal: plugins}
  90. singleton = &Manager{
  91. pluginDir: dir,
  92. etcDir: etcDir,
  93. registry: registry,
  94. }
  95. })
  96. return singleton, err
  97. }
  98. func findAll(t PluginType, pluginDir string) (result []string, err error) {
  99. dir := path.Join(pluginDir, PluginTypes[t])
  100. files, err := ioutil.ReadDir(dir)
  101. if err != nil {
  102. return
  103. }
  104. for _, file := range files {
  105. baseName := filepath.Base(file.Name())
  106. if strings.HasSuffix(baseName, ".so") {
  107. result = append(result, lcFirst(baseName[0:len(baseName)-3]))
  108. }
  109. }
  110. return
  111. }
  112. func (m *Manager) List(t PluginType) (result []string, err error) {
  113. return m.registry.List(t), nil
  114. }
  115. func (m *Manager) Register(t PluginType, j *Plugin) error {
  116. name, uri, cb := j.Name, j.File, j.Callback
  117. //Validation
  118. name = strings.Trim(name, " ")
  119. if name == "" {
  120. return fmt.Errorf("invalid name %s: should not be empty", name)
  121. }
  122. if !isValidUrl(uri) || !strings.HasSuffix(uri, ".zip") {
  123. return fmt.Errorf("invalid uri %s", uri)
  124. }
  125. for _, n := range m.registry.List(t) {
  126. if n == name {
  127. return fmt.Errorf("invalid name %s: duplicate", name)
  128. }
  129. }
  130. zipPath := path.Join(m.pluginDir, name+".zip")
  131. var unzipFiles []string
  132. //clean up: delete zip file and unzip files in error
  133. defer os.Remove(zipPath)
  134. //download
  135. err := downloadFile(zipPath, uri)
  136. if err != nil {
  137. return fmt.Errorf("fail to download file %s: %s", uri, err)
  138. }
  139. //unzip and copy to destination
  140. unzipFiles, err = m.unzipAndCopy(t, name, zipPath)
  141. if err != nil {
  142. if t == SOURCE && len(unzipFiles) == 1 { //source that only copy so file
  143. os.Remove(unzipFiles[0])
  144. }
  145. return fmt.Errorf("fail to unzip file %s: %s", uri, err)
  146. }
  147. m.registry.Store(t, name)
  148. return callback(cb)
  149. }
  150. func (m *Manager) Delete(t PluginType, name string) (result error) {
  151. name = strings.Trim(name, " ")
  152. if name == "" {
  153. return fmt.Errorf("invalid name %s: should not be empty", name)
  154. }
  155. found := false
  156. for _, n := range m.registry.List(t) {
  157. if n == name {
  158. found = true
  159. }
  160. }
  161. if !found {
  162. return fmt.Errorf("invalid name %s: not exist", name)
  163. }
  164. var results []string
  165. paths := []string{
  166. path.Join(m.pluginDir, PluginTypes[t], ucFirst(name)+".so"),
  167. }
  168. if t == SOURCE {
  169. paths = append(paths, path.Join(m.etcDir, PluginTypes[t], name+".yaml"))
  170. }
  171. for _, p := range paths {
  172. _, err := os.Stat(p)
  173. if err == nil {
  174. err = os.Remove(p)
  175. if err != nil {
  176. results = append(results, err.Error())
  177. }
  178. } else {
  179. results = append(results, fmt.Sprintf("can't find %s", p))
  180. }
  181. }
  182. if len(results) > 0 {
  183. return errors.New(strings.Join(results, "\n"))
  184. } else {
  185. return nil
  186. }
  187. }
  188. func (m *Manager) unzipAndCopy(t PluginType, name string, src string) ([]string, error) {
  189. var filenames []string
  190. r, err := zip.OpenReader(src)
  191. if err != nil {
  192. return filenames, err
  193. }
  194. defer r.Close()
  195. files := []string{
  196. ucFirst(name) + ".so",
  197. }
  198. paths := []string{
  199. path.Join(m.pluginDir, PluginTypes[t], files[0]),
  200. }
  201. if t == SOURCE {
  202. files = append(files, name+".yaml")
  203. paths = append(paths, path.Join(m.etcDir, PluginTypes[t], files[1]))
  204. }
  205. for i, d := range files {
  206. var z *zip.File
  207. for _, file := range r.File {
  208. fileName := file.Name
  209. if fileName == d {
  210. z = file
  211. }
  212. }
  213. if z == nil {
  214. return filenames, fmt.Errorf("invalid zip file: so file or conf file is missing")
  215. }
  216. err = unzipTo(z, paths[i])
  217. if err != nil {
  218. return filenames, err
  219. }
  220. filenames = append(filenames, paths[i])
  221. }
  222. return filenames, nil
  223. }
  224. func unzipTo(f *zip.File, fpath string) error {
  225. _, err := os.Stat(fpath)
  226. if err == nil || !os.IsNotExist(err) {
  227. return fmt.Errorf("%s already exist", fpath)
  228. }
  229. if f.FileInfo().IsDir() {
  230. return fmt.Errorf("%s: not a file, but a directory", fpath)
  231. }
  232. if err := os.MkdirAll(filepath.Dir(fpath), os.ModePerm); err != nil {
  233. return err
  234. }
  235. outFile, err := os.OpenFile(fpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode())
  236. if err != nil {
  237. return err
  238. }
  239. rc, err := f.Open()
  240. if err != nil {
  241. return err
  242. }
  243. _, err = io.Copy(outFile, rc)
  244. outFile.Close()
  245. rc.Close()
  246. return err
  247. }
  248. func isValidUrl(uri string) bool {
  249. _, err := url.ParseRequestURI(uri)
  250. if err != nil {
  251. return false
  252. }
  253. u, err := url.Parse(uri)
  254. if err != nil || u.Scheme == "" || u.Host == "" {
  255. return false
  256. }
  257. return true
  258. }
  259. func downloadFile(filepath string, url string) error {
  260. // Get the data
  261. resp, err := http.Get(url)
  262. if err != nil {
  263. return err
  264. }
  265. if resp.StatusCode != http.StatusOK {
  266. return fmt.Errorf("cannot download the file with status: %d %s", resp.StatusCode, resp.Status)
  267. }
  268. defer resp.Body.Close()
  269. // Create the file
  270. out, err := os.Create(filepath)
  271. if err != nil {
  272. return err
  273. }
  274. defer out.Close()
  275. // Write the body to file
  276. _, err = io.Copy(out, resp.Body)
  277. return err
  278. }
  279. func ucFirst(str string) string {
  280. for i, v := range str {
  281. return string(unicode.ToUpper(v)) + str[i+1:]
  282. }
  283. return ""
  284. }
  285. func lcFirst(str string) string {
  286. for i, v := range str {
  287. return string(unicode.ToLower(v)) + str[i+1:]
  288. }
  289. return ""
  290. }
  291. func callback(u string) error {
  292. return nil
  293. }