manager.go 9.7 KB

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