ai_gateway.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  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. "yunion.io/x/cloudmux/pkg/cloudprovider"
  18. "yunion.io/x/jsonutils"
  19. "yunion.io/x/pkg/errors"
  20. "yunion.io/x/pkg/util/compare"
  21. "yunion.io/x/sqlchemy"
  22. "yunion.io/x/onecloud/pkg/apis"
  23. api "yunion.io/x/onecloud/pkg/apis/compute"
  24. "yunion.io/x/onecloud/pkg/cloudcommon/db"
  25. "yunion.io/x/onecloud/pkg/cloudcommon/db/lockman"
  26. "yunion.io/x/onecloud/pkg/cloudcommon/db/taskman"
  27. "yunion.io/x/onecloud/pkg/cloudcommon/notifyclient"
  28. "yunion.io/x/onecloud/pkg/cloudcommon/validators"
  29. "yunion.io/x/onecloud/pkg/compute/options"
  30. "yunion.io/x/onecloud/pkg/httperrors"
  31. "yunion.io/x/onecloud/pkg/mcclient"
  32. "yunion.io/x/onecloud/pkg/util/stringutils2"
  33. )
  34. type SAiGatewayManager struct {
  35. db.SVirtualResourceBaseManager
  36. db.SExternalizedResourceBaseManager
  37. SManagedResourceBaseManager
  38. }
  39. var AiGatewayManager *SAiGatewayManager
  40. func init() {
  41. AiGatewayManager = &SAiGatewayManager{
  42. SVirtualResourceBaseManager: db.NewVirtualResourceBaseManager(
  43. SAiGateway{},
  44. "ai_gateways_tbl",
  45. "ai_gateway",
  46. "ai_gateways",
  47. ),
  48. }
  49. AiGatewayManager.SetVirtualObject(AiGatewayManager)
  50. }
  51. type SAiGateway struct {
  52. db.SVirtualResourceBase
  53. db.SExternalizedResourceBase
  54. SManagedResourceBase
  55. Authentication bool `default:"false" list:"user" create:"optional"`
  56. CacheInvalidateOnUpdate bool `default:"false" list:"user" create:"optional"`
  57. CacheTTL int `default:"0" list:"user" create:"optional"`
  58. CollectLogs bool `default:"false" list:"user" create:"optional"`
  59. RateLimitingInterval int `default:"0" list:"user" create:"optional"`
  60. RateLimitingLimit int `default:"0" list:"user" create:"optional"`
  61. RateLimitingTechnique string `width:"32" charset:"ascii" default:"" list:"user" create:"optional"`
  62. }
  63. // AI网关列表
  64. func (manager *SAiGatewayManager) ListItemFilter(
  65. ctx context.Context,
  66. q *sqlchemy.SQuery,
  67. userCred mcclient.TokenCredential,
  68. query api.AiGatewayListInput,
  69. ) (*sqlchemy.SQuery, error) {
  70. var err error
  71. q, err = manager.SExternalizedResourceBaseManager.ListItemFilter(ctx, q, userCred, query.ExternalizedResourceBaseListInput)
  72. if err != nil {
  73. return nil, errors.Wrap(err, "SExternalizedResourceBaseManager.ListItemFilter")
  74. }
  75. q, err = manager.SVirtualResourceBaseManager.ListItemFilter(ctx, q, userCred, query.VirtualResourceListInput)
  76. if err != nil {
  77. return nil, errors.Wrap(err, "SVirtualResourceBaseManager.ListItemFilter")
  78. }
  79. q, err = manager.SManagedResourceBaseManager.ListItemFilter(ctx, q, userCred, query.ManagedResourceListInput)
  80. if err != nil {
  81. return nil, err
  82. }
  83. return q, nil
  84. }
  85. func (manager *SAiGatewayManager) OrderByExtraFields(
  86. ctx context.Context,
  87. q *sqlchemy.SQuery,
  88. userCred mcclient.TokenCredential,
  89. query api.AiGatewayListInput,
  90. ) (*sqlchemy.SQuery, error) {
  91. var err error
  92. q, err = manager.SVirtualResourceBaseManager.OrderByExtraFields(ctx, q, userCred, query.VirtualResourceListInput)
  93. if err != nil {
  94. return nil, errors.Wrap(err, "SVirtualResourceBaseManager.OrderByExtraFields")
  95. }
  96. return q, nil
  97. }
  98. func (manager *SAiGatewayManager) QueryDistinctExtraField(q *sqlchemy.SQuery, field string) (*sqlchemy.SQuery, error) {
  99. var err error
  100. q, err = manager.SVirtualResourceBaseManager.QueryDistinctExtraField(q, field)
  101. if err == nil {
  102. return q, nil
  103. }
  104. q, err = manager.SManagedResourceBaseManager.QueryDistinctExtraField(q, field)
  105. if err == nil {
  106. return q, nil
  107. }
  108. return q, httperrors.ErrNotFound
  109. }
  110. func (manager *SAiGatewayManager) QueryDistinctExtraFields(q *sqlchemy.SQuery, resource string, fields []string) (*sqlchemy.SQuery, error) {
  111. var err error
  112. q, err = manager.SManagedResourceBaseManager.QueryDistinctExtraFields(q, resource, fields)
  113. if err == nil {
  114. return q, nil
  115. }
  116. return q, httperrors.ErrNotFound
  117. }
  118. func (self *SAiGateway) ValidateUpdateData(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, input *api.AiGatewayUpdateInput) (*api.AiGatewayUpdateInput, error) {
  119. var err error
  120. input.VirtualResourceBaseUpdateInput, err = self.SVirtualResourceBase.ValidateUpdateData(ctx, userCred, query, input.VirtualResourceBaseUpdateInput)
  121. if err != nil {
  122. return input, errors.Wrap(err, "SVirtualResourceBase.ValidateUpdateData")
  123. }
  124. return input, nil
  125. }
  126. func (manager *SAiGatewayManager) ValidateCreateData(
  127. ctx context.Context,
  128. userCred mcclient.TokenCredential,
  129. ownerId mcclient.IIdentityProvider,
  130. query jsonutils.JSONObject,
  131. input *api.AiGatewayCreateInput,
  132. ) (*api.AiGatewayCreateInput, error) {
  133. var err error
  134. input.VirtualResourceCreateInput, err = manager.SVirtualResourceBaseManager.ValidateCreateData(ctx, userCred, ownerId, query, input.VirtualResourceCreateInput)
  135. if err != nil {
  136. return input, errors.Wrap(err, "SVirtualResourceBaseManager.ValidateCreateData")
  137. }
  138. if len(input.CloudproviderId) > 0 {
  139. obj, err := validators.ValidateModel(ctx, userCred, CloudproviderManager, &input.CloudproviderId)
  140. if err != nil {
  141. return nil, err
  142. }
  143. input.ManagerId = obj.GetId()
  144. }
  145. input.Status = apis.STATUS_CREATING
  146. return input, nil
  147. }
  148. func (self *SAiGateway) PostCreate(ctx context.Context, userCred mcclient.TokenCredential, ownerId mcclient.IIdentityProvider, query jsonutils.JSONObject, data jsonutils.JSONObject) {
  149. self.SVirtualResourceBase.PostCreate(ctx, userCred, ownerId, query, data)
  150. self.StartAiGatewayCreateTask(ctx, userCred, "")
  151. }
  152. func (self *SAiGateway) StartAiGatewayCreateTask(ctx context.Context, userCred mcclient.TokenCredential, parentTaskId string) error {
  153. kwargs := jsonutils.NewDict()
  154. task, err := taskman.TaskManager.NewTask(ctx, "AiGatewayCreateTask", self, userCred, kwargs, parentTaskId, "", nil)
  155. if err != nil {
  156. return err
  157. }
  158. return task.ScheduleRun(nil)
  159. }
  160. func (self *SAiGateway) GetProvider(ctx context.Context) (cloudprovider.ICloudProvider, error) {
  161. if len(self.ManagerId) == 0 {
  162. return nil, errors.Wrapf(cloudprovider.ErrNotFound, "empty manager id")
  163. }
  164. provider := self.GetCloudprovider()
  165. if provider == nil {
  166. return nil, errors.Wrapf(cloudprovider.ErrNotFound, "failed to found provider")
  167. }
  168. return provider.GetProvider(ctx)
  169. }
  170. func (self *SAiGateway) GetIAiGateway(ctx context.Context) (cloudprovider.IAiGateway, error) {
  171. if len(self.ExternalId) == 0 {
  172. return nil, errors.Wrapf(cloudprovider.ErrNotFound, "empty external id")
  173. }
  174. provider, err := self.GetProvider(ctx)
  175. if err != nil {
  176. return nil, errors.Wrapf(err, "GetProvider")
  177. }
  178. ret, err := provider.GetIAiGatewayById(self.ExternalId)
  179. if err != nil {
  180. return nil, errors.Wrapf(err, "GetIAiGatewayById(%s)", self.ExternalId)
  181. }
  182. return ret, nil
  183. }
  184. func (provider *SCloudprovider) GetAiGateways() ([]SAiGateway, error) {
  185. q := AiGatewayManager.Query().Equals("manager_id", provider.Id)
  186. gateways := make([]SAiGateway, 0)
  187. err := db.FetchModelObjects(AiGatewayManager, q, &gateways)
  188. if err != nil {
  189. return nil, errors.Wrapf(err, "FetchModelObjects")
  190. }
  191. return gateways, nil
  192. }
  193. func (provider *SCloudprovider) SyncAiGateways(ctx context.Context, userCred mcclient.TokenCredential, gateways []cloudprovider.IAiGateway, xor bool) compare.SyncResult {
  194. lockman.LockRawObject(ctx, AiGatewayManager.Keyword(), provider.Id)
  195. defer lockman.ReleaseRawObject(ctx, AiGatewayManager.Keyword(), provider.Id)
  196. result := compare.SyncResult{}
  197. dbGateways, err := provider.GetAiGateways()
  198. if err != nil {
  199. result.Error(err)
  200. return result
  201. }
  202. removed := make([]SAiGateway, 0)
  203. commondb := make([]SAiGateway, 0)
  204. commonext := make([]cloudprovider.IAiGateway, 0)
  205. added := make([]cloudprovider.IAiGateway, 0)
  206. err = compare.CompareSets(dbGateways, gateways, &removed, &commondb, &commonext, &added)
  207. if err != nil {
  208. result.Error(err)
  209. return result
  210. }
  211. for i := 0; i < len(removed); i += 1 {
  212. err = removed[i].syncRemove(ctx, userCred)
  213. if err != nil {
  214. result.DeleteError(err)
  215. } else {
  216. result.Delete()
  217. }
  218. }
  219. if !xor {
  220. for i := 0; i < len(commondb); i += 1 {
  221. err = commondb[i].SyncWithCloudAiGateway(ctx, userCred, commonext[i])
  222. if err != nil {
  223. result.UpdateError(err)
  224. continue
  225. }
  226. result.Update()
  227. }
  228. }
  229. for i := 0; i < len(added); i += 1 {
  230. err := provider.newFromCloudAiGateway(ctx, userCred, added[i])
  231. if err != nil {
  232. result.AddError(err)
  233. continue
  234. }
  235. result.Add()
  236. }
  237. return result
  238. }
  239. func (self *SAiGateway) syncRemove(ctx context.Context, userCred mcclient.TokenCredential) error {
  240. lockman.LockObject(ctx, self)
  241. defer lockman.ReleaseObject(ctx, self)
  242. err := self.RealDelete(ctx, userCred)
  243. if err != nil {
  244. return err
  245. }
  246. return nil
  247. }
  248. func (self *SAiGateway) SyncWithCloudAiGateway(ctx context.Context, userCred mcclient.TokenCredential, extAiGateway cloudprovider.IAiGateway) error {
  249. diff, err := db.UpdateWithLock(ctx, self, func() error {
  250. if options.Options.EnableSyncName {
  251. newName, _ := db.GenerateAlterName(self, extAiGateway.GetName())
  252. if len(newName) > 0 {
  253. self.Name = newName
  254. }
  255. }
  256. self.ExternalId = extAiGateway.GetGlobalId()
  257. self.Authentication = extAiGateway.IsAuthentication()
  258. self.CacheInvalidateOnUpdate = extAiGateway.IsCacheInvalidateOnUpdate()
  259. self.CacheTTL = extAiGateway.GetCacheTTL()
  260. self.CollectLogs = extAiGateway.IsCollectLogs()
  261. self.RateLimitingInterval = extAiGateway.GetRateLimitingInterval()
  262. self.RateLimitingLimit = extAiGateway.GetRateLimitingLimit()
  263. self.RateLimitingTechnique = extAiGateway.GetRateLimitingTechnique()
  264. self.Status = extAiGateway.GetStatus()
  265. return nil
  266. })
  267. if err != nil {
  268. return errors.Wrapf(err, "db.UpdateWithLock")
  269. }
  270. if len(diff) > 0 {
  271. db.OpsLog.LogSyncUpdate(self, diff, userCred)
  272. }
  273. return nil
  274. }
  275. func (provider *SCloudprovider) newFromCloudAiGateway(ctx context.Context, userCred mcclient.TokenCredential, extAiGateway cloudprovider.IAiGateway) error {
  276. gateway := SAiGateway{}
  277. gateway.SetModelManager(AiGatewayManager, &gateway)
  278. gateway.Status = extAiGateway.GetStatus()
  279. gateway.ExternalId = extAiGateway.GetGlobalId()
  280. gateway.ManagerId = provider.Id
  281. gateway.Authentication = extAiGateway.IsAuthentication()
  282. gateway.CacheInvalidateOnUpdate = extAiGateway.IsCacheInvalidateOnUpdate()
  283. gateway.CacheTTL = extAiGateway.GetCacheTTL()
  284. gateway.CollectLogs = extAiGateway.IsCollectLogs()
  285. gateway.RateLimitingInterval = extAiGateway.GetRateLimitingInterval()
  286. gateway.RateLimitingLimit = extAiGateway.GetRateLimitingLimit()
  287. gateway.RateLimitingTechnique = extAiGateway.GetRateLimitingTechnique()
  288. if createAt := extAiGateway.GetCreatedAt(); !createAt.IsZero() {
  289. gateway.CreatedAt = createAt
  290. }
  291. var err = func() error {
  292. lockman.LockRawObject(ctx, AiGatewayManager.Keyword(), "name")
  293. defer lockman.ReleaseRawObject(ctx, AiGatewayManager.Keyword(), "name")
  294. newName, err := db.GenerateName(ctx, AiGatewayManager, provider.GetOwnerId(), extAiGateway.GetName())
  295. if err != nil {
  296. return err
  297. }
  298. gateway.Name = newName
  299. return AiGatewayManager.TableSpec().Insert(ctx, &gateway)
  300. }()
  301. if err != nil {
  302. return errors.Wrapf(err, "newFromCloudAiGateway")
  303. }
  304. syncVirtualResourceMetadata(ctx, userCred, &gateway, extAiGateway, false)
  305. SyncCloudProject(ctx, userCred, &gateway, provider.GetOwnerId(), extAiGateway, provider)
  306. db.OpsLog.LogEvent(&gateway, db.ACT_CREATE, gateway.GetShortDesc(ctx), userCred)
  307. notifyclient.EventNotify(ctx, userCred, notifyclient.SEventNotifyParam{
  308. Obj: &gateway,
  309. Action: notifyclient.ActionSyncCreate,
  310. })
  311. return nil
  312. }
  313. func (self *SAiGateway) Delete(ctx context.Context, userCred mcclient.TokenCredential) error {
  314. return nil
  315. }
  316. func (self *SAiGateway) RealDelete(ctx context.Context, userCred mcclient.TokenCredential) error {
  317. return self.SVirtualResourceBase.Delete(ctx, userCred)
  318. }
  319. func (self *SAiGateway) CustomizeDelete(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, data jsonutils.JSONObject) error {
  320. return self.StartAiGatewayDeleteTask(ctx, userCred, "")
  321. }
  322. func (manager *SAiGatewayManager) FetchCustomizeColumns(
  323. ctx context.Context,
  324. userCred mcclient.TokenCredential,
  325. query jsonutils.JSONObject,
  326. objs []interface{},
  327. fields stringutils2.SSortedStrings,
  328. isList bool,
  329. ) []api.AiGatewayDetails {
  330. rows := make([]api.AiGatewayDetails, len(objs))
  331. virtRows := manager.SVirtualResourceBaseManager.FetchCustomizeColumns(ctx, userCred, query, objs, fields, isList)
  332. managedRows := manager.SManagedResourceBaseManager.FetchCustomizeColumns(ctx, userCred, query, objs, fields, isList)
  333. for i := range rows {
  334. rows[i] = api.AiGatewayDetails{
  335. VirtualResourceDetails: virtRows[i],
  336. ManagedResourceInfo: managedRows[i],
  337. }
  338. }
  339. return rows
  340. }
  341. func (self *SAiGateway) StartAiGatewayDeleteTask(
  342. ctx context.Context, userCred mcclient.TokenCredential, parentTaskId string,
  343. ) error {
  344. params := jsonutils.NewDict()
  345. task, err := taskman.TaskManager.NewTask(ctx, "AiGatewayDeleteTask", self, userCred, params, parentTaskId, "", nil)
  346. if err != nil {
  347. return err
  348. }
  349. self.SetStatus(ctx, userCred, apis.STATUS_DELETING, "")
  350. return task.ScheduleRun(nil)
  351. }
  352. func (manager *SAiGatewayManager) ListItemExportKeys(ctx context.Context,
  353. q *sqlchemy.SQuery,
  354. userCred mcclient.TokenCredential,
  355. keys stringutils2.SSortedStrings,
  356. ) (*sqlchemy.SQuery, error) {
  357. var err error
  358. q, err = manager.SVirtualResourceBaseManager.ListItemExportKeys(ctx, q, userCred, keys)
  359. if err != nil {
  360. return nil, errors.Wrap(err, "SVirtualResourceBaseManager.ListItemExportKeys")
  361. }
  362. return q, nil
  363. }
  364. // 同步状态
  365. func (self *SAiGateway) PerformSyncstatus(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, data jsonutils.JSONObject) (jsonutils.JSONObject, error) {
  366. return nil, StartResourceSyncStatusTask(ctx, userCred, self, "AiGatewaySyncstatusTask", "")
  367. }
  368. // 更改配置
  369. func (self *SAiGateway) PerformChangeConfig(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, input *cloudprovider.AiGatewayChangeConfigOptions) (jsonutils.JSONObject, error) {
  370. return nil, self.StartAiGatewayChangeConfigTask(ctx, userCred, input)
  371. }
  372. func (self *SAiGateway) StartAiGatewayChangeConfigTask(ctx context.Context, userCred mcclient.TokenCredential, opts *cloudprovider.AiGatewayChangeConfigOptions) error {
  373. kwargs := jsonutils.Marshal(opts).(*jsonutils.JSONDict)
  374. task, err := taskman.TaskManager.NewTask(ctx, "AiGatewayChangeConfigTask", self, userCred, kwargs, "", "", nil)
  375. if err != nil {
  376. return err
  377. }
  378. self.SetStatus(ctx, userCred, apis.STATUS_CHANGE_CONFIG, "")
  379. return task.ScheduleRun(nil)
  380. }