natdtable.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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/pkg/util/regutils"
  22. "yunion.io/x/sqlchemy"
  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/validators"
  28. "yunion.io/x/onecloud/pkg/httperrors"
  29. "yunion.io/x/onecloud/pkg/mcclient"
  30. "yunion.io/x/onecloud/pkg/util/stringutils2"
  31. )
  32. // +onecloud:swagger-gen-model-singular=natdentry
  33. // +onecloud:swagger-gen-model-plural=natdentries
  34. type SNatDEntryManager struct {
  35. SNatEntryManager
  36. }
  37. var NatDEntryManager *SNatDEntryManager
  38. func init() {
  39. NatDEntryManager = &SNatDEntryManager{
  40. SNatEntryManager: NewNatEntryManager(
  41. SNatDEntry{},
  42. "natdtables_tbl",
  43. "natdentry",
  44. "natdentries",
  45. ),
  46. }
  47. NatDEntryManager.SetVirtualObject(NatDEntryManager)
  48. }
  49. type SNatDEntry struct {
  50. SNatEntry
  51. ExternalIP string `width:"17" charset:"ascii" list:"user" create:"required"`
  52. ExternalPort int `list:"user" create:"required"`
  53. InternalIP string `width:"17" charset:"ascii" list:"user" create:"required"`
  54. InternalPort int `list:"user" create:"required"`
  55. IpProtocol string `width:"8" charset:"ascii" list:"user" create:"required"`
  56. }
  57. // NAT网关的目的地址转换规则列表
  58. func (man *SNatDEntryManager) ListItemFilter(
  59. ctx context.Context,
  60. q *sqlchemy.SQuery,
  61. userCred mcclient.TokenCredential,
  62. query api.NatDEntryListInput,
  63. ) (*sqlchemy.SQuery, error) {
  64. q, err := man.SNatEntryManager.ListItemFilter(ctx, q, userCred, query.NatEntryListInput)
  65. if err != nil {
  66. return nil, errors.Wrap(err, "SNatEntryManager.ListItemFilter")
  67. }
  68. if len(query.ExternalIP) > 0 {
  69. q = q.In("external_ip", query.ExternalIP)
  70. }
  71. if len(query.ExternalPort) > 0 {
  72. q = q.In("external_port", query.ExternalPort)
  73. }
  74. if len(query.InternalIP) > 0 {
  75. q = q.In("internal_ip", query.InternalIP)
  76. }
  77. if len(query.InternalPort) > 0 {
  78. q = q.In("internal_port", query.InternalPort)
  79. }
  80. if len(query.IpProtocol) > 0 {
  81. q = q.In("ip_protocol", query.IpProtocol)
  82. }
  83. return q, nil
  84. }
  85. func (manager *SNatDEntryManager) OrderByExtraFields(
  86. ctx context.Context,
  87. q *sqlchemy.SQuery,
  88. userCred mcclient.TokenCredential,
  89. query api.NatDEntryListInput,
  90. ) (*sqlchemy.SQuery, error) {
  91. q, err := manager.SNatEntryManager.OrderByExtraFields(ctx, q, userCred, query.NatEntryListInput)
  92. if err != nil {
  93. return nil, errors.Wrap(err, "SNatEntryManager.OrderByExtraFields")
  94. }
  95. return q, nil
  96. }
  97. func (manager *SNatDEntryManager) QueryDistinctExtraField(q *sqlchemy.SQuery, field string) (*sqlchemy.SQuery, error) {
  98. var err error
  99. q, err = manager.SNatEntryManager.QueryDistinctExtraField(q, field)
  100. if err == nil {
  101. return q, nil
  102. }
  103. return q, httperrors.ErrNotFound
  104. }
  105. func (self *SNatDEntry) GetUniqValues() jsonutils.JSONObject {
  106. return jsonutils.Marshal(map[string]string{"natgateway_id": self.NatgatewayId})
  107. }
  108. func (manager *SNatDEntryManager) FetchUniqValues(ctx context.Context, data jsonutils.JSONObject) jsonutils.JSONObject {
  109. natId, _ := data.GetString("natgateway_id")
  110. return jsonutils.Marshal(map[string]string{"natgateway_id": natId})
  111. }
  112. func (manager *SNatDEntryManager) FilterByUniqValues(q *sqlchemy.SQuery, values jsonutils.JSONObject) *sqlchemy.SQuery {
  113. natId, _ := values.GetString("natgateway_id")
  114. if len(natId) > 0 {
  115. q = q.Equals("natgateway_id", natId)
  116. }
  117. return q
  118. }
  119. func (man *SNatDEntryManager) ValidateCreateData(ctx context.Context, userCred mcclient.TokenCredential, ownerId mcclient.IIdentityProvider, query jsonutils.JSONObject, input *api.SNatDCreateInput) (*api.SNatDCreateInput, error) {
  120. if len(input.NatgatewayId) == 0 {
  121. return nil, httperrors.NewMissingParameterError("natgateway_id")
  122. }
  123. if len(input.Eip) == 0 {
  124. return nil, httperrors.NewMissingParameterError("eip")
  125. }
  126. if input.ExternalPort < 1 || input.ExternalPort > 65535 {
  127. return nil, httperrors.NewInputParameterError("Port value error")
  128. }
  129. if input.InternalPort < 1 || input.InternalPort > 65535 {
  130. return nil, httperrors.NewInputParameterError("Port value error")
  131. }
  132. if !regutils.MatchIPAddr(input.InternalIp) {
  133. return nil, httperrors.NewInputParameterError("invalid internal ip address: %s", input.InternalIp)
  134. }
  135. _eip, err := validators.ValidateModel(ctx, userCred, ElasticipManager, &input.Eip)
  136. if err != nil {
  137. return nil, err
  138. }
  139. eip := _eip.(*SElasticip)
  140. input.ExternalIp = eip.IpAddr
  141. q := man.Query().Equals("external_ip", input.ExternalIp).Equals("external_port", input.ExternalPort)
  142. count, err := q.CountWithError()
  143. if err != nil {
  144. return nil, errors.Wrap(err, "q.CountWithError")
  145. }
  146. if count > 0 {
  147. return nil, httperrors.NewInputParameterError("there are dnat rules with same external ip and external port")
  148. }
  149. // check that eip is suitable
  150. if len(eip.AssociateId) > 0 && eip.AssociateId != input.NatgatewayId {
  151. return nil, httperrors.NewInputParameterError("eip has been binding to another instance")
  152. }
  153. return input, nil
  154. }
  155. func (manager *SNatDEntryManager) SyncNatDTable(
  156. ctx context.Context,
  157. userCred mcclient.TokenCredential,
  158. provider *SCloudprovider,
  159. nat *SNatGateway,
  160. extDTable []cloudprovider.ICloudNatDEntry,
  161. xor bool,
  162. ) compare.SyncResult {
  163. syncOwnerId := provider.GetOwnerId()
  164. lockman.LockRawObject(ctx, manager.Keyword(), nat.Id)
  165. defer lockman.ReleaseRawObject(ctx, manager.Keyword(), nat.Id)
  166. result := compare.SyncResult{}
  167. dbNatDTables, err := nat.GetDTable()
  168. if err != nil {
  169. result.Error(err)
  170. return result
  171. }
  172. removed := make([]SNatDEntry, 0)
  173. commondb := make([]SNatDEntry, 0)
  174. commonext := make([]cloudprovider.ICloudNatDEntry, 0)
  175. added := make([]cloudprovider.ICloudNatDEntry, 0)
  176. if err := compare.CompareSets(dbNatDTables, extDTable, &removed, &commondb, &commonext, &added); err != nil {
  177. result.Error(err)
  178. return result
  179. }
  180. for i := 0; i < len(removed); i += 1 {
  181. err := removed[i].syncRemoveCloudNatDTable(ctx, userCred)
  182. if err != nil {
  183. result.DeleteError(err)
  184. } else {
  185. result.Delete()
  186. }
  187. }
  188. if !xor {
  189. for i := 0; i < len(commondb); i += 1 {
  190. err := commondb[i].SyncWithCloudNatDTable(ctx, userCred, commonext[i], provider)
  191. if err != nil {
  192. result.UpdateError(err)
  193. continue
  194. }
  195. result.Update()
  196. }
  197. }
  198. for i := 0; i < len(added); i += 1 {
  199. _, err := manager.newFromCloudNatDTable(ctx, userCred, syncOwnerId, nat, added[i])
  200. if err != nil {
  201. result.AddError(err)
  202. continue
  203. }
  204. result.Add()
  205. }
  206. return result
  207. }
  208. func (self *SNatDEntry) GetCloudproviderId() string {
  209. nat, _ := self.GetNatgateway()
  210. if nat != nil {
  211. return nat.GetCloudproviderId()
  212. }
  213. return ""
  214. }
  215. func (self *SNatDEntry) syncRemoveCloudNatDTable(ctx context.Context, userCred mcclient.TokenCredential) error {
  216. lockman.LockObject(ctx, self)
  217. defer lockman.ReleaseObject(ctx, self)
  218. err := self.ValidateDeleteCondition(ctx, nil)
  219. if err != nil { // cannot delete
  220. return self.SetStatus(ctx, userCred, api.VPC_STATUS_UNKNOWN, "sync to delete")
  221. }
  222. return self.RealDelete(ctx, userCred)
  223. }
  224. func (self *SNatDEntry) SyncWithCloudNatDTable(ctx context.Context, userCred mcclient.TokenCredential, extEntry cloudprovider.ICloudNatDEntry, provider *SCloudprovider) error {
  225. diff, err := db.UpdateWithLock(ctx, self, func() error {
  226. self.Status = extEntry.GetStatus()
  227. self.ExternalIP = extEntry.GetExternalIp()
  228. self.ExternalPort = extEntry.GetExternalPort()
  229. self.InternalIP = extEntry.GetInternalIp()
  230. self.InternalPort = extEntry.GetInternalPort()
  231. self.IpProtocol = extEntry.GetIpProtocol()
  232. return nil
  233. })
  234. if err != nil {
  235. return err
  236. }
  237. SyncCloudDomain(userCred, self, provider.GetOwnerId())
  238. if account, _ := provider.GetCloudaccount(); account != nil {
  239. syncMetadata(ctx, userCred, self, extEntry, account.ReadOnly)
  240. }
  241. db.OpsLog.LogSyncUpdate(self, diff, userCred)
  242. return nil
  243. }
  244. func (manager *SNatDEntryManager) newFromCloudNatDTable(ctx context.Context, userCred mcclient.TokenCredential, ownerId mcclient.IIdentityProvider, nat *SNatGateway, extEntry cloudprovider.ICloudNatDEntry) (*SNatDEntry, error) {
  245. table := SNatDEntry{}
  246. table.SetModelManager(manager, &table)
  247. table.Status = extEntry.GetStatus()
  248. table.ExternalId = extEntry.GetGlobalId()
  249. table.IsEmulated = extEntry.IsEmulated()
  250. table.NatgatewayId = nat.Id
  251. table.ExternalIP = extEntry.GetExternalIp()
  252. table.ExternalPort = extEntry.GetExternalPort()
  253. table.InternalIP = extEntry.GetInternalIp()
  254. table.InternalPort = extEntry.GetInternalPort()
  255. table.IpProtocol = extEntry.GetIpProtocol()
  256. var err = func() error {
  257. lockman.LockRawObject(ctx, manager.Keyword(), "name")
  258. defer lockman.ReleaseRawObject(ctx, manager.Keyword(), "name")
  259. var err error
  260. table.Name, err = db.GenerateName(ctx, manager, ownerId, extEntry.GetName())
  261. if err != nil {
  262. return err
  263. }
  264. return manager.TableSpec().Insert(ctx, &table)
  265. }()
  266. if err != nil {
  267. return nil, errors.Wrapf(err, "Insert")
  268. }
  269. SyncCloudDomain(userCred, &table, ownerId)
  270. syncMetadata(ctx, userCred, &table, extEntry, false)
  271. db.OpsLog.LogEvent(&table, db.ACT_CREATE, table.GetShortDesc(ctx), userCred)
  272. return &table, nil
  273. }
  274. func (manager *SNatDEntryManager) FetchCustomizeColumns(
  275. ctx context.Context,
  276. userCred mcclient.TokenCredential,
  277. query jsonutils.JSONObject,
  278. objs []interface{},
  279. fields stringutils2.SSortedStrings,
  280. isList bool,
  281. ) []api.NatDEntryDetails {
  282. rows := make([]api.NatDEntryDetails, len(objs))
  283. entryRows := manager.SNatEntryManager.FetchCustomizeColumns(ctx, userCred, query, objs, fields, isList)
  284. for i := range rows {
  285. rows[i] = api.NatDEntryDetails{
  286. NatEntryDetails: entryRows[i],
  287. }
  288. }
  289. return rows
  290. }
  291. func (self *SNatDEntry) PostCreate(ctx context.Context, userCred mcclient.TokenCredential, ownerId mcclient.IIdentityProvider, query jsonutils.JSONObject, data jsonutils.JSONObject) {
  292. var err = func() error {
  293. task, err := taskman.TaskManager.NewTask(ctx, "SNatDEntryCreateTask", self, userCred, nil, "", "", nil)
  294. if err != nil {
  295. return errors.Wrapf(err, "NewTask")
  296. }
  297. return task.ScheduleRun(nil)
  298. }()
  299. if err != nil {
  300. self.SetStatus(ctx, userCred, api.NAT_STATUS_CREATE_FAILED, err.Error())
  301. return
  302. }
  303. self.SetStatus(ctx, userCred, api.NAT_STATUS_ALLOCATE, "")
  304. }
  305. func (self *SNatDEntry) CustomizeDelete(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, data jsonutils.JSONObject) error {
  306. return self.StartDeleteDNatTask(ctx, userCred)
  307. }
  308. func (self *SNatDEntry) StartDeleteDNatTask(ctx context.Context, userCred mcclient.TokenCredential) error {
  309. var err = func() error {
  310. task, err := taskman.TaskManager.NewTask(ctx, "SNatDEntryDeleteTask", self, userCred, nil, "", "", nil)
  311. if err != nil {
  312. return errors.Wrapf(err, "NewTask")
  313. }
  314. return task.ScheduleRun(nil)
  315. }()
  316. if err != nil {
  317. self.SetStatus(ctx, userCred, api.NAT_STATUS_DELETE_FAILED, err.Error())
  318. return err
  319. }
  320. self.SetStatus(ctx, userCred, api.NAT_STATUS_DELETING, "")
  321. return nil
  322. }
  323. func (self *SNatDEntry) GetEip() (*SElasticip, error) {
  324. q := ElasticipManager.Query().Equals("ip_addr", self.ExternalIP)
  325. eips := []SElasticip{}
  326. err := db.FetchModelObjects(ElasticipManager, q, &eips)
  327. if err != nil {
  328. return nil, errors.Wrapf(err, "db.FetchModelObjects")
  329. }
  330. if len(eips) == 1 {
  331. return &eips[0], nil
  332. }
  333. if len(eips) == 0 {
  334. return nil, errors.Wrapf(cloudprovider.ErrNotFound, "%v", self.ExternalIP)
  335. }
  336. return nil, errors.Wrapf(cloudprovider.ErrDuplicateId, "%v", self.ExternalIP)
  337. }