config.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package models
  15. import (
  16. "context"
  17. "database/sql"
  18. "fmt"
  19. "yunion.io/x/jsonutils"
  20. "yunion.io/x/log"
  21. "yunion.io/x/pkg/errors"
  22. "yunion.io/x/pkg/util/rbacscope"
  23. "yunion.io/x/pkg/util/sets"
  24. "yunion.io/x/pkg/utils"
  25. "yunion.io/x/sqlchemy"
  26. api "yunion.io/x/onecloud/pkg/apis/notify"
  27. "yunion.io/x/onecloud/pkg/cloudcommon/db"
  28. "yunion.io/x/onecloud/pkg/cloudcommon/db/taskman"
  29. "yunion.io/x/onecloud/pkg/httperrors"
  30. "yunion.io/x/onecloud/pkg/mcclient"
  31. "yunion.io/x/onecloud/pkg/mcclient/auth"
  32. "yunion.io/x/onecloud/pkg/notify/options"
  33. "yunion.io/x/onecloud/pkg/util/logclient"
  34. "yunion.io/x/onecloud/pkg/util/stringutils2"
  35. )
  36. type SConfigManager struct {
  37. db.SDomainLevelResourceBaseManager
  38. }
  39. var ConfigManager *SConfigManager
  40. var ConfigMap map[string]SConfig
  41. func init() {
  42. ConfigManager = &SConfigManager{
  43. SDomainLevelResourceBaseManager: db.NewDomainLevelResourceBaseManager(
  44. SConfig{},
  45. "configs_tbl",
  46. "notifyconfig",
  47. "notifyconfigs",
  48. ),
  49. }
  50. ConfigManager.SetVirtualObject(ConfigManager)
  51. }
  52. type SConfig struct {
  53. db.SDomainLevelResourceBase
  54. Type string `width:"15" nullable:"false" create:"required" get:"domain" list:"domain" index:"true"`
  55. Content *api.SNotifyConfigContent `nullable:"false" create:"required" update:"domain" get:"domain" list:"domain"`
  56. Attribution string `width:"8" nullable:"false" default:"system" get:"domain" list:"domain" create:"optional"`
  57. }
  58. func (cm *SConfigManager) ValidateCreateData(ctx context.Context, userCred mcclient.TokenCredential, ownerId mcclient.IIdentityProvider, query jsonutils.JSONObject, input api.ConfigCreateInput) (api.ConfigCreateInput, error) {
  59. var err error
  60. input.DomainLevelResourceCreateInput, err = cm.SDomainLevelResourceBaseManager.ValidateCreateData(ctx, userCred, ownerId, query, input.DomainLevelResourceCreateInput)
  61. if err != nil {
  62. return input, err
  63. }
  64. if !utils.IsInStringArray(input.Type, GetSenderTypes()) {
  65. return input, httperrors.NewInputParameterError("unkown type %s allow: %s", input.Type, GetSenderTypes())
  66. }
  67. if !utils.IsInStringArray(input.Attribution, []string{api.CONFIG_ATTRIBUTION_SYSTEM, api.CONFIG_ATTRIBUTION_DOMAIN}) {
  68. return input, httperrors.NewInputParameterError("invalid attribution, need %q or %q", api.CONFIG_ATTRIBUTION_SYSTEM, api.CONFIG_ATTRIBUTION_DOMAIN)
  69. }
  70. if input.Content == nil {
  71. return input, httperrors.NewMissingParameterError("content")
  72. }
  73. config, err := cm.Config(input.Type, input.ProjectDomainId, input.Attribution)
  74. if config != nil {
  75. return input, httperrors.NewDuplicateResourceError("duplicate type %q", input.Type)
  76. }
  77. if err != nil && errors.Cause(err) != sql.ErrNoRows {
  78. return input, err
  79. }
  80. driver := GetDriver(input.Type)
  81. // validate
  82. if input.Type != api.MOBILE {
  83. message, err := driver.ValidateConfig(ctx, api.NotifyConfig{
  84. SNotifyConfigContent: *input.Content,
  85. Attribution: input.Attribution,
  86. DomainId: input.ProjectDomainId,
  87. })
  88. if err != nil {
  89. return input, errors.Wrapf(err, "%s", message)
  90. }
  91. }
  92. if len(input.Name) == 0 {
  93. input.Name = input.Type
  94. }
  95. return input, nil
  96. }
  97. func (manager *SConfigManager) GetPropertyCapability(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject) (jsonutils.JSONObject, error) {
  98. q := manager.Query()
  99. configs := []SConfig{}
  100. err := db.FetchModelObjects(manager, q, &configs)
  101. if err != nil {
  102. return nil, err
  103. }
  104. ret := struct {
  105. System []string `json:"system,allowempty"`
  106. Domain map[string][]string `json:"domain,allowempty"`
  107. }{
  108. System: []string{},
  109. Domain: map[string][]string{},
  110. }
  111. for _, config := range configs {
  112. switch config.Attribution {
  113. case api.CONFIG_ATTRIBUTION_SYSTEM:
  114. ret.System = append(ret.System, config.Type)
  115. case api.CONFIG_ATTRIBUTION_DOMAIN:
  116. _, ok := ret.Domain[config.DomainId]
  117. if !ok {
  118. ret.Domain[config.DomainId] = []string{}
  119. }
  120. ret.Domain[config.DomainId] = append(ret.Domain[config.DomainId], config.Type)
  121. }
  122. }
  123. return jsonutils.Marshal(ret), nil
  124. }
  125. func (c *SConfig) PostCreate(ctx context.Context, userCred mcclient.TokenCredential, ownerId mcclient.IIdentityProvider, query jsonutils.JSONObject, data jsonutils.JSONObject) {
  126. c.SDomainLevelResourceBase.PostCreate(ctx, userCred, ownerId, query, data)
  127. err := c.StartRepullSubcontactTask(ctx, userCred, false)
  128. if err != nil {
  129. log.Errorf("unable to StartRepullSubcontactTask: %v", err)
  130. }
  131. driver := GetDriver(c.Type)
  132. driver.RegisterConfig(*c)
  133. }
  134. func (c *SConfig) GetNotifyConfig() api.NotifyConfig {
  135. return api.NotifyConfig{
  136. SNotifyConfigContent: *c.Content,
  137. Attribution: c.Attribution,
  138. DomainId: c.DomainId,
  139. }
  140. }
  141. func (c *SConfig) ValidateUpdateData(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, input api.ConfigUpdateInput) (api.ConfigUpdateInput, error) {
  142. q := ConfigManager.Query()
  143. q = q.Equals("type", c.Type)
  144. confs := []SConfig{}
  145. err := db.FetchModelObjects(ConfigManager, q, &confs)
  146. if err != nil {
  147. return input, errors.Wrapf(err, "config type:%s", c.Type)
  148. }
  149. if len(confs) == 0 {
  150. return input, errors.Wrapf(errors.ErrNotFound, "config type:%s", c.Type)
  151. }
  152. // check if changed
  153. if input.Content != nil {
  154. driver := GetDriver(c.Type)
  155. if c.Type != api.MOBILE {
  156. message, err := driver.ValidateConfig(ctx, api.NotifyConfig{
  157. SNotifyConfigContent: *input.Content,
  158. Attribution: c.Attribution,
  159. DomainId: c.DomainId,
  160. })
  161. if err != nil {
  162. return input, errors.Wrapf(err, "%s", message)
  163. }
  164. }
  165. }
  166. return input, nil
  167. }
  168. func (c *SConfig) PostUpdate(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, data jsonutils.JSONObject) {
  169. c.SStandaloneResourceBase.PostUpdate(ctx, userCred, query, data)
  170. config := c.GetNotifyConfig()
  171. ConfigMap[fmt.Sprintf("%s-%s", c.Type, c.DomainId)] = SConfig{
  172. Content: &config.SNotifyConfigContent,
  173. }
  174. err := c.StartRepullSubcontactTask(ctx, userCred, false)
  175. if err != nil {
  176. log.Errorf("unable to StartRepullSubcontactTask: %v", err)
  177. }
  178. }
  179. func (c *SConfig) PreDelete(ctx context.Context, userCred mcclient.TokenCredential) {
  180. c.SStandaloneResourceBase.PreDelete(ctx, userCred)
  181. key := fmt.Sprintf("%s-%s", c.Type, c.DomainId)
  182. if c.Type == api.MOBILE || c.Type == api.EMAIL {
  183. key = c.Type
  184. }
  185. delete(ConfigMap, key)
  186. }
  187. func (c *SConfig) CustomizeDelete(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, data jsonutils.JSONObject) error {
  188. err := c.SStandaloneResourceBase.CustomizeDelete(ctx, userCred, query, data)
  189. if err != nil {
  190. return err
  191. }
  192. return c.StartRepullSubcontactTask(ctx, userCred, true)
  193. }
  194. func (c *SConfig) Delete(ctx context.Context, userCred mcclient.TokenCredential) error {
  195. return nil
  196. }
  197. func (c *SConfig) RealDelete(ctx context.Context, userCred mcclient.TokenCredential) error {
  198. delete(ConfigMap, fmt.Sprintf("%s-%s", c.Type, c.DomainId))
  199. return c.SDomainLevelResourceBase.Delete(ctx, userCred)
  200. }
  201. func (self *SConfig) GetReceivers() ([]SReceiver, error) {
  202. subq := SubContactManager.Query("receiver_id").Equals("type", self.Type).SubQuery()
  203. q := ReceiverManager.Query()
  204. if self.Attribution == api.CONFIG_ATTRIBUTION_DOMAIN {
  205. q = q.Equals("domain_id", self.DomainId)
  206. } else {
  207. // The system-level config update should not affect the receiver under the domain with config
  208. configq := ConfigManager.Query("domain_id").Equals("type", self.Type).Equals("attribution", api.CONFIG_ATTRIBUTION_DOMAIN).SubQuery()
  209. q = q.NotIn("domain_id", configq)
  210. }
  211. q = q.Join(subq, sqlchemy.Equals(q.Field("id"), subq.Field("receiver_id")))
  212. ret := []SReceiver{}
  213. err := db.FetchModelObjects(ReceiverManager, q, &ret)
  214. return ret, err
  215. }
  216. func (c *SConfig) StartRepullSubcontactTask(ctx context.Context, userCred mcclient.TokenCredential, del bool) error {
  217. taskData := jsonutils.NewDict()
  218. if del {
  219. taskData.Set("deleted", jsonutils.JSONTrue)
  220. }
  221. task, err := taskman.TaskManager.NewTask(ctx, "RepullSuncontactTask", c, userCred, taskData, "", "")
  222. if err != nil {
  223. return err
  224. }
  225. task.ScheduleRun(nil)
  226. return nil
  227. }
  228. var sortedCTypes = []string{
  229. api.WEBCONSOLE, api.EMAIL, api.MOBILE, api.DINGTALK, api.FEISHU, api.WORKWX,
  230. }
  231. func sortContactType(ctypes []string) []string {
  232. ctSet := sets.NewString(ctypes...)
  233. ret := make([]string, 0, len(ctypes))
  234. for _, ct := range sortedCTypes {
  235. if ctSet.Has(ct) {
  236. ret = append(ret, ct)
  237. }
  238. }
  239. return ret
  240. }
  241. func (cm *SConfigManager) contactTypesQuery(domainId string) *sqlchemy.SQuery {
  242. q := cm.Query("type").Distinct()
  243. if domainId == "" {
  244. q = q.Equals("attribution", api.CONFIG_ATTRIBUTION_SYSTEM)
  245. } else {
  246. q = q.Filter(sqlchemy.OR(sqlchemy.AND(sqlchemy.Equals(q.Field("attribution"), api.CONFIG_ATTRIBUTION_DOMAIN), sqlchemy.Equals(q.Field("domain_id"), domainId)), sqlchemy.Equals(q.Field("attribution"), api.CONFIG_ATTRIBUTION_SYSTEM)))
  247. }
  248. return q
  249. }
  250. func (cm *SConfigManager) availableContactTypes(domainId string) ([]string, error) {
  251. q := cm.Query("type")
  252. q = q.Filter(sqlchemy.OR(sqlchemy.AND(sqlchemy.Equals(q.Field("attribution"), api.CONFIG_ATTRIBUTION_DOMAIN), sqlchemy.Equals(q.Field("domain_id"), domainId)), sqlchemy.Equals(q.Field("attribution"), api.CONFIG_ATTRIBUTION_SYSTEM)))
  253. allTypes := make([]struct {
  254. Type string
  255. }, 0, 3)
  256. err := q.All(&allTypes)
  257. if err != nil {
  258. return nil, err
  259. }
  260. ret := make([]string, len(allTypes))
  261. for i := range ret {
  262. ret[i] = allTypes[i].Type
  263. }
  264. // De-duplication
  265. return sets.NewString(ret...).UnsortedList(), nil
  266. }
  267. func (cm *SConfigManager) allContactType(domainid string) ([]string, error) {
  268. q := cm.Query("type")
  269. q = q.Equals("domain_id", domainid)
  270. allTypes := make([]struct {
  271. Type string
  272. }, 0, 3)
  273. err := q.All(&allTypes)
  274. if err != nil {
  275. return nil, err
  276. }
  277. ret := make([]string, len(allTypes))
  278. for i := range ret {
  279. ret[i] = allTypes[i].Type
  280. }
  281. return ret, nil
  282. }
  283. func (self *SConfigManager) ListItemFilter(ctx context.Context, q *sqlchemy.SQuery, userCred mcclient.TokenCredential, input api.ConfigListInput) (*sqlchemy.SQuery, error) {
  284. q, err := self.SDomainLevelResourceBaseManager.ListItemFilter(ctx, q, userCred, input.DomainLevelResourceListInput)
  285. if err != nil {
  286. return nil, err
  287. }
  288. q = q.NotEquals("type", api.WEBCONSOLE)
  289. if len(input.Type) > 0 {
  290. q.Filter(sqlchemy.Equals(q.Field("type"), input.Type))
  291. }
  292. if len(input.Attribution) > 0 {
  293. q = q.Equals("attribution", input.Attribution)
  294. }
  295. return q, nil
  296. }
  297. func (manager *SConfigManager) ListItemExportKeys(ctx context.Context, q *sqlchemy.SQuery, userCred mcclient.TokenCredential, keys stringutils2.SSortedStrings) (*sqlchemy.SQuery, error) {
  298. return manager.SDomainLevelResourceBaseManager.ListItemExportKeys(ctx, q, userCred, keys)
  299. }
  300. func (cm *SConfigManager) FetchCustomizeColumns(
  301. ctx context.Context,
  302. userCred mcclient.TokenCredential,
  303. query jsonutils.JSONObject,
  304. objs []interface{},
  305. fields stringutils2.SSortedStrings,
  306. isList bool,
  307. ) []api.ConfigDetails {
  308. sRows := cm.SDomainLevelResourceBaseManager.FetchCustomizeColumns(ctx, userCred, query, objs, fields, isList)
  309. rows := make([]api.ConfigDetails, len(objs))
  310. for i := range rows {
  311. rows[i].DomainLevelResourceDetails = sRows[i]
  312. }
  313. return rows
  314. }
  315. func (cm *SConfigManager) QueryDistinctExtraField(q *sqlchemy.SQuery, field string) (*sqlchemy.SQuery, error) {
  316. q, err := cm.SDomainLevelResourceBaseManager.QueryDistinctExtraField(q, field)
  317. if err != nil {
  318. return q, nil
  319. }
  320. return q, nil
  321. }
  322. func (cm *SConfigManager) OrderByExtraFields(ctx context.Context, q *sqlchemy.SQuery, userCred mcclient.TokenCredential, query api.ConfigListInput) (*sqlchemy.SQuery, error) {
  323. q, err := cm.SDomainLevelResourceBaseManager.OrderByExtraFields(ctx, q, userCred, query.DomainLevelResourceListInput)
  324. if err != nil {
  325. return nil, err
  326. }
  327. return q, nil
  328. }
  329. func (cm *SConfigManager) PerformValidate(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, input api.ConfigValidateInput) (api.ConfigValidateOutput, error) {
  330. output := api.ConfigValidateOutput{}
  331. if !utils.IsInStringArray(input.Type, GetSenderTypes()) {
  332. return output, httperrors.NewInputParameterError("unkown type %q", input.Type)
  333. }
  334. if input.Content == nil {
  335. return output, httperrors.NewMissingParameterError("content")
  336. }
  337. // validate
  338. driver := GetDriver(input.Type)
  339. message, err := driver.ValidateConfig(ctx, api.NotifyConfig{
  340. SNotifyConfigContent: *input.Content,
  341. DomainId: userCred.GetDomainId(),
  342. })
  343. if err != nil {
  344. return output, errors.Wrapf(err, "%s", message)
  345. }
  346. output.IsValid = true
  347. output.Message = message
  348. return output, nil
  349. }
  350. func (confManager *SConfigManager) InitializeData() error {
  351. q := confManager.Query()
  352. res := []SConfig{}
  353. err := db.FetchModelObjects(confManager, q, &res)
  354. if err != nil {
  355. return errors.Wrap(err, "init configMap err")
  356. }
  357. ConfigMap = make(map[string]SConfig)
  358. for _, config := range res {
  359. driver := GetDriver(config.Type)
  360. driver.RegisterConfig(config)
  361. err := driver.GetAccessToken(context.Background(), config.DomainId)
  362. if err != nil {
  363. session := auth.GetAdminSession(context.Background(), options.Options.Region)
  364. logclient.AddSimpleActionLog(&config, logclient.ACT_INIT_NOTIFY_CONFIGMAP, err, session.GetToken(), false)
  365. }
  366. }
  367. log.Infoln("init ConfigMap:", jsonutils.Marshal(ConfigMap))
  368. return nil
  369. }
  370. func (cm *SConfigManager) FilterByOwner(ctx context.Context, q *sqlchemy.SQuery, man db.FilterByOwnerProvider, userCred mcclient.TokenCredential, owner mcclient.IIdentityProvider, scope rbacscope.TRbacScope) *sqlchemy.SQuery {
  371. switch scope {
  372. case rbacscope.ScopeDomain, rbacscope.ScopeProject:
  373. q = q.Equals("attribution", api.CONFIG_ATTRIBUTION_DOMAIN)
  374. if owner != nil {
  375. q = q.Equals("domain_id", owner.GetProjectDomainId())
  376. }
  377. }
  378. return q
  379. }
  380. // Fetch all SConfig struct which type is contactType.
  381. func (self *SConfigManager) Configs(contactType string) ([]SConfig, error) {
  382. var configs = make([]SConfig, 0, 2)
  383. q := self.Query()
  384. q.Filter(sqlchemy.Equals(q.Field("type"), contactType))
  385. err := q.All(&configs)
  386. if err != nil {
  387. return nil, errors.Wrapf(err, "fail to fetch SConfigs by type %s", contactType)
  388. }
  389. return configs, nil
  390. }
  391. func (self *SConfigManager) Config(contactType, domainId string, attribution string) (*SConfig, error) {
  392. q := self.Query()
  393. q = q.Equals("type", contactType).Equals("attribution", attribution)
  394. if attribution == api.CONFIG_ATTRIBUTION_DOMAIN {
  395. q = q.Equals("domain_id", domainId)
  396. }
  397. var config SConfig
  398. err := q.First(&config)
  399. if err != nil {
  400. return nil, errors.Wrapf(err, "fail to fetch SConfig by type %s and domain %s", contactType, domainId)
  401. }
  402. return &config, nil
  403. }
  404. func (self *SConfigManager) HasSystemConfig(contactType string) (bool, error) {
  405. q := self.Query().Equals("type", contactType).Equals("attribution", api.CONFIG_ATTRIBUTION_SYSTEM)
  406. c, err := q.CountWithError()
  407. if err != nil {
  408. return false, err
  409. }
  410. return c > 0, nil
  411. }