manager.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  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. func getPlugin(t string, pt PluginType) (plugin.Symbol, error) {
  80. ut := ucFirst(t)
  81. ptype := PluginTypes[pt]
  82. key := ptype + "/" + t
  83. var nf plugin.Symbol
  84. nf, ok := symbolRegistry[key]
  85. if !ok {
  86. loc, err := common.GetLoc("/plugins/")
  87. if err != nil {
  88. return nil, fmt.Errorf("cannot find the plugins folder")
  89. }
  90. m, err := NewPluginManager()
  91. if err != nil {
  92. return nil, fmt.Errorf("fail to initialize the plugin manager")
  93. }
  94. soFile, err := getSoFileName(m, pt, t)
  95. if err != nil {
  96. return nil, fmt.Errorf("cannot get the plugin file name: %v", err)
  97. }
  98. mod := path.Join(loc, ptype, soFile)
  99. plug, err := plugin.Open(mod)
  100. if err != nil {
  101. return nil, fmt.Errorf("cannot open %s: %v", mod, err)
  102. }
  103. nf, err = plug.Lookup(ut)
  104. if err != nil {
  105. return nil, fmt.Errorf("cannot find symbol %s, please check if it is exported", t)
  106. }
  107. symbolRegistry[key] = nf
  108. }
  109. return nf, nil
  110. }
  111. func GetSource(t string) (api.Source, error) {
  112. nf, err := getPlugin(t, SOURCE)
  113. if err != nil {
  114. return nil, err
  115. }
  116. var s api.Source
  117. switch t := nf.(type) {
  118. case api.Source:
  119. s = t
  120. case func() api.Source:
  121. s = t()
  122. default:
  123. return nil, fmt.Errorf("exported symbol %s is not type of api.Source or function that return api.Source", t)
  124. }
  125. return s, nil
  126. }
  127. func GetSink(t string) (api.Sink, error) {
  128. nf, err := getPlugin(t, SINK)
  129. if err != nil {
  130. return nil, err
  131. }
  132. var s api.Sink
  133. switch t := nf.(type) {
  134. case api.Sink:
  135. s = t
  136. case func() api.Sink:
  137. s = t()
  138. default:
  139. return nil, fmt.Errorf("exported symbol %s is not type of api.Sink or function that return api.Sink", t)
  140. }
  141. return s, nil
  142. }
  143. func GetFunction(t string) (api.Function, error) {
  144. nf, err := getPlugin(t, FUNCTION)
  145. if err != nil {
  146. return nil, err
  147. }
  148. var s api.Function
  149. switch t := nf.(type) {
  150. case api.Function:
  151. s = t
  152. case func() api.Function:
  153. s = t()
  154. default:
  155. return nil, fmt.Errorf("exported symbol %s is not type of api.Function or function that return api.Function", t)
  156. }
  157. return s, nil
  158. }
  159. type Manager struct {
  160. pluginDir string
  161. etcDir string
  162. registry *Registry
  163. }
  164. func NewPluginManager() (*Manager, error) {
  165. var err error
  166. once.Do(func() {
  167. dir, err := common.GetLoc("/plugins")
  168. if err != nil {
  169. err = fmt.Errorf("cannot find plugins folder: %s", err)
  170. return
  171. }
  172. etcDir, err := common.GetLoc("/etc")
  173. if err != nil {
  174. err = fmt.Errorf("cannot find etc folder: %s", err)
  175. return
  176. }
  177. plugins := make([]map[string]string, 3)
  178. for i := 0; i < 3; i++ {
  179. names, err := findAll(PluginType(i), dir)
  180. if err != nil {
  181. err = fmt.Errorf("fail to find existing plugins: %s", err)
  182. return
  183. }
  184. plugins[i] = names
  185. }
  186. registry := &Registry{internal: plugins}
  187. singleton = &Manager{
  188. pluginDir: dir,
  189. etcDir: etcDir,
  190. registry: registry,
  191. }
  192. })
  193. return singleton, err
  194. }
  195. func findAll(t PluginType, pluginDir string) (result map[string]string, err error) {
  196. result = make(map[string]string)
  197. dir := path.Join(pluginDir, PluginTypes[t])
  198. files, err := ioutil.ReadDir(dir)
  199. if err != nil {
  200. return
  201. }
  202. for _, file := range files {
  203. baseName := filepath.Base(file.Name())
  204. if strings.HasSuffix(baseName, ".so") {
  205. n, v := parseName(baseName)
  206. result[n] = v
  207. }
  208. }
  209. return
  210. }
  211. func (m *Manager) List(t PluginType) (result []string, err error) {
  212. return m.registry.List(t), nil
  213. }
  214. func (m *Manager) Register(t PluginType, j *Plugin) error {
  215. name, uri := j.Name, j.File
  216. //Validation
  217. name = strings.Trim(name, " ")
  218. if name == "" {
  219. return fmt.Errorf("invalid name %s: should not be empty", name)
  220. }
  221. if !isValidUrl(uri) || !strings.HasSuffix(uri, ".zip") {
  222. return fmt.Errorf("invalid uri %s", uri)
  223. }
  224. if v, ok := m.registry.Get(t, name); ok {
  225. if v == DELETED {
  226. 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)
  227. } else {
  228. return fmt.Errorf("invalid name %s: duplicate", name)
  229. }
  230. }
  231. zipPath := path.Join(m.pluginDir, name+".zip")
  232. var unzipFiles []string
  233. //clean up: delete zip file and unzip files in error
  234. defer os.Remove(zipPath)
  235. //download
  236. err := downloadFile(zipPath, uri)
  237. if err != nil {
  238. return fmt.Errorf("fail to download file %s: %s", uri, err)
  239. }
  240. //unzip and copy to destination
  241. unzipFiles, version, err := m.install(t, name, zipPath)
  242. if err != nil {
  243. if t == SOURCE && len(unzipFiles) == 1 { //source that only copy so file
  244. os.Remove(unzipFiles[0])
  245. }
  246. return fmt.Errorf("fail to unzip file %s: %s", uri, err)
  247. }
  248. m.registry.Store(t, name, version)
  249. return nil
  250. }
  251. func (m *Manager) Delete(t PluginType, name string, stop bool) error {
  252. name = strings.Trim(name, " ")
  253. if name == "" {
  254. return fmt.Errorf("invalid name %s: should not be empty", name)
  255. }
  256. soFile, err := getSoFileName(m, t, name)
  257. if err != nil {
  258. return err
  259. }
  260. var results []string
  261. paths := []string{
  262. path.Join(m.pluginDir, PluginTypes[t], soFile),
  263. }
  264. if t == SOURCE {
  265. paths = append(paths, path.Join(m.etcDir, PluginTypes[t], name+".yaml"))
  266. }
  267. for _, p := range paths {
  268. _, err := os.Stat(p)
  269. if err == nil {
  270. err = os.Remove(p)
  271. if err != nil {
  272. results = append(results, err.Error())
  273. }
  274. } else {
  275. results = append(results, fmt.Sprintf("can't find %s", p))
  276. }
  277. }
  278. if len(results) > 0 {
  279. return errors.New(strings.Join(results, "\n"))
  280. } else {
  281. m.registry.Store(t, name, DELETED)
  282. if stop {
  283. go func() {
  284. time.Sleep(1 * time.Second)
  285. os.Exit(100)
  286. }()
  287. }
  288. return nil
  289. }
  290. }
  291. func (m *Manager) Get(t PluginType, name string) (map[string]string, bool) {
  292. v, ok := m.registry.Get(t, name)
  293. if ok {
  294. m := map[string]string{
  295. "name": name,
  296. "version": v,
  297. }
  298. return m, ok
  299. }
  300. return nil, false
  301. }
  302. func getSoFileName(m *Manager, t PluginType, name string) (string, error) {
  303. v, ok := m.registry.Get(t, name)
  304. if !ok {
  305. return "", fmt.Errorf("invalid name %s: not exist", name)
  306. }
  307. soFile := ucFirst(name) + ".so"
  308. if v != "" {
  309. soFile = fmt.Sprintf("%s@v%s.so", ucFirst(name), v)
  310. }
  311. return soFile, nil
  312. }
  313. func (m *Manager) install(t PluginType, name string, src string) ([]string, string, error) {
  314. var filenames []string
  315. var tempPath = path.Join(m.pluginDir, "temp", PluginTypes[t], name)
  316. defer os.RemoveAll(tempPath)
  317. r, err := zip.OpenReader(src)
  318. if err != nil {
  319. return filenames, "", err
  320. }
  321. defer r.Close()
  322. soPrefix := regexp.MustCompile(fmt.Sprintf(`^%s(@v.*)?\.so$`, ucFirst(name)))
  323. var yamlFile, yamlPath, version string
  324. expFiles := 1
  325. if t == SOURCE {
  326. yamlFile = name + ".yaml"
  327. yamlPath = path.Join(m.etcDir, PluginTypes[t], yamlFile)
  328. expFiles = 2
  329. }
  330. needInstall := false
  331. for _, file := range r.File {
  332. fileName := file.Name
  333. if yamlFile == fileName {
  334. err = unzipTo(file, yamlPath)
  335. if err != nil {
  336. return filenames, "", err
  337. }
  338. filenames = append(filenames, yamlPath)
  339. } else if soPrefix.Match([]byte(fileName)) {
  340. soPath := path.Join(m.pluginDir, PluginTypes[t], fileName)
  341. err = unzipTo(file, soPath)
  342. if err != nil {
  343. return filenames, "", err
  344. }
  345. filenames = append(filenames, soPath)
  346. _, version = parseName(fileName)
  347. } else { //unzip other files
  348. err = unzipTo(file, path.Join(tempPath, fileName))
  349. if err != nil {
  350. return filenames, "", err
  351. }
  352. if fileName == "install.sh" {
  353. needInstall = true
  354. }
  355. }
  356. }
  357. if len(filenames) != expFiles {
  358. return filenames, version, fmt.Errorf("invalid zip file: so file or conf file is missing")
  359. } else if needInstall {
  360. //run install script if there is
  361. spath := path.Join(tempPath, "install.sh")
  362. out, err := exec.Command("/bin/sh", spath).Output()
  363. if err != nil {
  364. return filenames, "", err
  365. } else {
  366. common.Log.Infof("install %s plugin %s log: %s", PluginTypes[t], name, out)
  367. }
  368. }
  369. return filenames, version, nil
  370. }
  371. func parseName(n string) (string, string) {
  372. result := strings.Split(n, ".so")
  373. result = strings.Split(result[0], "@v")
  374. name := lcFirst(result[0])
  375. if len(result) > 1 {
  376. return name, result[1]
  377. }
  378. return name, ""
  379. }
  380. func unzipTo(f *zip.File, fpath string) error {
  381. _, err := os.Stat(fpath)
  382. if err == nil || !os.IsNotExist(err) {
  383. if err = os.Remove(fpath); err != nil {
  384. return fmt.Errorf("failed to delete file %s", fpath)
  385. }
  386. }
  387. if f.FileInfo().IsDir() {
  388. return fmt.Errorf("%s: not a file, but a directory", fpath)
  389. }
  390. if err := os.MkdirAll(filepath.Dir(fpath), os.ModePerm); err != nil {
  391. return err
  392. }
  393. outFile, err := os.OpenFile(fpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode())
  394. if err != nil {
  395. return err
  396. }
  397. rc, err := f.Open()
  398. if err != nil {
  399. return err
  400. }
  401. _, err = io.Copy(outFile, rc)
  402. outFile.Close()
  403. rc.Close()
  404. return err
  405. }
  406. func isValidUrl(uri string) bool {
  407. _, err := url.ParseRequestURI(uri)
  408. if err != nil {
  409. return false
  410. }
  411. u, err := url.Parse(uri)
  412. if err != nil || u.Scheme == "" || u.Host == "" {
  413. return false
  414. }
  415. return true
  416. }
  417. func downloadFile(filepath string, url string) error {
  418. // Get the data
  419. resp, err := http.Get(url)
  420. if err != nil {
  421. return err
  422. }
  423. if resp.StatusCode != http.StatusOK {
  424. return fmt.Errorf("cannot download the file with status: %s", resp.Status)
  425. }
  426. defer resp.Body.Close()
  427. // Create the file
  428. out, err := os.Create(filepath)
  429. if err != nil {
  430. return err
  431. }
  432. defer out.Close()
  433. // Write the body to file
  434. _, err = io.Copy(out, resp.Body)
  435. return err
  436. }
  437. func ucFirst(str string) string {
  438. for i, v := range str {
  439. return string(unicode.ToUpper(v)) + str[i+1:]
  440. }
  441. return ""
  442. }
  443. func lcFirst(str string) string {
  444. for i, v := range str {
  445. return string(unicode.ToLower(v)) + str[i+1:]
  446. }
  447. return ""
  448. }