manager.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  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. m, err := NewPluginManager()
  90. if err != nil {
  91. return nil, fmt.Errorf("fail to initialize the plugin manager")
  92. }
  93. mod, err := getSoFilePath(m, pt, t)
  94. if err != nil {
  95. return nil, fmt.Errorf("cannot get the plugin file path: %v", err)
  96. }
  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. func GetSource(t string) (api.Source, error) {
  110. nf, err := getPlugin(t, SOURCE)
  111. if err != nil {
  112. return nil, err
  113. }
  114. var s api.Source
  115. switch t := nf.(type) {
  116. case api.Source:
  117. s = t
  118. case func() api.Source:
  119. s = t()
  120. default:
  121. return nil, fmt.Errorf("exported symbol %s is not type of api.Source or function that return api.Source", t)
  122. }
  123. return s, nil
  124. }
  125. func GetSink(t string) (api.Sink, error) {
  126. nf, err := getPlugin(t, SINK)
  127. if err != nil {
  128. return nil, err
  129. }
  130. var s api.Sink
  131. switch t := nf.(type) {
  132. case api.Sink:
  133. s = t
  134. case func() api.Sink:
  135. s = t()
  136. default:
  137. return nil, fmt.Errorf("exported symbol %s is not type of api.Sink or function that return api.Sink", t)
  138. }
  139. return s, nil
  140. }
  141. func GetFunction(t string) (api.Function, error) {
  142. nf, err := getPlugin(t, FUNCTION)
  143. if err != nil {
  144. return nil, err
  145. }
  146. var s api.Function
  147. switch t := nf.(type) {
  148. case api.Function:
  149. s = t
  150. case func() api.Function:
  151. s = t()
  152. default:
  153. return nil, fmt.Errorf("exported symbol %s is not type of api.Function or function that return api.Function", t)
  154. }
  155. return s, nil
  156. }
  157. type Manager struct {
  158. pluginDir string
  159. etcDir string
  160. registry *Registry
  161. }
  162. func NewPluginManager() (*Manager, error) {
  163. var outerErr error
  164. once.Do(func() {
  165. dir, err := common.GetLoc("/plugins")
  166. if err != nil {
  167. outerErr = fmt.Errorf("cannot find plugins folder: %s", err)
  168. return
  169. }
  170. etcDir, err := common.GetLoc("/etc")
  171. if err != nil {
  172. outerErr = fmt.Errorf("cannot find etc folder: %s", err)
  173. return
  174. }
  175. plugins := make([]map[string]string, 3)
  176. for i := 0; i < 3; i++ {
  177. names, err := findAll(PluginType(i), dir)
  178. if err != nil {
  179. outerErr = fmt.Errorf("fail to find existing plugins: %s", err)
  180. return
  181. }
  182. plugins[i] = names
  183. }
  184. registry := &Registry{internal: plugins}
  185. singleton = &Manager{
  186. pluginDir: dir,
  187. etcDir: etcDir,
  188. registry: registry,
  189. }
  190. if err := singleton.readSourceMetaDir(); nil != err {
  191. common.Log.Errorf("readSourceMetaDir:%v", err)
  192. }
  193. if err := singleton.readSinkMetaDir(); nil != err {
  194. common.Log.Errorf("readSinkMetaDir:%v", err)
  195. }
  196. if err := singleton.readFuncMetaDir(); nil != err {
  197. common.Log.Errorf("readFuncMetaDir:%v", err)
  198. }
  199. })
  200. return singleton, outerErr
  201. }
  202. func findAll(t PluginType, pluginDir string) (result map[string]string, err error) {
  203. result = make(map[string]string)
  204. dir := path.Join(pluginDir, PluginTypes[t])
  205. files, err := ioutil.ReadDir(dir)
  206. if err != nil {
  207. return
  208. }
  209. for _, file := range files {
  210. baseName := filepath.Base(file.Name())
  211. if strings.HasSuffix(baseName, ".so") {
  212. n, v := parseName(baseName)
  213. result[n] = v
  214. }
  215. }
  216. return
  217. }
  218. func (m *Manager) List(t PluginType) (result []string, err error) {
  219. return m.registry.List(t), nil
  220. }
  221. func (m *Manager) Register(t PluginType, j *Plugin) error {
  222. name, uri := j.Name, j.File
  223. //Validation
  224. name = strings.Trim(name, " ")
  225. if name == "" {
  226. return fmt.Errorf("invalid name %s: should not be empty", name)
  227. }
  228. if !isValidUrl(uri) || !strings.HasSuffix(uri, ".zip") {
  229. return fmt.Errorf("invalid uri %s", uri)
  230. }
  231. if v, ok := m.registry.Get(t, name); ok {
  232. if v == DELETED {
  233. 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)
  234. } else {
  235. return fmt.Errorf("invalid name %s: duplicate", name)
  236. }
  237. }
  238. zipPath := path.Join(m.pluginDir, name+".zip")
  239. var unzipFiles []string
  240. //clean up: delete zip file and unzip files in error
  241. defer os.Remove(zipPath)
  242. //download
  243. err := downloadFile(zipPath, uri)
  244. if err != nil {
  245. return fmt.Errorf("fail to download file %s: %s", uri, err)
  246. }
  247. //unzip and copy to destination
  248. unzipFiles, version, err := m.install(t, name, zipPath)
  249. if err != nil {
  250. if t == SOURCE && len(unzipFiles) == 1 { //source that only copy so file
  251. os.Remove(unzipFiles[0])
  252. }
  253. return fmt.Errorf("fail to unzip file %s: %s", uri, err)
  254. }
  255. m.registry.Store(t, name, version)
  256. switch t {
  257. case SINK:
  258. if err := m.readSinkMetaFile(path.Join(m.etcDir, PluginTypes[t], name+`.json`)); nil != err {
  259. common.Log.Errorf("readSinkFile:%v", err)
  260. }
  261. case SOURCE:
  262. if err := m.readSourceMetaFile(path.Join(m.etcDir, PluginTypes[t], name+`.json`)); nil != err {
  263. common.Log.Errorf("readSourceFile:%v", err)
  264. }
  265. case FUNCTION:
  266. if err := m.readFuncMetaFile(path.Join(m.etcDir, PluginTypes[t], name+`.json`)); nil != err {
  267. common.Log.Errorf("readFuncFile:%v", err)
  268. }
  269. }
  270. return nil
  271. }
  272. func (m *Manager) Delete(t PluginType, name string, stop bool) error {
  273. name = strings.Trim(name, " ")
  274. if name == "" {
  275. return fmt.Errorf("invalid name %s: should not be empty", name)
  276. }
  277. soPath, err := getSoFilePath(m, t, name)
  278. if err != nil {
  279. return err
  280. }
  281. var results []string
  282. paths := []string{
  283. soPath,
  284. }
  285. switch t {
  286. case SOURCE:
  287. paths = append(paths, path.Join(m.etcDir, PluginTypes[t], name+".yaml"))
  288. m.uninstalSource(name)
  289. case SINK:
  290. m.uninstalSink(name)
  291. case FUNCTION:
  292. m.uninstalFunc(name)
  293. }
  294. for _, p := range paths {
  295. _, err := os.Stat(p)
  296. if err == nil {
  297. err = os.Remove(p)
  298. if err != nil {
  299. results = append(results, err.Error())
  300. }
  301. } else {
  302. results = append(results, fmt.Sprintf("can't find %s", p))
  303. }
  304. }
  305. if len(results) > 0 {
  306. return errors.New(strings.Join(results, "\n"))
  307. } else {
  308. m.registry.Store(t, name, DELETED)
  309. if stop {
  310. go func() {
  311. time.Sleep(1 * time.Second)
  312. os.Exit(100)
  313. }()
  314. }
  315. return nil
  316. }
  317. }
  318. func (m *Manager) Get(t PluginType, name string) (map[string]string, bool) {
  319. v, ok := m.registry.Get(t, name)
  320. if strings.HasPrefix(v, "v") {
  321. v = v[1:]
  322. }
  323. if ok {
  324. m := map[string]string{
  325. "name": name,
  326. "version": v,
  327. }
  328. return m, ok
  329. }
  330. return nil, false
  331. }
  332. // Return the lowercase version of so name. It may be upper case in path.
  333. func getSoFilePath(m *Manager, t PluginType, name string) (string, error) {
  334. v, ok := m.registry.Get(t, name)
  335. if !ok {
  336. return "", common.NewErrorWithCode(common.NOT_FOUND, fmt.Sprintf("invalid name %s: not exist", name))
  337. }
  338. soFile := name + ".so"
  339. if v != "" {
  340. soFile = fmt.Sprintf("%s@%s.so", name, v)
  341. }
  342. p := path.Join(m.pluginDir, PluginTypes[t], soFile)
  343. if _, err := os.Stat(p); err != nil {
  344. p = path.Join(m.pluginDir, PluginTypes[t], ucFirst(soFile))
  345. }
  346. if _, err := os.Stat(p); err != nil {
  347. return "", common.NewErrorWithCode(common.NOT_FOUND, fmt.Sprintf("cannot find .so file for plugin %s", name))
  348. }
  349. return p, nil
  350. }
  351. func (m *Manager) install(t PluginType, name string, src string) ([]string, string, error) {
  352. var filenames []string
  353. var tempPath = path.Join(m.pluginDir, "temp", PluginTypes[t], name)
  354. defer os.RemoveAll(tempPath)
  355. r, err := zip.OpenReader(src)
  356. if err != nil {
  357. return filenames, "", err
  358. }
  359. defer r.Close()
  360. soPrefix := regexp.MustCompile(fmt.Sprintf(`^((%s)|(%s))(@.*)?\.so$`, name, ucFirst(name)))
  361. var yamlFile, yamlPath, version string
  362. expFiles := 1
  363. if t == SOURCE {
  364. yamlFile = name + ".yaml"
  365. yamlPath = path.Join(m.etcDir, PluginTypes[t], yamlFile)
  366. expFiles = 2
  367. }
  368. needInstall := false
  369. for _, file := range r.File {
  370. fileName := file.Name
  371. if yamlFile == fileName {
  372. err = unzipTo(file, yamlPath)
  373. if err != nil {
  374. return filenames, "", err
  375. }
  376. filenames = append(filenames, yamlPath)
  377. } else if fileName == name+".json" {
  378. if err := unzipTo(file, path.Join(m.etcDir, PluginTypes[t], fileName)); nil != err {
  379. common.Log.Errorf("Failed to decompress the metadata %s file", fileName)
  380. }
  381. } else if soPrefix.Match([]byte(fileName)) {
  382. soPath := path.Join(m.pluginDir, PluginTypes[t], fileName)
  383. err = unzipTo(file, soPath)
  384. if err != nil {
  385. return filenames, "", err
  386. }
  387. filenames = append(filenames, soPath)
  388. _, version = parseName(fileName)
  389. } else { //unzip other files
  390. err = unzipTo(file, path.Join(tempPath, fileName))
  391. if err != nil {
  392. return filenames, "", err
  393. }
  394. if fileName == "install.sh" {
  395. needInstall = true
  396. }
  397. }
  398. }
  399. if len(filenames) != expFiles {
  400. return filenames, version, fmt.Errorf("invalid zip file: so file or conf file is missing")
  401. } else if needInstall {
  402. //run install script if there is
  403. spath := path.Join(tempPath, "install.sh")
  404. out, err := exec.Command("/bin/sh", spath).Output()
  405. if err != nil {
  406. return filenames, "", err
  407. } else {
  408. common.Log.Infof("install %s plugin %s log: %s", PluginTypes[t], name, out)
  409. }
  410. }
  411. return filenames, version, nil
  412. }
  413. func parseName(n string) (string, string) {
  414. result := strings.Split(n, ".so")
  415. result = strings.Split(result[0], "@")
  416. name := lcFirst(result[0])
  417. if len(result) > 1 {
  418. return name, result[1]
  419. }
  420. return name, ""
  421. }
  422. func unzipTo(f *zip.File, fpath string) error {
  423. _, err := os.Stat(fpath)
  424. if err == nil || !os.IsNotExist(err) {
  425. if err = os.Remove(fpath); err != nil {
  426. return fmt.Errorf("failed to delete file %s", fpath)
  427. }
  428. }
  429. if f.FileInfo().IsDir() {
  430. return fmt.Errorf("%s: not a file, but a directory", fpath)
  431. }
  432. if err := os.MkdirAll(filepath.Dir(fpath), os.ModePerm); err != nil {
  433. return err
  434. }
  435. outFile, err := os.OpenFile(fpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode())
  436. if err != nil {
  437. return err
  438. }
  439. rc, err := f.Open()
  440. if err != nil {
  441. return err
  442. }
  443. _, err = io.Copy(outFile, rc)
  444. outFile.Close()
  445. rc.Close()
  446. return err
  447. }
  448. func isValidUrl(uri string) bool {
  449. pu, err := url.ParseRequestURI(uri)
  450. if err != nil {
  451. return false
  452. }
  453. switch pu.Scheme {
  454. case "http", "https":
  455. u, err := url.Parse(uri)
  456. if err != nil || u.Scheme == "" || u.Host == "" {
  457. return false
  458. }
  459. case "file":
  460. if pu.Host != "" || pu.Path == "" {
  461. return false
  462. }
  463. default:
  464. return false
  465. }
  466. return true
  467. }
  468. func downloadFile(filepath string, uri string) error {
  469. u, err := url.ParseRequestURI(uri)
  470. if err != nil {
  471. return err
  472. }
  473. var src io.Reader
  474. switch u.Scheme {
  475. case "file":
  476. // deal with windows path
  477. if strings.Index(u.Path, ":") == 2 {
  478. u.Path = u.Path[1:]
  479. }
  480. fmt.Printf(u.Path)
  481. sourceFileStat, err := os.Stat(u.Path)
  482. if err != nil {
  483. return err
  484. }
  485. if !sourceFileStat.Mode().IsRegular() {
  486. return fmt.Errorf("%s is not a regular file", u.Path)
  487. }
  488. srcFile, err := os.Open(u.Path)
  489. if err != nil {
  490. return err
  491. }
  492. defer srcFile.Close()
  493. src = srcFile
  494. case "http", "https":
  495. // Get the data
  496. resp, err := http.Get(uri)
  497. if err != nil {
  498. return err
  499. }
  500. if resp.StatusCode != http.StatusOK {
  501. return fmt.Errorf("cannot download the file with status: %s", resp.Status)
  502. }
  503. defer resp.Body.Close()
  504. src = resp.Body
  505. default:
  506. return fmt.Errorf("unsupported url scheme %s", u.Scheme)
  507. }
  508. // Create the file
  509. out, err := os.Create(filepath)
  510. if err != nil {
  511. return err
  512. }
  513. defer out.Close()
  514. // Write the body to file
  515. _, err = io.Copy(out, src)
  516. return err
  517. }
  518. func ucFirst(str string) string {
  519. for i, v := range str {
  520. return string(unicode.ToUpper(v)) + str[i+1:]
  521. }
  522. return ""
  523. }
  524. func lcFirst(str string) string {
  525. for i, v := range str {
  526. return string(unicode.ToLower(v)) + str[i+1:]
  527. }
  528. return ""
  529. }