manager.go 14 KB

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