guest_secgroups.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  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. "fmt"
  18. "gopkg.in/fatih/set.v0"
  19. "yunion.io/x/jsonutils"
  20. "yunion.io/x/pkg/errors"
  21. "yunion.io/x/pkg/utils"
  22. api "yunion.io/x/onecloud/pkg/apis/compute"
  23. "yunion.io/x/onecloud/pkg/cloudcommon/db"
  24. "yunion.io/x/onecloud/pkg/cloudcommon/validators"
  25. "yunion.io/x/onecloud/pkg/compute/options"
  26. "yunion.io/x/onecloud/pkg/httperrors"
  27. "yunion.io/x/onecloud/pkg/mcclient"
  28. "yunion.io/x/onecloud/pkg/util/logclient"
  29. )
  30. // 绑定多个安全组
  31. func (self *SGuest) PerformAddSecgroup(
  32. ctx context.Context,
  33. userCred mcclient.TokenCredential,
  34. query jsonutils.JSONObject,
  35. input api.GuestAddSecgroupInput,
  36. ) (jsonutils.JSONObject, error) {
  37. if !utils.IsInStringArray(self.Status, []string{api.VM_READY, api.VM_RUNNING, api.VM_SUSPEND}) {
  38. return nil, httperrors.NewInputParameterError("Cannot add security groups in status %s", self.Status)
  39. }
  40. drv, err := self.GetDriver()
  41. if err != nil {
  42. return nil, err
  43. }
  44. maxCount := drv.GetMaxSecurityGroupCount()
  45. if maxCount == 0 {
  46. return nil, httperrors.NewUnsupportOperationError("Cannot add security groups for hypervisor %s", self.Hypervisor)
  47. }
  48. if len(input.SecgroupIds) == 0 {
  49. return nil, httperrors.NewMissingParameterError("secgroup_ids")
  50. }
  51. secgroups, err := self.GetSecgroups()
  52. if err != nil {
  53. return nil, httperrors.NewGeneralError(errors.Wrap(err, "GetSecgroups"))
  54. }
  55. if len(secgroups)+len(input.SecgroupIds) > maxCount {
  56. return nil, httperrors.NewUnsupportOperationError("guest %s band to up to %d security groups", self.Name, maxCount)
  57. }
  58. secgroupIds := []string{}
  59. for _, secgroup := range secgroups {
  60. secgroupIds = append(secgroupIds, secgroup.Id)
  61. }
  62. vpc, err := self.GetVpc()
  63. if err != nil {
  64. return nil, errors.Wrapf(err, "GetVpc")
  65. }
  66. secgroupNames := []string{}
  67. for i := range input.SecgroupIds {
  68. secObj, err := validators.ValidateModel(ctx, userCred, SecurityGroupManager, &input.SecgroupIds[i])
  69. if err != nil {
  70. return nil, err
  71. }
  72. secgroup := secObj.(*SSecurityGroup)
  73. if utils.IsInStringArray(secObj.GetId(), secgroupIds) {
  74. return nil, httperrors.NewInputParameterError("security group %s has already been assigned to guest %s", secObj.GetName(), self.Name)
  75. }
  76. err = vpc.CheckSecurityGroupConsistent(secgroup)
  77. if err != nil {
  78. return nil, err
  79. }
  80. secgroupIds = append(secgroupIds, secgroup.GetId())
  81. secgroupNames = append(secgroupNames, secgroup.Name)
  82. }
  83. err = self.SaveSecgroups(ctx, userCred, secgroupIds)
  84. if err != nil {
  85. return nil, httperrors.NewGeneralError(errors.Wrap(err, "saveSecgroups"))
  86. }
  87. notes := map[string][]string{"secgroups": secgroupNames}
  88. logclient.AddActionLogWithContext(ctx, self, logclient.ACT_VM_ASSIGNSECGROUP, notes, userCred, true)
  89. return nil, self.StartSyncTask(ctx, userCred, true, "")
  90. }
  91. func (self *SGuest) saveDefaultSecgroupId(userCred mcclient.TokenCredential, secGrpId string, isAdmin bool) error {
  92. if (!isAdmin && secGrpId != self.SecgrpId) || (isAdmin && secGrpId != self.AdminSecgrpId) {
  93. diff, err := db.Update(self, func() error {
  94. if isAdmin {
  95. self.AdminSecgrpId = secGrpId
  96. } else {
  97. self.SecgrpId = secGrpId
  98. }
  99. return nil
  100. })
  101. if err != nil {
  102. return errors.Wrap(err, "db.Update")
  103. }
  104. db.OpsLog.LogEvent(self, db.ACT_UPDATE, diff, userCred)
  105. }
  106. return nil
  107. }
  108. // 解绑安全组
  109. func (self *SGuest) PerformRevokeSecgroup(
  110. ctx context.Context,
  111. userCred mcclient.TokenCredential,
  112. query jsonutils.JSONObject,
  113. input api.GuestRevokeSecgroupInput,
  114. ) (jsonutils.JSONObject, error) {
  115. if !utils.IsInStringArray(self.Status, []string{api.VM_READY, api.VM_RUNNING, api.VM_SUSPEND}) {
  116. return nil, httperrors.NewInputParameterError("Cannot revoke security groups in status %s", self.Status)
  117. }
  118. if len(input.SecgroupIds) == 0 {
  119. return nil, nil
  120. }
  121. secgroups, err := self.GetSecgroups()
  122. if err != nil {
  123. return nil, httperrors.NewGeneralError(errors.Wrap(err, "GetSecgroups"))
  124. }
  125. secgroupMaps := map[string]string{}
  126. for _, secgroup := range secgroups {
  127. secgroupMaps[secgroup.Id] = secgroup.Name
  128. }
  129. secgroupNames := []string{}
  130. for i := range input.SecgroupIds {
  131. secObj, err := validators.ValidateModel(ctx, userCred, SecurityGroupManager, &input.SecgroupIds[i])
  132. if err != nil {
  133. return nil, err
  134. }
  135. secgrp := secObj.(*SSecurityGroup)
  136. _, ok := secgroupMaps[secgrp.GetId()]
  137. if !ok {
  138. return nil, httperrors.NewInputParameterError("security group %s not assigned to guest %s", secgrp.GetName(), self.Name)
  139. }
  140. delete(secgroupMaps, secgrp.GetId())
  141. secgroupNames = append(secgroupNames, secgrp.GetName())
  142. }
  143. secgrpIds := []string{}
  144. for secgroupId := range secgroupMaps {
  145. secgrpIds = append(secgrpIds, secgroupId)
  146. }
  147. err = self.SaveSecgroups(ctx, userCred, secgrpIds)
  148. if err != nil {
  149. return nil, httperrors.NewGeneralError(errors.Wrap(err, "saveSecgroups"))
  150. }
  151. notes := map[string][]string{"secgroups": secgroupNames}
  152. logclient.AddActionLogWithContext(ctx, self, logclient.ACT_VM_REVOKESECGROUP, notes, userCred, true)
  153. return nil, self.StartSyncTask(ctx, userCred, true, "")
  154. }
  155. // 解绑管理员安全组
  156. func (guest *SGuest) PerformRevokeAdminSecgroup(
  157. ctx context.Context,
  158. userCred mcclient.TokenCredential,
  159. query jsonutils.JSONObject,
  160. input api.GuestRevokeSecgroupInput,
  161. ) (jsonutils.JSONObject, error) {
  162. if !db.IsAdminAllowPerform(ctx, userCred, guest, "revoke-admin-secgroup") {
  163. return nil, httperrors.NewForbiddenError("not allow to revoke admin secgroup")
  164. }
  165. if !utils.IsInStringArray(guest.Status, []string{api.VM_READY, api.VM_RUNNING, api.VM_SUSPEND}) {
  166. return nil, httperrors.NewInputParameterError("Cannot assign security rules in status %s", guest.Status)
  167. }
  168. var notes string
  169. optAdminSecGrpId := options.Options.GetDefaultAdminSecurityGroupId(guest.Hypervisor)
  170. adminSecgrpId := ""
  171. if len(optAdminSecGrpId) > 0 {
  172. adminSecgrp, _ := SecurityGroupManager.FetchSecgroupById(optAdminSecGrpId)
  173. if adminSecgrp != nil {
  174. adminSecgrpId = adminSecgrp.Id
  175. notes = fmt.Sprintf("reset admin secgroup to %s(%s)", adminSecgrp.Name, adminSecgrp.Id)
  176. }
  177. }
  178. if adminSecgrpId == "" {
  179. notes = "clean admin secgroup"
  180. }
  181. err := guest.saveDefaultSecgroupId(userCred, adminSecgrpId, true)
  182. if err != nil {
  183. return nil, errors.Wrap(err, "saveDefaultSecgroupId")
  184. }
  185. logclient.AddActionLogWithContext(ctx, guest, logclient.ACT_VM_REVOKESECGROUP, notes, userCred, true)
  186. return nil, guest.StartSyncTask(ctx, userCred, true, "")
  187. }
  188. // +onecloud:swagger-gen-ignore
  189. func (self *SGuest) PerformAssignSecgroup(
  190. ctx context.Context,
  191. userCred mcclient.TokenCredential,
  192. query jsonutils.JSONObject,
  193. input api.GuestAssignSecgroupInput,
  194. ) (jsonutils.JSONObject, error) {
  195. return self.performAssignSecgroup(ctx, userCred, query, input, false)
  196. }
  197. // +onecloud:swagger-gen-ignore
  198. func (self *SGuest) PerformAssignAdminSecgroup(
  199. ctx context.Context,
  200. userCred mcclient.TokenCredential,
  201. query jsonutils.JSONObject,
  202. input api.GuestAssignSecgroupInput,
  203. ) (jsonutils.JSONObject, error) {
  204. if !db.IsAdminAllowPerform(ctx, userCred, self, "assign-admin-secgroup") {
  205. return nil, httperrors.NewForbiddenError("not allow to assign admin secgroup")
  206. }
  207. return self.performAssignSecgroup(ctx, userCred, query, input, true)
  208. }
  209. func (self *SGuest) performAssignSecgroup(
  210. ctx context.Context,
  211. userCred mcclient.TokenCredential,
  212. query jsonutils.JSONObject,
  213. input api.GuestAssignSecgroupInput,
  214. isAdmin bool,
  215. ) (jsonutils.JSONObject, error) {
  216. if !utils.IsInStringArray(self.Status, []string{api.VM_READY, api.VM_RUNNING, api.VM_SUSPEND}) {
  217. return nil, httperrors.NewInputParameterError("Cannot assign security rules in status %s", self.Status)
  218. }
  219. if len(input.SecgroupId) == 0 {
  220. return nil, httperrors.NewMissingParameterError("secgroup_id")
  221. }
  222. vpc, err := self.GetVpc()
  223. if err != nil {
  224. return nil, errors.Wrapf(err, "GetVpc")
  225. }
  226. secObj, err := validators.ValidateModel(ctx, userCred, SecurityGroupManager, &input.SecgroupId)
  227. if err != nil {
  228. return nil, err
  229. }
  230. secgroup := secObj.(*SSecurityGroup)
  231. err = vpc.CheckSecurityGroupConsistent(secgroup)
  232. if err != nil {
  233. return nil, err
  234. }
  235. err = self.saveDefaultSecgroupId(userCred, input.SecgroupId, isAdmin)
  236. if err != nil {
  237. return nil, err
  238. }
  239. notes := map[string]string{"name": secObj.GetName(), "id": secObj.GetId(), "is_admin": fmt.Sprintf("%v", isAdmin)}
  240. logclient.AddActionLogWithContext(ctx, self, logclient.ACT_VM_ASSIGNSECGROUP, notes, userCred, true)
  241. return nil, self.StartSyncTask(ctx, userCred, true, "")
  242. }
  243. // 全量覆盖安全组
  244. func (self *SGuest) PerformSetSecgroup(
  245. ctx context.Context,
  246. userCred mcclient.TokenCredential,
  247. query jsonutils.JSONObject,
  248. input api.GuestSetSecgroupInput,
  249. ) (jsonutils.JSONObject, error) {
  250. if !utils.IsInStringArray(self.Status, []string{api.VM_READY, api.VM_RUNNING, api.VM_SUSPEND}) {
  251. return nil, httperrors.NewInputParameterError("Cannot set security rules in status %s", self.Status)
  252. }
  253. if len(input.SecgroupIds) == 0 {
  254. return nil, httperrors.NewMissingParameterError("secgroup_ids")
  255. }
  256. drv, err := self.GetDriver()
  257. if err != nil {
  258. return nil, err
  259. }
  260. maxCount := drv.GetMaxSecurityGroupCount()
  261. if maxCount == 0 {
  262. return nil, httperrors.NewUnsupportOperationError("Cannot set security group for this guest %s", self.Name)
  263. }
  264. if len(input.SecgroupIds) > maxCount {
  265. return nil, httperrors.NewUnsupportOperationError("guest %s band to up to %d security groups", self.Name, maxCount)
  266. }
  267. vpc, err := self.GetVpc()
  268. if err != nil {
  269. return nil, errors.Wrapf(err, "GetVpc")
  270. }
  271. secgroupIds := []string{}
  272. secgroupNames := []string{}
  273. for i := range input.SecgroupIds {
  274. secObj, err := validators.ValidateModel(ctx, userCred, SecurityGroupManager, &input.SecgroupIds[i])
  275. if err != nil {
  276. return nil, err
  277. }
  278. secgrp := secObj.(*SSecurityGroup)
  279. err = vpc.CheckSecurityGroupConsistent(secgrp)
  280. if err != nil {
  281. return nil, err
  282. }
  283. if !utils.IsInStringArray(secgrp.GetId(), secgroupIds) {
  284. secgroupIds = append(secgroupIds, secgrp.GetId())
  285. secgroupNames = append(secgroupNames, secgrp.GetName())
  286. }
  287. }
  288. err = self.SaveSecgroups(ctx, userCred, secgroupIds)
  289. if err != nil {
  290. return nil, httperrors.NewGeneralError(errors.Wrapf(err, "saveSecgroups"))
  291. }
  292. notes := map[string][]string{"secgroups": secgroupNames}
  293. logclient.AddActionLogWithContext(ctx, self, logclient.ACT_VM_SETSECGROUP, notes, userCred, true)
  294. return nil, self.StartSyncTask(ctx, userCred, true, "")
  295. }
  296. func (self *SGuest) GetGuestSecgroups() ([]SGuestsecgroup, error) {
  297. gss := []SGuestsecgroup{}
  298. q := GuestsecgroupManager.Query().Equals("guest_id", self.Id)
  299. err := db.FetchModelObjects(GuestsecgroupManager, q, &gss)
  300. if err != nil {
  301. return nil, errors.Wrapf(err, "db.FetchModelObjects")
  302. }
  303. return gss, nil
  304. }
  305. func (self *SGuest) SaveSecgroups(ctx context.Context, userCred mcclient.TokenCredential, secgroupIds []string) error {
  306. if len(secgroupIds) == 0 {
  307. return self.RevokeAllSecgroups(ctx, userCred)
  308. }
  309. oldIds := set.New(set.ThreadSafe)
  310. newIds := set.New(set.ThreadSafe)
  311. gss, err := self.GetGuestSecgroups()
  312. if err != nil {
  313. return errors.Wrapf(err, "GetGuestSecgroups")
  314. }
  315. secgroupMaps := map[string]SGuestsecgroup{}
  316. for i := range gss {
  317. oldIds.Add(gss[i].SecgroupId)
  318. secgroupMaps[gss[i].SecgroupId] = gss[i]
  319. }
  320. for i := 1; i < len(secgroupIds); i++ {
  321. newIds.Add(secgroupIds[i])
  322. }
  323. for _, removed := range set.Difference(oldIds, newIds).List() {
  324. id := removed.(string)
  325. gs, ok := secgroupMaps[id]
  326. if ok {
  327. err = gs.Delete(ctx, userCred)
  328. if err != nil {
  329. return errors.Wrapf(err, "Delete guest secgroup for guest %s secgroup %s", self.Name, id)
  330. }
  331. }
  332. }
  333. for _, added := range set.Difference(newIds, oldIds).List() {
  334. id := added.(string)
  335. err = self.newGuestSecgroup(ctx, id)
  336. if err != nil {
  337. return errors.Wrapf(err, "New guest secgroup for guest %s with secgroup %s", self.Name, id)
  338. }
  339. }
  340. return self.saveDefaultSecgroupId(userCred, secgroupIds[0], false)
  341. }
  342. func (self *SGuest) newGuestSecgroup(ctx context.Context, secgroupId string) error {
  343. gs := &SGuestsecgroup{}
  344. gs.SetModelManager(GuestsecgroupManager, gs)
  345. gs.GuestId = self.Id
  346. gs.SecgroupId = secgroupId
  347. return GuestsecgroupManager.TableSpec().Insert(ctx, gs)
  348. }
  349. func (guest *SGuest) RevokeAllSecgroups(ctx context.Context, userCred mcclient.TokenCredential) error {
  350. gss, err := guest.GetGuestSecgroups()
  351. if err != nil {
  352. return errors.Wrapf(err, "GetGuestSecgroups")
  353. }
  354. for i := range gss {
  355. err = gss[i].Delete(ctx, userCred)
  356. if err != nil {
  357. return errors.Wrap(err, "Delete")
  358. }
  359. }
  360. return guest.saveDefaultSecgroupId(userCred, options.Options.GetDefaultSecurityGroupId(guest.Hypervisor), false)
  361. }
  362. func isValidSecgroups(ctx context.Context, userCred mcclient.TokenCredential, secgroups []string) ([]string, error) {
  363. secGrpIds := []string{}
  364. for _, secgroup := range secgroups {
  365. secGrpObj, err := SecurityGroupManager.FetchByIdOrName(ctx, userCred, secgroup)
  366. if err != nil {
  367. return nil, httperrors.NewResourceNotFoundError("Secgroup %s not found", secgroup)
  368. }
  369. if !utils.IsInStringArray(secGrpObj.GetId(), secGrpIds) {
  370. secGrpIds = append(secGrpIds, secGrpObj.GetId())
  371. }
  372. }
  373. return secGrpIds, nil
  374. }