app.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. package service
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/md5"
  6. "encoding/hex"
  7. "encoding/json"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "go-common/app/admin/main/config/model"
  12. "go-common/library/database/sql"
  13. "go-common/library/ecode"
  14. "go-common/library/log"
  15. "github.com/jinzhu/gorm"
  16. "github.com/satori/go.uuid"
  17. )
  18. var (
  19. rdsEnvs = []*model.Env{
  20. {Name: "dev", NikeName: "开发环境"},
  21. {Name: "fat1", NikeName: "功能环境1"},
  22. {Name: "uat", NikeName: "集成环境"},
  23. {Name: "pre", NikeName: "预发环境"},
  24. {Name: "prod", NikeName: "线上环境"},
  25. }
  26. opsEnvs = []*model.Env{
  27. {Name: "dev", NikeName: "开发环境"},
  28. {Name: "fat1", NikeName: "功能环境1"},
  29. {Name: "uat", NikeName: "集成环境"},
  30. }
  31. )
  32. // CreateApp create App.
  33. func (s *Service) CreateApp(name, env, zone string, treeID int64) error {
  34. bytes := [16]byte(uuid.NewV1())
  35. token := md5.Sum([]byte(hex.EncodeToString(bytes[:])))
  36. app := &model.App{Name: name, Env: env, Zone: zone, Token: hex.EncodeToString(token[:]), TreeID: treeID, Status: model.StatusShow}
  37. return s.dao.DB.Create(app).Error
  38. }
  39. // UpdateToken update token.
  40. func (s *Service) UpdateToken(c context.Context, env, zone string, treeID int64) (err error) {
  41. bytes := [16]byte(uuid.NewV1())
  42. token := hex.EncodeToString(bytes[:])
  43. if err = s.dao.DB.Model(&model.App{}).Where("tree_id =? AND env=? AND zone=?", treeID, env, zone).Update("token", token).Error; err != nil {
  44. return
  45. }
  46. err = s.SetToken(c, treeID, env, zone, token)
  47. return
  48. }
  49. // AppByTree get token by Name.
  50. func (s *Service) AppByTree(treeID int64, env, zone string) (app *model.App, err error) {
  51. app = &model.App{}
  52. row := s.dao.DB.Select("id,token").Where("tree_id=? AND env=? AND zone=?", treeID, env, zone).Model(&model.App{}).Row()
  53. if err = row.Scan(&app.ID, &app.Token); err != nil {
  54. log.Error("AppByTree(%v) err(%v)", treeID, err)
  55. if err == sql.ErrNoRows {
  56. err = ecode.NothingFound
  57. }
  58. }
  59. return
  60. }
  61. // AppsByTreeZone get token by Name and zone.
  62. func (s *Service) AppsByTreeZone(treeID int64, zone string) (apps []*model.App, err error) {
  63. if err = s.dao.DB.Select("id,env,token").Where("tree_id=? AND zone=?", treeID, zone).Find(&apps).Error; err != nil {
  64. log.Error("AppsByTreezone(%d) error(%v)", treeID, err)
  65. if err == sql.ErrNoRows {
  66. err = ecode.NothingFound
  67. }
  68. }
  69. return
  70. }
  71. // AppList get token by Name.
  72. func (s *Service) AppList(ctx context.Context, bu, team, name, env, zone string, ps, pn int64, nodes *model.CacheData, status int8) (pager *model.AppPager, err error) {
  73. var (
  74. like string
  75. apps []*model.App
  76. total int64
  77. ids []int64
  78. statusIn []int8
  79. )
  80. like = "%"
  81. if len(bu) != 0 {
  82. like = bu + ".%"
  83. }
  84. if len(team) != 0 {
  85. like = team + ".%"
  86. }
  87. if len(name) != 0 {
  88. like = "%.%.%" + name + "%"
  89. }
  90. if len(name) != 0 && len(team) != 0 {
  91. like = team + ".%" + name + "%"
  92. } else if len(name) != 0 && len(bu) != 0 {
  93. like = bu + ".%.%" + name + "%"
  94. }
  95. if status > 0 {
  96. statusIn = append(statusIn, status)
  97. } else {
  98. statusIn = []int8{model.StatusShow, model.StatusHidden}
  99. }
  100. for _, node := range nodes.Data {
  101. ids = append(ids, node.ID)
  102. }
  103. if err = s.dao.DB.Where("env=? AND zone=? AND name like ? AND tree_id in (?) And status in (?)", env, zone, like, ids, statusIn).
  104. Offset((pn - 1) * ps).Limit(ps).Find(&apps).Error; err != nil {
  105. log.Error("AppList() find page apps() error(%v)", err)
  106. return
  107. }
  108. if err = s.dao.DB.Model(&model.App{}).Where("env=? AND zone=? AND name like ? AND tree_id in (?) And status in (?)", env, zone, like, ids, statusIn).
  109. Count(&total).Error; err != nil {
  110. log.Error("AppList() count page apps() error(%v)", err)
  111. return
  112. }
  113. pager = &model.AppPager{Total: total, Pn: pn, Ps: ps, Items: apps}
  114. return
  115. }
  116. // Tree get service tree.
  117. func (s *Service) Tree(ctx context.Context, user string) (data interface{}, err error) {
  118. var (
  119. parme []byte
  120. msg map[string]interface{}
  121. tmp interface{}
  122. token string
  123. ok bool
  124. )
  125. if parme, err = json.Marshal(map[string]string{"user_name": user, "platform_id": s.c.Tree.Platform}); err != nil {
  126. log.Error("json.Marshal() error(%v)", err)
  127. return
  128. }
  129. if msg, err = s.dao.Token(ctx, string(parme)); err != nil {
  130. return
  131. }
  132. if tmp, ok = msg["token"]; !ok {
  133. err = ecode.NothingFound
  134. return
  135. }
  136. if token, ok = tmp.(string); !ok {
  137. err = ecode.NothingFound
  138. return
  139. }
  140. return s.dao.Tree(ctx, token)
  141. }
  142. // Node node.
  143. func (s *Service) Node(ctx context.Context, user, node, team, cookie string, nodes *model.CacheData) (res []*model.Node, err error) {
  144. var nNodes *model.CacheData
  145. //bu list.
  146. if node == "" && team == "" {
  147. if nNodes, err = s.SyncTree(ctx, user, cookie); err == nil {
  148. nodes = nNodes
  149. }
  150. tmp := make(map[string]struct{})
  151. for _, app := range nodes.Data {
  152. idx := strings.Index(app.Path, ".")
  153. bu := string([]byte(app.Path)[:idx])
  154. if _, ok := tmp[bu]; ok {
  155. continue
  156. }
  157. n := new(model.Node)
  158. n.Name = bu
  159. n.Path = bu
  160. res = append(res, n)
  161. tmp[bu] = struct{}{}
  162. }
  163. return
  164. }
  165. //team list.
  166. if node != "" && team == "" {
  167. tmp := make(map[string]struct{})
  168. for _, app := range nodes.Data {
  169. s := []byte(app.Path)
  170. sep := []byte(".")
  171. fidx := bytes.Index(s, sep)
  172. lidx := bytes.LastIndex(s, sep)
  173. team = string(s[:lidx])
  174. if node == string(s[:fidx]) {
  175. if _, ok := tmp[team]; ok {
  176. continue
  177. }
  178. n := new(model.Node)
  179. n.Name = string([]byte(app.Path)[fidx+1 : lidx])
  180. n.Path = team
  181. tmp[team] = struct{}{}
  182. res = append(res, n)
  183. }
  184. }
  185. return
  186. }
  187. //app list.
  188. if team == "" {
  189. return
  190. }
  191. for _, app := range nodes.Data {
  192. s := []byte(app.Path)
  193. sep := []byte(".")
  194. lidx := bytes.LastIndex(s, sep)
  195. t := string(s[:lidx])
  196. if team != t {
  197. continue
  198. }
  199. n := new(model.Node)
  200. n.Name = string(s[lidx+1:])
  201. n.Path = app.Path
  202. n.TreeID = app.ID
  203. res = append(res, n)
  204. }
  205. return
  206. }
  207. //Envs envs.
  208. func (s *Service) Envs(ctx context.Context, user, appName, zone string, treeID int64, nodes *model.CacheData) (envs []*model.Env, err error) {
  209. var (
  210. ok bool
  211. node *model.RoleNode
  212. apps []*model.App
  213. )
  214. envs = rdsEnvs
  215. if node, ok = nodes.Data[treeID]; !ok {
  216. return
  217. }
  218. if node.Role == model.Ops {
  219. envs = opsEnvs
  220. }
  221. apps, err = s.AppsByTreeZone(treeID, zone)
  222. for _, env := range envs {
  223. env.Token = ""
  224. for _, app := range apps {
  225. if app.Env == env.Name {
  226. env.Token = app.Token
  227. break
  228. }
  229. }
  230. }
  231. return
  232. }
  233. //EnvsByTeam envs.
  234. func (s *Service) EnvsByTeam(ctx context.Context, appName, zone string, nodes *model.CacheData) (envs []*model.Env, err error) {
  235. envs = rdsEnvs
  236. return
  237. }
  238. //SyncTree syncTree.
  239. func (s *Service) SyncTree(ctx context.Context, user string, cookie string) (nodes *model.CacheData, err error) {
  240. var (
  241. msg map[string]interface{}
  242. tmp interface{}
  243. token string
  244. ok bool
  245. )
  246. if msg, err = s.dao.Auth(ctx, cookie); err != nil {
  247. return
  248. }
  249. if tmp, ok = msg["token"]; !ok {
  250. err = ecode.NothingFound
  251. return
  252. }
  253. if token, ok = tmp.(string); !ok {
  254. err = ecode.NothingFound
  255. return
  256. }
  257. if nodes, err = s.dao.Role(ctx, user, token); err != nil {
  258. return
  259. }
  260. s.cLock.Lock()
  261. s.cache[user] = nodes
  262. s.cLock.Unlock()
  263. return
  264. }
  265. //AuthApps authApps.
  266. func (s *Service) AuthApps(ctx context.Context, user, cookie string) (nodes *model.CacheData, err error) {
  267. if len(user) == 0 {
  268. err = ecode.NothingFound
  269. return
  270. }
  271. var ok bool
  272. s.cLock.RLock()
  273. nodes, ok = s.cache[user]
  274. s.cLock.RUnlock()
  275. if !ok || (time.Since(nodes.CTime) > 60*time.Second) {
  276. s.SyncTree(ctx, user, cookie)
  277. s.cLock.RLock()
  278. nodes, ok = s.cache[user]
  279. s.cLock.RUnlock()
  280. if !ok {
  281. err = ecode.NothingFound
  282. }
  283. }
  284. return
  285. }
  286. //AuthApp authApp.
  287. func (s *Service) AuthApp(ctx context.Context, user, cookie string, treeID int64) (rule int8, err error) {
  288. var (
  289. ok bool
  290. node *model.RoleNode
  291. nodes *model.CacheData
  292. )
  293. if nodes, err = s.AuthApps(ctx, user, cookie); err != nil {
  294. return
  295. }
  296. if node, ok = nodes.Data[treeID]; !ok {
  297. err = ecode.AccessDenied
  298. return
  299. }
  300. return node.Role, nil
  301. }
  302. //ConfigGetTreeID ...
  303. func (s *Service) ConfigGetTreeID(configID int64) (TreeID int64, err error) {
  304. conf := new(model.Config)
  305. if err = s.dao.DB.First(&conf, configID).Error; err != nil {
  306. log.Error("ConfigGetTreeID(%v) error(%v)", configID, err)
  307. return
  308. }
  309. TreeID, err = s.AppIDGetTreeID(conf.AppID)
  310. return
  311. }
  312. //AppIDGetTreeID ...
  313. func (s *Service) AppIDGetTreeID(appID int64) (TreeID int64, err error) {
  314. app := new(model.App)
  315. if err = s.dao.DB.First(&app, appID).Error; err != nil {
  316. log.Error("AppIDGetTreeID(%v) error(%v)", appID, err)
  317. return
  318. }
  319. TreeID = app.TreeID
  320. return
  321. }
  322. //BuildGetTreeID ...
  323. func (s *Service) BuildGetTreeID(buildID int64) (TreeID int64, err error) {
  324. build := new(model.Build)
  325. if err = s.dao.DB.First(&build, buildID).Error; err != nil {
  326. log.Error("BuildGetTreeID(%v) error(%v)", buildID, err)
  327. return
  328. }
  329. TreeID, err = s.AppIDGetTreeID(build.AppID)
  330. return
  331. }
  332. //TagGetTreeID ...
  333. func (s *Service) TagGetTreeID(tagID int64) (TreeID int64, err error) {
  334. tag := new(model.Tag)
  335. if err = s.dao.DB.First(&tag, tagID).Error; err != nil {
  336. log.Error("TagGetTreeID(%v) error(%v)", tagID, err)
  337. return
  338. }
  339. TreeID, err = s.AppIDGetTreeID(tag.AppID)
  340. return
  341. }
  342. //ZoneCopy ...
  343. func (s *Service) ZoneCopy(ctx context.Context, AppName, From, To string, TreeID int64) (err error) {
  344. apps := []*model.App{}
  345. if err = s.dao.DB.Where("name = ? and tree_id = ? and zone = ?", AppName, TreeID, From).Find(&apps).Error; err != nil {
  346. log.Error("ZoneCopy from apps error(%v)", err)
  347. return
  348. }
  349. tx := s.dao.DB.Begin()
  350. for _, v := range apps {
  351. app := &model.App{}
  352. if err = s.dao.DB.Where("name = ? and tree_id = ? and zone = ? and env = ?", AppName, TreeID, To, v.Env).First(app).Error; err != nil {
  353. if err != gorm.ErrRecordNotFound {
  354. log.Error("ZoneCopy to app error(%v)", err)
  355. return
  356. }
  357. //add app
  358. if err = s.CreateApp(AppName, v.Env, To, TreeID); err != nil {
  359. log.Error("ZoneCopy add app error(%v)", err)
  360. return
  361. }
  362. if err = s.dao.DB.Where("name = ? and tree_id = ? and zone = ? and env = ?", AppName, TreeID, To, v.Env).First(app).Error; err != nil {
  363. log.Error("ZoneCopy first app error(%v)", err)
  364. return
  365. }
  366. }
  367. //
  368. configs := []*model.Config{}
  369. if err = tx.Where("app_id = ?", app.ID).Find(&configs).Error; err != nil {
  370. log.Error("ZoneCopy find configs error(%v)", err)
  371. tx.Rollback()
  372. return
  373. }
  374. builds := []*model.Build{}
  375. if err = tx.Where("app_id = ?", v.ID).Find(&builds).Error; err != nil {
  376. log.Error("ZoneCopy find builds error(%v)", err)
  377. tx.Rollback()
  378. return
  379. }
  380. for _, val := range builds {
  381. tag := &model.Tag{}
  382. if err = tx.First(tag, val.TagID).Error; err != nil {
  383. log.Error("ZoneCopy find tag error(%v)", err)
  384. tx.Rollback()
  385. return
  386. }
  387. configs = []*model.Config{}
  388. in := strings.Split(tag.ConfigIDs, ",")
  389. if err = tx.Where("id in (?)", in).Find(&configs).Error; err != nil {
  390. log.Error("ZoneCopy find build configs error(%v)", err)
  391. tx.Rollback()
  392. return
  393. }
  394. config := &model.Config{}
  395. var configIDS string
  396. for _, vvv := range configs {
  397. config = &model.Config{}
  398. config.Operator = vvv.Operator
  399. config.Name = vvv.Name
  400. config.Mark = vvv.Mark
  401. config.Comment = vvv.Comment
  402. config.State = vvv.State
  403. config.From = 0 //公共文件变私人文件
  404. if err = s.CreateConf(config, TreeID, v.Env, To, true); err != nil {
  405. log.Error("ZoneCopy config create error(%v)", err)
  406. tx.Rollback()
  407. return
  408. }
  409. if len(configIDS) > 0 {
  410. configIDS += ","
  411. }
  412. configIDS += strconv.FormatInt(config.ID, 10)
  413. }
  414. newTag := &model.Tag{}
  415. newTag.Operator = tag.Operator
  416. newTag.Mark = tag.Mark
  417. newTag.ConfigIDs = configIDS
  418. s.UpdateTag(ctx, TreeID, v.Env, To, val.Name, newTag)
  419. }
  420. }
  421. tx.Commit()
  422. return
  423. }
  424. // CanalCheckToken ...
  425. func (s *Service) CanalCheckToken(AppName, Env, Zone, Token string) (err error) {
  426. app := &model.App{}
  427. if err = s.dao.DB.Where("name = ? and env = ? and zone = ? and tree_id = ? and token = ?", AppName, Env, Zone, 3766, Token).First(app).Error; err != nil {
  428. log.Error("canalCheckToken error(%v)", err)
  429. }
  430. return
  431. }
  432. // CasterEnvs ...
  433. func (s *Service) CasterEnvs(zone string, treeID int64) (envs []*model.Env, err error) {
  434. var (
  435. apps []*model.App
  436. )
  437. envs = rdsEnvs
  438. apps, err = s.AppsByTreeZone(treeID, zone)
  439. for _, env := range envs {
  440. env.Token = ""
  441. for _, app := range apps {
  442. if app.Env == env.Name {
  443. env.Token = app.Token
  444. break
  445. }
  446. }
  447. }
  448. return
  449. }
  450. // AppRename ...
  451. func (s *Service) AppRename(treeID int64, user, cookie string) (err error) {
  452. var (
  453. ok bool
  454. node *model.RoleNode
  455. nodes *model.CacheData
  456. )
  457. s.cLock.RLock()
  458. nodes, ok = s.cache[user]
  459. s.cLock.RUnlock()
  460. if !ok {
  461. err = ecode.NothingFound
  462. return
  463. }
  464. if node, ok = nodes.Data[treeID]; !ok {
  465. err = ecode.AccessDenied
  466. return
  467. }
  468. if len(node.Path) == 0 {
  469. err = ecode.NothingFound
  470. return
  471. }
  472. if err = s.dao.DB.Model(&model.App{}).Where("tree_id =?", treeID).Update("name", node.Path).Error; err != nil {
  473. log.Error("AppRename update error(%v)", err)
  474. return
  475. }
  476. return
  477. }
  478. // GetApps ...
  479. func (s *Service) GetApps(env string) (apps []*model.App, err error) {
  480. if err = s.dao.DB.Where("env = ?", env).Find(&apps).Error; err != nil {
  481. log.Error("GetApps error(%v)", err)
  482. }
  483. return
  484. }
  485. // IdsGetApps ...
  486. func (s *Service) IdsGetApps(ids []int64) (apps []*model.App, err error) {
  487. if err = s.dao.DB.Where("id in (?)", ids).Find(&apps).Error; err != nil {
  488. log.Error("IdsGetApps error(%v)", err)
  489. }
  490. return
  491. }
  492. // UpAppStatus edit status.
  493. func (s *Service) UpAppStatus(ctx context.Context, status int8, treeID int64) (err error) {
  494. var (
  495. apps []*model.App
  496. )
  497. ups := map[string]interface{}{
  498. "status": status,
  499. }
  500. if err = s.dao.DB.Model(apps).Where("tree_id = ?", treeID).Updates(ups).Error; err != nil {
  501. log.Error("AppStatus error(%v) status(%v)", err, status)
  502. }
  503. return
  504. }