manager.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  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. "os/exec"
  13. "path"
  14. "path/filepath"
  15. "plugin"
  16. "regexp"
  17. "strings"
  18. "sync"
  19. "time"
  20. "unicode"
  21. )
  22. type Plugin struct {
  23. Name string `json:"name"`
  24. File string `json:"file"`
  25. }
  26. type PluginType int
  27. const (
  28. SOURCE PluginType = iota
  29. SINK
  30. FUNCTION
  31. )
  32. var (
  33. PluginTypes = []string{"sources", "sinks", "functions"}
  34. once sync.Once
  35. singleton *Manager
  36. )
  37. //Registry is append only because plugin cannot delete or reload. To delete a plugin, restart the server to reindex
  38. type Registry struct {
  39. sync.RWMutex
  40. internal []map[string]string
  41. }
  42. func (rr *Registry) Store(t PluginType, name string, version string) {
  43. rr.Lock()
  44. rr.internal[t][name] = version
  45. rr.Unlock()
  46. }
  47. func (rr *Registry) List(t PluginType) []string {
  48. rr.RLock()
  49. result := rr.internal[t]
  50. rr.RUnlock()
  51. keys := make([]string, 0, len(result))
  52. for k := range result {
  53. keys = append(keys, k)
  54. }
  55. return keys
  56. }
  57. func (rr *Registry) Get(t PluginType, name string) (string, bool) {
  58. rr.RLock()
  59. result := rr.internal[t]
  60. rr.RUnlock()
  61. r, ok := result[name]
  62. return r, ok
  63. }
  64. //func (rr *Registry) Delete(t PluginType, value string) {
  65. // rr.Lock()
  66. // s := rr.internal[t]
  67. // for i, f := range s{
  68. // if f == value{
  69. // s[len(s)-1], s[i] = s[i], s[len(s)-1]
  70. // rr.internal[t] = s
  71. // break
  72. // }
  73. // }
  74. // rr.Unlock()
  75. //}
  76. var symbolRegistry = make(map[string]plugin.Symbol)
  77. func GetPlugin(t string, pt PluginType) (plugin.Symbol, error) {
  78. ut := ucFirst(t)
  79. ptype := PluginTypes[pt]
  80. key := ptype + "/" + t
  81. var nf plugin.Symbol
  82. nf, ok := symbolRegistry[key]
  83. if !ok {
  84. loc, err := common.GetLoc("/plugins/")
  85. if err != nil {
  86. return nil, fmt.Errorf("cannot find the plugins folder")
  87. }
  88. m, err := NewPluginManager()
  89. if err != nil {
  90. return nil, fmt.Errorf("fail to initialize the plugin manager")
  91. }
  92. soFile, err := getSoFileName(m, pt, t)
  93. if err != nil {
  94. return nil, fmt.Errorf("cannot get the plugin file name: %v", err)
  95. }
  96. mod := path.Join(loc, ptype, soFile)
  97. plug, err := plugin.Open(mod)
  98. if err != nil {
  99. return nil, fmt.Errorf("cannot open %s: %v", mod, err)
  100. }
  101. nf, err = plug.Lookup(ut)
  102. if err != nil {
  103. return nil, fmt.Errorf("cannot find symbol %s, please check if it is exported", t)
  104. }
  105. symbolRegistry[key] = nf
  106. }
  107. return nf, nil
  108. }
  109. type Manager struct {
  110. pluginDir string
  111. etcDir string
  112. registry *Registry
  113. }
  114. func NewPluginManager() (*Manager, error) {
  115. var err error
  116. once.Do(func() {
  117. dir, err := common.GetLoc("/plugins")
  118. if err != nil {
  119. err = fmt.Errorf("cannot find plugins folder: %s", err)
  120. return
  121. }
  122. etcDir, err := common.GetLoc("/etc")
  123. if err != nil {
  124. err = fmt.Errorf("cannot find etc folder: %s", err)
  125. return
  126. }
  127. plugins := make([]map[string]string, 3)
  128. for i := 0; i < 3; i++ {
  129. names, err := findAll(PluginType(i), dir)
  130. if err != nil {
  131. err = fmt.Errorf("fail to find existing plugins: %s", err)
  132. return
  133. }
  134. plugins[i] = names
  135. }
  136. registry := &Registry{internal: plugins}
  137. singleton = &Manager{
  138. pluginDir: dir,
  139. etcDir: etcDir,
  140. registry: registry,
  141. }
  142. })
  143. return singleton, err
  144. }
  145. func findAll(t PluginType, pluginDir string) (result map[string]string, err error) {
  146. result = make(map[string]string)
  147. dir := path.Join(pluginDir, PluginTypes[t])
  148. files, err := ioutil.ReadDir(dir)
  149. if err != nil {
  150. return
  151. }
  152. for _, file := range files {
  153. baseName := filepath.Base(file.Name())
  154. if strings.HasSuffix(baseName, ".so") {
  155. n, v := parseName(baseName)
  156. result[n] = v
  157. }
  158. }
  159. return
  160. }
  161. func (m *Manager) List(t PluginType) (result []string, err error) {
  162. return m.registry.List(t), nil
  163. }
  164. func (m *Manager) Register(t PluginType, j *Plugin) error {
  165. name, uri := j.Name, j.File
  166. //Validation
  167. name = strings.Trim(name, " ")
  168. if name == "" {
  169. return fmt.Errorf("invalid name %s: should not be empty", name)
  170. }
  171. if !isValidUrl(uri) || !strings.HasSuffix(uri, ".zip") {
  172. return fmt.Errorf("invalid uri %s", uri)
  173. }
  174. for _, n := range m.registry.List(t) {
  175. if n == name {
  176. return fmt.Errorf("invalid name %s: duplicate", name)
  177. }
  178. }
  179. zipPath := path.Join(m.pluginDir, name+".zip")
  180. var unzipFiles []string
  181. //clean up: delete zip file and unzip files in error
  182. defer os.Remove(zipPath)
  183. //download
  184. err := downloadFile(zipPath, uri)
  185. if err != nil {
  186. return fmt.Errorf("fail to download file %s: %s", uri, err)
  187. }
  188. //unzip and copy to destination
  189. unzipFiles, version, err := m.install(t, name, zipPath)
  190. if err != nil {
  191. if t == SOURCE && len(unzipFiles) == 1 { //source that only copy so file
  192. os.Remove(unzipFiles[0])
  193. }
  194. return fmt.Errorf("fail to unzip file %s: %s", uri, err)
  195. }
  196. m.registry.Store(t, name, version)
  197. return nil
  198. }
  199. func (m *Manager) Delete(t PluginType, name string, stop bool) error {
  200. name = strings.Trim(name, " ")
  201. if name == "" {
  202. return fmt.Errorf("invalid name %s: should not be empty", name)
  203. }
  204. soFile, err := getSoFileName(m, t, name)
  205. if err != nil {
  206. return err
  207. }
  208. var results []string
  209. paths := []string{
  210. path.Join(m.pluginDir, PluginTypes[t], soFile),
  211. }
  212. if t == SOURCE {
  213. paths = append(paths, path.Join(m.etcDir, PluginTypes[t], name+".yaml"))
  214. }
  215. for _, p := range paths {
  216. _, err := os.Stat(p)
  217. if err == nil {
  218. err = os.Remove(p)
  219. if err != nil {
  220. results = append(results, err.Error())
  221. }
  222. } else {
  223. results = append(results, fmt.Sprintf("can't find %s", p))
  224. }
  225. }
  226. if len(results) > 0 {
  227. return errors.New(strings.Join(results, "\n"))
  228. } else {
  229. if stop {
  230. go func() {
  231. time.Sleep(1 * time.Second)
  232. os.Exit(100)
  233. }()
  234. }
  235. return nil
  236. }
  237. }
  238. func (m *Manager) Get(t PluginType, name string) (map[string]string, bool) {
  239. v, ok := m.registry.Get(t, name)
  240. if ok {
  241. m := map[string]string{
  242. "name": name,
  243. "version": v,
  244. }
  245. return m, ok
  246. }
  247. return nil, false
  248. }
  249. func getSoFileName(m *Manager, t PluginType, name string) (string, error) {
  250. v, ok := m.registry.Get(t, name)
  251. if !ok {
  252. return "", fmt.Errorf("invalid name %s: not exist", name)
  253. }
  254. soFile := ucFirst(name) + ".so"
  255. if v != "" {
  256. soFile = fmt.Sprintf("%s@v%s.so", ucFirst(name), v)
  257. }
  258. return soFile, nil
  259. }
  260. func (m *Manager) install(t PluginType, name string, src string) ([]string, string, error) {
  261. var filenames []string
  262. var tempPath = path.Join(m.pluginDir, "temp", PluginTypes[t], name)
  263. defer os.RemoveAll(tempPath)
  264. r, err := zip.OpenReader(src)
  265. if err != nil {
  266. return filenames, "", err
  267. }
  268. defer r.Close()
  269. soPrefix := regexp.MustCompile(fmt.Sprintf(`^%s(@v.*)?\.so$`, ucFirst(name)))
  270. var yamlFile, yamlPath, version string
  271. expFiles := 1
  272. if t == SOURCE {
  273. yamlFile = name + ".yaml"
  274. yamlPath = path.Join(m.etcDir, PluginTypes[t], yamlFile)
  275. expFiles = 2
  276. }
  277. needInstall := false
  278. for _, file := range r.File {
  279. fileName := file.Name
  280. if yamlFile == fileName {
  281. err = unzipTo(file, yamlPath)
  282. if err != nil {
  283. return filenames, "", err
  284. }
  285. filenames = append(filenames, yamlPath)
  286. } else if soPrefix.Match([]byte(fileName)) {
  287. soPath := path.Join(m.pluginDir, PluginTypes[t], fileName)
  288. err = unzipTo(file, soPath)
  289. if err != nil {
  290. return filenames, "", err
  291. }
  292. filenames = append(filenames, soPath)
  293. _, version = parseName(fileName)
  294. } else { //unzip other files
  295. err = unzipTo(file, path.Join(tempPath, fileName))
  296. if err != nil {
  297. return filenames, "", err
  298. }
  299. if fileName == "install.sh" {
  300. needInstall = true
  301. }
  302. }
  303. }
  304. if len(filenames) != expFiles {
  305. return filenames, version, fmt.Errorf("invalid zip file: so file or conf file is missing")
  306. } else if needInstall {
  307. //run install script if there is
  308. spath := path.Join(tempPath, "install.sh")
  309. out, err := exec.Command("/bin/sh", spath).Output()
  310. if err != nil {
  311. return filenames, "", err
  312. } else {
  313. common.Log.Infof("install %s plugin %s log: %s", PluginTypes[t], name, out)
  314. }
  315. }
  316. return filenames, version, nil
  317. }
  318. func parseName(n string) (string, string) {
  319. result := strings.Split(n, ".so")
  320. result = strings.Split(result[0], "@v")
  321. name := lcFirst(result[0])
  322. if len(result) > 1 {
  323. return name, result[1]
  324. }
  325. return name, ""
  326. }
  327. func unzipTo(f *zip.File, fpath string) error {
  328. _, err := os.Stat(fpath)
  329. if err == nil || !os.IsNotExist(err) {
  330. return fmt.Errorf("%s already exist", fpath)
  331. }
  332. if f.FileInfo().IsDir() {
  333. return fmt.Errorf("%s: not a file, but a directory", fpath)
  334. }
  335. if err := os.MkdirAll(filepath.Dir(fpath), os.ModePerm); err != nil {
  336. return err
  337. }
  338. outFile, err := os.OpenFile(fpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode())
  339. if err != nil {
  340. return err
  341. }
  342. rc, err := f.Open()
  343. if err != nil {
  344. return err
  345. }
  346. _, err = io.Copy(outFile, rc)
  347. outFile.Close()
  348. rc.Close()
  349. return err
  350. }
  351. func isValidUrl(uri string) bool {
  352. _, err := url.ParseRequestURI(uri)
  353. if err != nil {
  354. return false
  355. }
  356. u, err := url.Parse(uri)
  357. if err != nil || u.Scheme == "" || u.Host == "" {
  358. return false
  359. }
  360. return true
  361. }
  362. func downloadFile(filepath string, url string) error {
  363. // Get the data
  364. resp, err := http.Get(url)
  365. if err != nil {
  366. return err
  367. }
  368. if resp.StatusCode != http.StatusOK {
  369. return fmt.Errorf("cannot download the file with status: %s", resp.Status)
  370. }
  371. defer resp.Body.Close()
  372. // Create the file
  373. out, err := os.Create(filepath)
  374. if err != nil {
  375. return err
  376. }
  377. defer out.Close()
  378. // Write the body to file
  379. _, err = io.Copy(out, resp.Body)
  380. return err
  381. }
  382. func ucFirst(str string) string {
  383. for i, v := range str {
  384. return string(unicode.ToUpper(v)) + str[i+1:]
  385. }
  386. return ""
  387. }
  388. func lcFirst(str string) string {
  389. for i, v := range str {
  390. return string(unicode.ToLower(v)) + str[i+1:]
  391. }
  392. return ""
  393. }