domain.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  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 db
  15. import (
  16. "context"
  17. "database/sql"
  18. "yunion.io/x/jsonutils"
  19. "yunion.io/x/pkg/errors"
  20. "yunion.io/x/pkg/util/rbacscope"
  21. "yunion.io/x/pkg/util/reflectutils"
  22. "yunion.io/x/sqlchemy"
  23. "yunion.io/x/onecloud/pkg/apis"
  24. "yunion.io/x/onecloud/pkg/apis/identity"
  25. "yunion.io/x/onecloud/pkg/cloudcommon/consts"
  26. "yunion.io/x/onecloud/pkg/cloudcommon/policy"
  27. "yunion.io/x/onecloud/pkg/httperrors"
  28. "yunion.io/x/onecloud/pkg/mcclient"
  29. "yunion.io/x/onecloud/pkg/util/stringutils2"
  30. "yunion.io/x/onecloud/pkg/util/tagutils"
  31. )
  32. type SDomainizedResourceBaseManager struct {
  33. }
  34. type SDomainizedResourceBase struct {
  35. // 域Id
  36. DomainId string `width:"64" charset:"ascii" default:"default" nullable:"false" index:"true" list:"user" json:"domain_id"`
  37. }
  38. func (manager *SDomainizedResourceBaseManager) NamespaceScope() rbacscope.TRbacScope {
  39. if consts.IsDomainizedNamespace() {
  40. return rbacscope.ScopeDomain
  41. } else {
  42. return rbacscope.ScopeSystem
  43. }
  44. }
  45. func (manager *SDomainizedResourceBaseManager) ResourceScope() rbacscope.TRbacScope {
  46. return rbacscope.ScopeDomain
  47. }
  48. func (manager *SDomainizedResourceBaseManager) FilterByOwner(ctx context.Context, q *sqlchemy.SQuery, man FilterByOwnerProvider, userCred mcclient.TokenCredential, owner mcclient.IIdentityProvider, scope rbacscope.TRbacScope) *sqlchemy.SQuery {
  49. if owner != nil {
  50. switch scope {
  51. case rbacscope.ScopeProject, rbacscope.ScopeDomain:
  52. q = q.Equals("domain_id", owner.GetProjectDomainId())
  53. if userCred != nil {
  54. result := policy.PolicyManager.Allow(scope, userCred, consts.GetServiceType(), man.KeywordPlural(), policy.PolicyActionList)
  55. if !result.ObjectTags.IsEmpty() {
  56. policyTagFilters := tagutils.STagFilters{}
  57. policyTagFilters.AddFilters(result.ObjectTags)
  58. q = ObjectIdQueryWithTagFilters(ctx, q, "id", man.Keyword(), policyTagFilters)
  59. }
  60. }
  61. case rbacscope.ScopeSystem:
  62. if userCred != nil {
  63. result := policy.PolicyManager.Allow(scope, userCred, consts.GetServiceType(), man.KeywordPlural(), policy.PolicyActionList)
  64. if !result.DomainTags.IsEmpty() {
  65. policyFilters := tagutils.STagFilters{}
  66. policyFilters.AddFilters(result.DomainTags)
  67. q = ObjectIdQueryWithTagFilters(ctx, q, "domain_id", "domain", policyFilters)
  68. }
  69. if !result.ObjectTags.IsEmpty() {
  70. policyTagFilters := tagutils.STagFilters{}
  71. policyTagFilters.AddFilters(result.ObjectTags)
  72. q = ObjectIdQueryWithTagFilters(ctx, q, "id", man.Keyword(), policyTagFilters)
  73. }
  74. }
  75. }
  76. }
  77. return q
  78. }
  79. func (manager *SDomainizedResourceBaseManager) FetchOwnerId(ctx context.Context, data jsonutils.JSONObject) (mcclient.IIdentityProvider, error) {
  80. return FetchDomainInfo(ctx, data)
  81. }
  82. func (model *SDomainizedResourceBase) GetOwnerId() mcclient.IIdentityProvider {
  83. owner := SOwnerId{DomainId: model.DomainId}
  84. return &owner
  85. }
  86. // returns candiate domain Id list that the resource can change owner to
  87. // nil or empty means any domain
  88. func (model *SDomainizedResourceBase) GetChangeOwnerCandidateDomainIds() []string {
  89. return nil
  90. }
  91. func (model *SDomainizedResourceBase) GetChangeOwnerRequiredDomainIds() []string {
  92. return nil
  93. }
  94. func ValidateCreateDomainId(domainId string) error {
  95. if !consts.GetNonDefaultDomainProjects() && domainId != identity.DEFAULT_DOMAIN_ID {
  96. return httperrors.NewForbiddenError("project in non-default domain is prohibited")
  97. }
  98. return nil
  99. }
  100. func (manager *SDomainizedResourceBaseManager) QueryDistinctExtraField(q *sqlchemy.SQuery, field string) (*sqlchemy.SQuery, error) {
  101. switch field {
  102. case "domain":
  103. tenantCacheQuery := TenantCacheManager.getTable() // GetDomainQuery("name", "id").SubQuery()
  104. q = q.AppendField(tenantCacheQuery.Field("name", "domain")).Distinct()
  105. q = q.Join(tenantCacheQuery, sqlchemy.Equals(q.Field("domain_id"), tenantCacheQuery.Field("id")))
  106. return q, nil
  107. }
  108. return q, httperrors.ErrNotFound
  109. }
  110. func (manager *SDomainizedResourceBaseManager) ListItemFilter(
  111. ctx context.Context,
  112. q *sqlchemy.SQuery,
  113. userCred mcclient.TokenCredential,
  114. query apis.DomainizedResourceListInput,
  115. ) (*sqlchemy.SQuery, error) {
  116. if len(query.ProjectDomainIds) > 0 {
  117. // make sure ids are not utf8 string
  118. idList := stringutils2.RemoveUtf8Strings(query.ProjectDomainIds)
  119. tenants := DefaultDomainQuery().SubQuery()
  120. // tenants := TenantCacheManager.GetDomainQuery().SubQuery()
  121. subq := tenants.Query(tenants.Field("id")).Filter(sqlchemy.OR(
  122. sqlchemy.In(tenants.Field("id"), idList),
  123. sqlchemy.In(tenants.Field("name"), query.ProjectDomainIds),
  124. )).SubQuery()
  125. q = q.In("domain_id", subq)
  126. }
  127. tagFilters := tagutils.STagFilters{}
  128. if !query.DomainTags.IsEmpty() {
  129. tagFilters.AddFilters(query.DomainTags)
  130. }
  131. if !query.NoDomainTags.IsEmpty() {
  132. tagFilters.AddNoFilters(query.NoDomainTags)
  133. }
  134. q = ObjectIdQueryWithTagFilters(ctx, q, "domain_id", "domain", tagFilters)
  135. return q, nil
  136. }
  137. func (manager *SDomainizedResourceBaseManager) OrderByExtraFields(
  138. ctx context.Context,
  139. q *sqlchemy.SQuery,
  140. userCred mcclient.TokenCredential,
  141. query apis.DomainizedResourceListInput,
  142. ) (*sqlchemy.SQuery, error) {
  143. subq := TenantCacheManager.GetDomainQuery("id", "name").SubQuery()
  144. if NeedOrderQuery([]string{query.OrderByDomain}) {
  145. q = q.LeftJoin(subq, sqlchemy.Equals(q.Field("domain_id"), subq.Field("id")))
  146. q = OrderByFields(q, []string{query.OrderByDomain}, []sqlchemy.IQueryField{subq.Field("name")})
  147. return q, nil
  148. }
  149. return q, nil
  150. }
  151. func (manager *SDomainizedResourceBaseManager) FetchCustomizeColumns(
  152. ctx context.Context,
  153. userCred mcclient.TokenCredential,
  154. query jsonutils.JSONObject,
  155. objs []interface{},
  156. fields stringutils2.SSortedStrings,
  157. isList bool,
  158. ) []apis.DomainizedResourceInfo {
  159. ret := make([]apis.DomainizedResourceInfo, len(objs))
  160. for i := range objs {
  161. ret[i] = apis.DomainizedResourceInfo{}
  162. }
  163. if len(fields) == 0 || fields.Contains("project_domain") {
  164. domainIds := stringutils2.SSortedStrings{}
  165. for i := range objs {
  166. var base *SDomainizedResourceBase
  167. reflectutils.FindAnonymouStructPointer(objs[i], &base)
  168. if base != nil && len(base.DomainId) > 0 {
  169. domainIds = stringutils2.Append(domainIds, base.DomainId)
  170. }
  171. }
  172. domains := DefaultProjectsFetcher(ctx, domainIds, true)
  173. if domains != nil {
  174. for i := range objs {
  175. var base *SDomainizedResourceBase
  176. reflectutils.FindAnonymouStructPointer(objs[i], &base)
  177. if base != nil && len(base.DomainId) > 0 {
  178. if proj, ok := domains[base.DomainId]; ok {
  179. if len(fields) == 0 || fields.Contains("project_domain") {
  180. ret[i].ProjectDomain = proj.Name
  181. }
  182. }
  183. }
  184. }
  185. }
  186. }
  187. return ret
  188. }
  189. func ValidateDomainizedResourceInput(ctx context.Context, input apis.DomainizedResourceInput) (*STenant, apis.DomainizedResourceInput, error) {
  190. domain, err := DefaultDomainFetcher(ctx, input.ProjectDomainId)
  191. if err != nil {
  192. if errors.Cause(err) == sql.ErrNoRows {
  193. return nil, input, httperrors.NewResourceNotFoundError2("domain", input.ProjectDomainId)
  194. } else {
  195. return nil, input, errors.Wrap(err, "TenantCacheManager.FetchDomainByIdOrName")
  196. }
  197. }
  198. input.ProjectDomainId = domain.GetId()
  199. return domain, input, nil
  200. }
  201. func (manager *SDomainizedResourceBaseManager) ListItemExportKeys(ctx context.Context, q *sqlchemy.SQuery, userCred mcclient.TokenCredential, keys stringutils2.SSortedStrings) (*sqlchemy.SQuery, error) {
  202. if keys.Contains("project_domain") {
  203. domainsQ := DefaultDomainQuery().SubQuery()
  204. q = q.LeftJoin(domainsQ, sqlchemy.Equals(q.Field("domain_id"), domainsQ.Field("id")))
  205. q = q.AppendField(domainsQ.Field("name", "project_domain"))
  206. }
  207. return q, nil
  208. }