manager.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  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. })
  206. return singleton, outerErr
  207. }
  208. func findAll(t PluginType, pluginDir string) (result map[string]string, err error) {
  209. result = make(map[string]string)
  210. dir := path.Join(pluginDir, PluginTypes[t])
  211. files, err := ioutil.ReadDir(dir)
  212. if err != nil {
  213. return
  214. }
  215. for _, file := range files {
  216. baseName := filepath.Base(file.Name())
  217. if strings.HasSuffix(baseName, ".so") {
  218. n, v := parseName(baseName)
  219. result[n] = v
  220. }
  221. }
  222. return
  223. }
  224. func (m *Manager) List(t PluginType) (result []string, err error) {
  225. return m.registry.List(t), nil
  226. }
  227. func (m *Manager) Register(t PluginType, j *Plugin) error {
  228. name, uri, shellParas := j.Name, j.File, j.ShellParas
  229. //Validation
  230. name = strings.Trim(name, " ")
  231. if name == "" {
  232. return fmt.Errorf("invalid name %s: should not be empty", name)
  233. }
  234. if !isValidUrl(uri) || !strings.HasSuffix(uri, ".zip") {
  235. return fmt.Errorf("invalid uri %s", uri)
  236. }
  237. if v, ok := m.registry.Get(t, name); ok {
  238. if v == DELETED {
  239. 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)
  240. } else {
  241. return fmt.Errorf("invalid name %s: duplicate", name)
  242. }
  243. }
  244. zipPath := path.Join(m.pluginDir, name+".zip")
  245. var unzipFiles []string
  246. //clean up: delete zip file and unzip files in error
  247. defer os.Remove(zipPath)
  248. //download
  249. err := downloadFile(zipPath, uri)
  250. if err != nil {
  251. return fmt.Errorf("fail to download file %s: %s", uri, err)
  252. }
  253. //unzip and copy to destination
  254. unzipFiles, version, err := m.install(t, name, zipPath, shellParas)
  255. if err != nil {
  256. if t == SOURCE && len(unzipFiles) == 1 { //source that only copy so file
  257. os.Remove(unzipFiles[0])
  258. }
  259. return fmt.Errorf("fail to unzip file %s: %s", uri, err)
  260. }
  261. m.registry.Store(t, name, version)
  262. switch t {
  263. case SINK:
  264. if err := m.readSinkMetaFile(path.Join(m.etcDir, PluginTypes[t], name+`.json`)); nil != err {
  265. common.Log.Errorf("readSinkFile:%v", err)
  266. }
  267. case SOURCE:
  268. if err := m.readSourceMetaFile(path.Join(m.etcDir, PluginTypes[t], name+`.json`)); nil != err {
  269. common.Log.Errorf("readSourceFile:%v", err)
  270. }
  271. case FUNCTION:
  272. if err := m.readFuncMetaFile(path.Join(m.etcDir, PluginTypes[t], name+`.json`)); nil != err {
  273. common.Log.Errorf("readFuncFile:%v", err)
  274. }
  275. }
  276. return nil
  277. }
  278. func (m *Manager) Delete(t PluginType, name string, stop bool) error {
  279. name = strings.Trim(name, " ")
  280. if name == "" {
  281. return fmt.Errorf("invalid name %s: should not be empty", name)
  282. }
  283. soPath, err := getSoFilePath(m, t, name)
  284. if err != nil {
  285. return err
  286. }
  287. var results []string
  288. paths := []string{
  289. soPath,
  290. }
  291. switch t {
  292. case SOURCE:
  293. paths = append(paths, path.Join(m.etcDir, PluginTypes[t], name+".yaml"))
  294. m.uninstalSource(name)
  295. case SINK:
  296. m.uninstalSink(name)
  297. case FUNCTION:
  298. m.uninstalFunc(name)
  299. }
  300. for _, p := range paths {
  301. _, err := os.Stat(p)
  302. if err == nil {
  303. err = os.Remove(p)
  304. if err != nil {
  305. results = append(results, err.Error())
  306. }
  307. } else {
  308. results = append(results, fmt.Sprintf("can't find %s", p))
  309. }
  310. }
  311. if len(results) > 0 {
  312. return errors.New(strings.Join(results, "\n"))
  313. } else {
  314. m.registry.Store(t, name, DELETED)
  315. if stop {
  316. go func() {
  317. time.Sleep(1 * time.Second)
  318. os.Exit(100)
  319. }()
  320. }
  321. return nil
  322. }
  323. }
  324. func (m *Manager) Get(t PluginType, name string) (map[string]string, bool) {
  325. v, ok := m.registry.Get(t, name)
  326. if strings.HasPrefix(v, "v") {
  327. v = v[1:]
  328. }
  329. if ok {
  330. m := map[string]string{
  331. "name": name,
  332. "version": v,
  333. }
  334. return m, ok
  335. }
  336. return nil, false
  337. }
  338. // Return the lowercase version of so name. It may be upper case in path.
  339. func getSoFilePath(m *Manager, t PluginType, name string) (string, error) {
  340. v, ok := m.registry.Get(t, name)
  341. if !ok {
  342. return "", common.NewErrorWithCode(common.NOT_FOUND, fmt.Sprintf("invalid name %s: not exist", name))
  343. }
  344. soFile := name + ".so"
  345. if v != "" {
  346. soFile = fmt.Sprintf("%s@%s.so", name, v)
  347. }
  348. p := path.Join(m.pluginDir, PluginTypes[t], soFile)
  349. if _, err := os.Stat(p); err != nil {
  350. p = path.Join(m.pluginDir, PluginTypes[t], ucFirst(soFile))
  351. }
  352. if _, err := os.Stat(p); err != nil {
  353. return "", common.NewErrorWithCode(common.NOT_FOUND, fmt.Sprintf("cannot find .so file for plugin %s", name))
  354. }
  355. return p, nil
  356. }
  357. func (m *Manager) install(t PluginType, name, src string, shellParas []string) ([]string, string, error) {
  358. var filenames []string
  359. var tempPath = path.Join(m.pluginDir, "temp", PluginTypes[t], name)
  360. defer os.RemoveAll(tempPath)
  361. r, err := zip.OpenReader(src)
  362. if err != nil {
  363. return filenames, "", err
  364. }
  365. defer r.Close()
  366. soPrefix := regexp.MustCompile(fmt.Sprintf(`^((%s)|(%s))(@.*)?\.so$`, name, ucFirst(name)))
  367. var yamlFile, yamlPath, version string
  368. expFiles := 1
  369. if t == SOURCE {
  370. yamlFile = name + ".yaml"
  371. yamlPath = path.Join(m.etcDir, PluginTypes[t], yamlFile)
  372. expFiles = 2
  373. }
  374. var revokeFiles []string
  375. needInstall := false
  376. for _, file := range r.File {
  377. fileName := file.Name
  378. if yamlFile == fileName {
  379. err = unzipTo(file, yamlPath)
  380. if err != nil {
  381. return filenames, "", err
  382. }
  383. revokeFiles = append(revokeFiles, yamlPath)
  384. filenames = append(filenames, yamlPath)
  385. } else if fileName == name+".json" {
  386. jsonPath := path.Join(m.etcDir, PluginTypes[t], fileName)
  387. if err := unzipTo(file, jsonPath); nil != err {
  388. common.Log.Errorf("Failed to decompress the metadata %s file", fileName)
  389. } else {
  390. revokeFiles = append(revokeFiles, jsonPath)
  391. }
  392. } else if soPrefix.Match([]byte(fileName)) {
  393. soPath := path.Join(m.pluginDir, PluginTypes[t], fileName)
  394. err = unzipTo(file, soPath)
  395. if err != nil {
  396. return filenames, "", err
  397. }
  398. filenames = append(filenames, soPath)
  399. revokeFiles = append(revokeFiles, soPath)
  400. _, version = parseName(fileName)
  401. } else { //unzip other files
  402. err = unzipTo(file, path.Join(tempPath, fileName))
  403. if err != nil {
  404. return filenames, "", err
  405. }
  406. if fileName == "install.sh" {
  407. needInstall = true
  408. }
  409. }
  410. }
  411. if len(filenames) != expFiles {
  412. return filenames, version, fmt.Errorf("invalid zip file: so file or conf file is missing")
  413. } else if needInstall {
  414. //run install script if there is
  415. spath := path.Join(tempPath, "install.sh")
  416. shellParas = append(shellParas, spath)
  417. if 1 != len(shellParas) {
  418. copy(shellParas[1:], shellParas[0:])
  419. shellParas[0] = spath
  420. }
  421. cmd := exec.Command("/bin/sh", shellParas...)
  422. var outb, errb bytes.Buffer
  423. cmd.Stdout = &outb
  424. cmd.Stderr = &errb
  425. err := cmd.Run()
  426. if err != nil {
  427. for _, f := range revokeFiles {
  428. os.Remove(f)
  429. }
  430. common.Log.Infof(`err:%v stdout:%s stderr:%s`, err, outb.String(), errb.String())
  431. return filenames, "", err
  432. } else {
  433. common.Log.Infof("install %s plugin %s", PluginTypes[t], name)
  434. }
  435. }
  436. return filenames, version, nil
  437. }
  438. func parseName(n string) (string, string) {
  439. result := strings.Split(n, ".so")
  440. result = strings.Split(result[0], "@")
  441. name := lcFirst(result[0])
  442. if len(result) > 1 {
  443. return name, result[1]
  444. }
  445. return name, ""
  446. }
  447. func unzipTo(f *zip.File, fpath string) error {
  448. _, err := os.Stat(fpath)
  449. if err == nil || !os.IsNotExist(err) {
  450. if err = os.Remove(fpath); err != nil {
  451. return fmt.Errorf("failed to delete file %s", fpath)
  452. }
  453. }
  454. if f.FileInfo().IsDir() {
  455. return fmt.Errorf("%s: not a file, but a directory", fpath)
  456. }
  457. if err := os.MkdirAll(filepath.Dir(fpath), os.ModePerm); err != nil {
  458. return err
  459. }
  460. outFile, err := os.OpenFile(fpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode())
  461. if err != nil {
  462. return err
  463. }
  464. rc, err := f.Open()
  465. if err != nil {
  466. return err
  467. }
  468. _, err = io.Copy(outFile, rc)
  469. outFile.Close()
  470. rc.Close()
  471. return err
  472. }
  473. func isValidUrl(uri string) bool {
  474. pu, err := url.ParseRequestURI(uri)
  475. if err != nil {
  476. return false
  477. }
  478. switch pu.Scheme {
  479. case "http", "https":
  480. u, err := url.Parse(uri)
  481. if err != nil || u.Scheme == "" || u.Host == "" {
  482. return false
  483. }
  484. case "file":
  485. if pu.Host != "" || pu.Path == "" {
  486. return false
  487. }
  488. default:
  489. return false
  490. }
  491. return true
  492. }
  493. func downloadFile(filepath string, uri string) error {
  494. common.Log.Infof("Start to download file %s\n", uri)
  495. u, err := url.ParseRequestURI(uri)
  496. if err != nil {
  497. return err
  498. }
  499. var src io.Reader
  500. switch u.Scheme {
  501. case "file":
  502. // deal with windows path
  503. if strings.Index(u.Path, ":") == 2 {
  504. u.Path = u.Path[1:]
  505. }
  506. common.Log.Debugf(u.Path)
  507. sourceFileStat, err := os.Stat(u.Path)
  508. if err != nil {
  509. return err
  510. }
  511. if !sourceFileStat.Mode().IsRegular() {
  512. return fmt.Errorf("%s is not a regular file", u.Path)
  513. }
  514. srcFile, err := os.Open(u.Path)
  515. if err != nil {
  516. return err
  517. }
  518. defer srcFile.Close()
  519. src = srcFile
  520. case "http", "https":
  521. // Get the data
  522. timeout := time.Duration(5 * time.Minute)
  523. client := &http.Client{
  524. Timeout: timeout,
  525. Transport: &http.Transport{
  526. TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
  527. },
  528. }
  529. resp, err := client.Get(uri)
  530. if err != nil {
  531. return err
  532. }
  533. if resp.StatusCode != http.StatusOK {
  534. return fmt.Errorf("cannot download the file with status: %s", resp.Status)
  535. }
  536. defer resp.Body.Close()
  537. src = resp.Body
  538. default:
  539. return fmt.Errorf("unsupported url scheme %s", u.Scheme)
  540. }
  541. // Create the file
  542. out, err := os.Create(filepath)
  543. if err != nil {
  544. return err
  545. }
  546. defer out.Close()
  547. // Write the body to file
  548. _, err = io.Copy(out, src)
  549. return err
  550. }
  551. func ucFirst(str string) string {
  552. for i, v := range str {
  553. return string(unicode.ToUpper(v)) + str[i+1:]
  554. }
  555. return ""
  556. }
  557. func lcFirst(str string) string {
  558. for i, v := range str {
  559. return string(unicode.ToLower(v)) + str[i+1:]
  560. }
  561. return ""
  562. }