manager.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  1. package plugins
  2. import (
  3. "archive/zip"
  4. "errors"
  5. "fmt"
  6. "github.com/emqx/kuiper/common"
  7. "github.com/emqx/kuiper/xstream/api"
  8. "io"
  9. "io/ioutil"
  10. "net/http"
  11. "net/url"
  12. "os"
  13. "os/exec"
  14. "path"
  15. "path/filepath"
  16. "plugin"
  17. "regexp"
  18. "strings"
  19. "sync"
  20. "time"
  21. "unicode"
  22. )
  23. type Plugin struct {
  24. Name string `json:"name"`
  25. File string `json:"file"`
  26. }
  27. type PluginType int
  28. const (
  29. SOURCE PluginType = iota
  30. SINK
  31. FUNCTION
  32. )
  33. const DELETED = "$deleted"
  34. var (
  35. PluginTypes = []string{"sources", "sinks", "functions"}
  36. once sync.Once
  37. singleton *Manager
  38. )
  39. //Registry is append only because plugin cannot delete or reload. To delete a plugin, restart the server to reindex
  40. type Registry struct {
  41. sync.RWMutex
  42. internal []map[string]string
  43. }
  44. func (rr *Registry) Store(t PluginType, name string, version string) {
  45. rr.Lock()
  46. rr.internal[t][name] = version
  47. rr.Unlock()
  48. }
  49. func (rr *Registry) List(t PluginType) []string {
  50. rr.RLock()
  51. result := rr.internal[t]
  52. rr.RUnlock()
  53. keys := make([]string, 0, len(result))
  54. for k := range result {
  55. keys = append(keys, k)
  56. }
  57. return keys
  58. }
  59. func (rr *Registry) Get(t PluginType, name string) (string, bool) {
  60. rr.RLock()
  61. result := rr.internal[t]
  62. rr.RUnlock()
  63. r, ok := result[name]
  64. return r, ok
  65. }
  66. //func (rr *Registry) Delete(t PluginType, value string) {
  67. // rr.Lock()
  68. // s := rr.internal[t]
  69. // for i, f := range s{
  70. // if f == value{
  71. // s[len(s)-1], s[i] = s[i], s[len(s)-1]
  72. // rr.internal[t] = s
  73. // break
  74. // }
  75. // }
  76. // rr.Unlock()
  77. //}
  78. var symbolRegistry = make(map[string]plugin.Symbol)
  79. var mu sync.RWMutex
  80. func getPlugin(t string, pt PluginType) (plugin.Symbol, error) {
  81. ut := ucFirst(t)
  82. ptype := PluginTypes[pt]
  83. key := ptype + "/" + t
  84. mu.Lock()
  85. defer mu.Unlock()
  86. var nf plugin.Symbol
  87. nf, ok := symbolRegistry[key]
  88. if !ok {
  89. loc, err := common.GetLoc("/plugins/")
  90. if err != nil {
  91. return nil, fmt.Errorf("cannot find the plugins folder")
  92. }
  93. m, err := NewPluginManager()
  94. if err != nil {
  95. return nil, fmt.Errorf("fail to initialize the plugin manager")
  96. }
  97. soFile, err := getSoFileName(m, pt, t)
  98. if err != nil {
  99. return nil, fmt.Errorf("cannot get the plugin file name: %v", err)
  100. }
  101. mod := path.Join(loc, ptype, soFile)
  102. plug, err := plugin.Open(mod)
  103. if err != nil {
  104. return nil, fmt.Errorf("cannot open %s: %v", mod, err)
  105. }
  106. nf, err = plug.Lookup(ut)
  107. if err != nil {
  108. return nil, fmt.Errorf("cannot find symbol %s, please check if it is exported", t)
  109. }
  110. symbolRegistry[key] = nf
  111. }
  112. return nf, nil
  113. }
  114. func GetSource(t string) (api.Source, error) {
  115. nf, err := getPlugin(t, SOURCE)
  116. if err != nil {
  117. return nil, err
  118. }
  119. var s api.Source
  120. switch t := nf.(type) {
  121. case api.Source:
  122. s = t
  123. case func() api.Source:
  124. s = t()
  125. default:
  126. return nil, fmt.Errorf("exported symbol %s is not type of api.Source or function that return api.Source", t)
  127. }
  128. return s, nil
  129. }
  130. func GetSink(t string) (api.Sink, error) {
  131. nf, err := getPlugin(t, SINK)
  132. if err != nil {
  133. return nil, err
  134. }
  135. var s api.Sink
  136. switch t := nf.(type) {
  137. case api.Sink:
  138. s = t
  139. case func() api.Sink:
  140. s = t()
  141. default:
  142. return nil, fmt.Errorf("exported symbol %s is not type of api.Sink or function that return api.Sink", t)
  143. }
  144. return s, nil
  145. }
  146. func GetFunction(t string) (api.Function, error) {
  147. nf, err := getPlugin(t, FUNCTION)
  148. if err != nil {
  149. return nil, err
  150. }
  151. var s api.Function
  152. switch t := nf.(type) {
  153. case api.Function:
  154. s = t
  155. case func() api.Function:
  156. s = t()
  157. default:
  158. return nil, fmt.Errorf("exported symbol %s is not type of api.Function or function that return api.Function", t)
  159. }
  160. return s, nil
  161. }
  162. type Manager struct {
  163. pluginDir string
  164. etcDir string
  165. registry *Registry
  166. }
  167. func NewPluginManager() (*Manager, error) {
  168. var outerErr error
  169. once.Do(func() {
  170. dir, err := common.GetLoc("/plugins")
  171. if err != nil {
  172. outerErr = fmt.Errorf("cannot find plugins folder: %s", err)
  173. return
  174. }
  175. etcDir, err := common.GetLoc("/etc")
  176. if err != nil {
  177. outerErr = fmt.Errorf("cannot find etc folder: %s", err)
  178. return
  179. }
  180. plugins := make([]map[string]string, 3)
  181. for i := 0; i < 3; i++ {
  182. names, err := findAll(PluginType(i), dir)
  183. if err != nil {
  184. outerErr = fmt.Errorf("fail to find existing plugins: %s", err)
  185. return
  186. }
  187. plugins[i] = names
  188. }
  189. registry := &Registry{internal: plugins}
  190. singleton = &Manager{
  191. pluginDir: dir,
  192. etcDir: etcDir,
  193. registry: registry,
  194. }
  195. readSourceMetaDir()
  196. readSinkMetaDir()
  197. readFuncMetaDir()
  198. })
  199. return singleton, outerErr
  200. }
  201. func findAll(t PluginType, pluginDir string) (result map[string]string, err error) {
  202. result = make(map[string]string)
  203. dir := path.Join(pluginDir, PluginTypes[t])
  204. files, err := ioutil.ReadDir(dir)
  205. if err != nil {
  206. return
  207. }
  208. for _, file := range files {
  209. baseName := filepath.Base(file.Name())
  210. if strings.HasSuffix(baseName, ".so") {
  211. n, v := parseName(baseName)
  212. result[n] = v
  213. }
  214. }
  215. return
  216. }
  217. func (m *Manager) List(t PluginType) (result []string, err error) {
  218. return m.registry.List(t), nil
  219. }
  220. func (m *Manager) Register(t PluginType, j *Plugin) error {
  221. name, uri := j.Name, j.File
  222. //Validation
  223. name = strings.Trim(name, " ")
  224. if name == "" {
  225. return fmt.Errorf("invalid name %s: should not be empty", name)
  226. }
  227. if !isValidUrl(uri) || !strings.HasSuffix(uri, ".zip") {
  228. return fmt.Errorf("invalid uri %s", uri)
  229. }
  230. if v, ok := m.registry.Get(t, name); ok {
  231. if v == DELETED {
  232. return fmt.Errorf("invalid name %s: the plugin is marked as deleted but Kuiper is not restarted for the change to take effect yet", name)
  233. } else {
  234. return fmt.Errorf("invalid name %s: duplicate", name)
  235. }
  236. }
  237. zipPath := path.Join(m.pluginDir, name+".zip")
  238. var unzipFiles []string
  239. //clean up: delete zip file and unzip files in error
  240. defer os.Remove(zipPath)
  241. //download
  242. err := downloadFile(zipPath, uri)
  243. if err != nil {
  244. return fmt.Errorf("fail to download file %s: %s", uri, err)
  245. }
  246. //unzip and copy to destination
  247. unzipFiles, version, err := m.install(t, name, zipPath)
  248. if err != nil {
  249. if t == SOURCE && len(unzipFiles) == 1 { //source that only copy so file
  250. os.Remove(unzipFiles[0])
  251. }
  252. return fmt.Errorf("fail to unzip file %s: %s", uri, err)
  253. }
  254. confDir, err := common.GetConfLoc()
  255. if nil != err {
  256. return err
  257. }
  258. if SINK == t {
  259. readSinkMetaFile(path.Join(confDir, PluginTypes[t], name+`.json`))
  260. } else if SOURCE == t {
  261. readSourceMetaFile(path.Join(confDir, PluginTypes[t], name+`.json`))
  262. }
  263. m.registry.Store(t, name, version)
  264. return nil
  265. }
  266. func (m *Manager) Delete(t PluginType, name string, stop bool) error {
  267. name = strings.Trim(name, " ")
  268. if name == "" {
  269. return fmt.Errorf("invalid name %s: should not be empty", name)
  270. }
  271. soFile, err := getSoFileName(m, t, name)
  272. if err != nil {
  273. return err
  274. }
  275. var results []string
  276. paths := []string{
  277. path.Join(m.pluginDir, PluginTypes[t], soFile),
  278. }
  279. if confDir, err := common.GetConfLoc(); nil == err {
  280. os.Remove(path.Join(confDir, PluginTypes[t], name+".json"))
  281. }
  282. if t == SOURCE {
  283. paths = append(paths, path.Join(m.etcDir, PluginTypes[t], name+".yaml"))
  284. }
  285. for _, p := range paths {
  286. _, err := os.Stat(p)
  287. if err == nil {
  288. err = os.Remove(p)
  289. if err != nil {
  290. results = append(results, err.Error())
  291. }
  292. } else {
  293. results = append(results, fmt.Sprintf("can't find %s", p))
  294. }
  295. }
  296. if len(results) > 0 {
  297. return errors.New(strings.Join(results, "\n"))
  298. } else {
  299. m.registry.Store(t, name, DELETED)
  300. if stop {
  301. go func() {
  302. time.Sleep(1 * time.Second)
  303. os.Exit(100)
  304. }()
  305. }
  306. return nil
  307. }
  308. }
  309. func (m *Manager) Get(t PluginType, name string) (map[string]string, bool) {
  310. v, ok := m.registry.Get(t, name)
  311. if strings.HasPrefix(v, "v") {
  312. v = v[1:]
  313. }
  314. if ok {
  315. m := map[string]string{
  316. "name": name,
  317. "version": v,
  318. }
  319. return m, ok
  320. }
  321. return nil, false
  322. }
  323. func getSoFileName(m *Manager, t PluginType, name string) (string, error) {
  324. v, ok := m.registry.Get(t, name)
  325. if !ok {
  326. return "", common.NewErrorWithCode(common.NOT_FOUND, fmt.Sprintf("invalid name %s: not exist", name))
  327. }
  328. soFile := ucFirst(name) + ".so"
  329. if v != "" {
  330. soFile = fmt.Sprintf("%s@%s.so", ucFirst(name), v)
  331. }
  332. return soFile, nil
  333. }
  334. func (m *Manager) install(t PluginType, name string, src string) ([]string, string, error) {
  335. var filenames []string
  336. var tempPath = path.Join(m.pluginDir, "temp", PluginTypes[t], name)
  337. defer os.RemoveAll(tempPath)
  338. r, err := zip.OpenReader(src)
  339. if err != nil {
  340. return filenames, "", err
  341. }
  342. defer r.Close()
  343. soPrefix := regexp.MustCompile(fmt.Sprintf(`^%s(@.*)?\.so$`, ucFirst(name)))
  344. var yamlFile, yamlPath, version string
  345. expFiles := 1
  346. if t == SOURCE {
  347. yamlFile = name + ".yaml"
  348. yamlPath = path.Join(m.etcDir, PluginTypes[t], yamlFile)
  349. expFiles = 2
  350. }
  351. needInstall := false
  352. for _, file := range r.File {
  353. fileName := file.Name
  354. if yamlFile == fileName {
  355. err = unzipTo(file, yamlPath)
  356. if err != nil {
  357. return filenames, "", err
  358. }
  359. filenames = append(filenames, yamlPath)
  360. } else if fileName == name+".json" {
  361. confDir, err := common.GetConfLoc()
  362. if nil != err {
  363. return filenames, "", err
  364. }
  365. err = unzipTo(file, path.Join(confDir, PluginTypes[t], fileName))
  366. if err != nil {
  367. return filenames, "", err
  368. }
  369. } else if soPrefix.Match([]byte(fileName)) {
  370. soPath := path.Join(m.pluginDir, PluginTypes[t], fileName)
  371. err = unzipTo(file, soPath)
  372. if err != nil {
  373. return filenames, "", err
  374. }
  375. filenames = append(filenames, soPath)
  376. _, version = parseName(fileName)
  377. } else { //unzip other files
  378. err = unzipTo(file, path.Join(tempPath, fileName))
  379. if err != nil {
  380. return filenames, "", err
  381. }
  382. if fileName == "install.sh" {
  383. needInstall = true
  384. }
  385. }
  386. }
  387. if len(filenames) != expFiles {
  388. return filenames, version, fmt.Errorf("invalid zip file: so file or conf file is missing")
  389. } else if needInstall {
  390. //run install script if there is
  391. spath := path.Join(tempPath, "install.sh")
  392. out, err := exec.Command("/bin/sh", spath).Output()
  393. if err != nil {
  394. return filenames, "", err
  395. } else {
  396. common.Log.Infof("install %s plugin %s log: %s", PluginTypes[t], name, out)
  397. }
  398. }
  399. return filenames, version, nil
  400. }
  401. func parseName(n string) (string, string) {
  402. result := strings.Split(n, ".so")
  403. result = strings.Split(result[0], "@")
  404. name := lcFirst(result[0])
  405. if len(result) > 1 {
  406. return name, result[1]
  407. }
  408. return name, ""
  409. }
  410. func unzipTo(f *zip.File, fpath string) error {
  411. _, err := os.Stat(fpath)
  412. if err == nil || !os.IsNotExist(err) {
  413. if err = os.Remove(fpath); err != nil {
  414. return fmt.Errorf("failed to delete file %s", fpath)
  415. }
  416. }
  417. if f.FileInfo().IsDir() {
  418. return fmt.Errorf("%s: not a file, but a directory", fpath)
  419. }
  420. if err := os.MkdirAll(filepath.Dir(fpath), os.ModePerm); err != nil {
  421. return err
  422. }
  423. outFile, err := os.OpenFile(fpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode())
  424. if err != nil {
  425. return err
  426. }
  427. rc, err := f.Open()
  428. if err != nil {
  429. return err
  430. }
  431. _, err = io.Copy(outFile, rc)
  432. outFile.Close()
  433. rc.Close()
  434. return err
  435. }
  436. func isValidUrl(uri string) bool {
  437. pu, err := url.ParseRequestURI(uri)
  438. if err != nil {
  439. return false
  440. }
  441. switch pu.Scheme {
  442. case "http", "https":
  443. u, err := url.Parse(uri)
  444. if err != nil || u.Scheme == "" || u.Host == "" {
  445. return false
  446. }
  447. case "file":
  448. if pu.Host != "" || pu.Path == "" {
  449. return false
  450. }
  451. default:
  452. return false
  453. }
  454. return true
  455. }
  456. func downloadFile(filepath string, uri string) error {
  457. u, err := url.ParseRequestURI(uri)
  458. if err != nil {
  459. return err
  460. }
  461. var src io.Reader
  462. switch u.Scheme {
  463. case "file":
  464. // deal with windows path
  465. if strings.Index(u.Path, ":") == 2 {
  466. u.Path = u.Path[1:]
  467. }
  468. fmt.Printf(u.Path)
  469. sourceFileStat, err := os.Stat(u.Path)
  470. if err != nil {
  471. return err
  472. }
  473. if !sourceFileStat.Mode().IsRegular() {
  474. return fmt.Errorf("%s is not a regular file", u.Path)
  475. }
  476. srcFile, err := os.Open(u.Path)
  477. if err != nil {
  478. return err
  479. }
  480. defer srcFile.Close()
  481. src = srcFile
  482. case "http", "https":
  483. // Get the data
  484. resp, err := http.Get(uri)
  485. if err != nil {
  486. return err
  487. }
  488. if resp.StatusCode != http.StatusOK {
  489. return fmt.Errorf("cannot download the file with status: %s", resp.Status)
  490. }
  491. defer resp.Body.Close()
  492. src = resp.Body
  493. default:
  494. return fmt.Errorf("unsupported url scheme %s", u.Scheme)
  495. }
  496. // Create the file
  497. out, err := os.Create(filepath)
  498. if err != nil {
  499. return err
  500. }
  501. defer out.Close()
  502. // Write the body to file
  503. _, err = io.Copy(out, src)
  504. return err
  505. }
  506. func ucFirst(str string) string {
  507. for i, v := range str {
  508. return string(unicode.ToUpper(v)) + str[i+1:]
  509. }
  510. return ""
  511. }
  512. func lcFirst(str string) string {
  513. for i, v := range str {
  514. return string(unicode.ToLower(v)) + str[i+1:]
  515. }
  516. return ""
  517. }