network_ip_mac.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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. "strings"
  20. "yunion.io/x/jsonutils"
  21. "yunion.io/x/log"
  22. "yunion.io/x/pkg/errors"
  23. "yunion.io/x/pkg/util/rbacscope"
  24. "yunion.io/x/pkg/utils"
  25. "yunion.io/x/sqlchemy"
  26. api "yunion.io/x/onecloud/pkg/apis/compute"
  27. "yunion.io/x/onecloud/pkg/cloudcommon/db"
  28. "yunion.io/x/onecloud/pkg/httperrors"
  29. "yunion.io/x/onecloud/pkg/mcclient"
  30. "yunion.io/x/onecloud/pkg/util/logclient"
  31. "yunion.io/x/onecloud/pkg/util/stringutils2"
  32. )
  33. type SNetworkIpMacManager struct {
  34. db.SStandaloneAnonResourceBaseManager
  35. }
  36. var NetworkIpMacManager *SNetworkIpMacManager
  37. func GetNetworkIpMacManager() *SNetworkIpMacManager {
  38. if NetworkIpMacManager != nil {
  39. return NetworkIpMacManager
  40. }
  41. NetworkIpMacManager = &SNetworkIpMacManager{
  42. SStandaloneAnonResourceBaseManager: db.NewStandaloneAnonResourceBaseManager(
  43. SNetworkIpMac{},
  44. "network_ip_macs_tbl",
  45. "network_ip_mac",
  46. "network_ip_macs",
  47. ),
  48. }
  49. NetworkIpMacManager.SetVirtualObject(NetworkIpMacManager)
  50. return NetworkIpMacManager
  51. }
  52. func init() {
  53. GetNetworkIpMacManager()
  54. }
  55. type SNetworkIpMac struct {
  56. db.SStandaloneAnonResourceBase
  57. NetworkId string `width:"36" charset:"ascii" nullable:"false" list:"user" index:"true" create:"required"`
  58. // MAC地址
  59. MacAddr string `width:"32" charset:"ascii" nullable:"false" list:"user" index:"true" update:"user" create:"required"`
  60. // IPv4地址
  61. IpAddr string `width:"16" charset:"ascii" nullable:"false" list:"user" index:"true" update:"user" create:"required"`
  62. }
  63. func (manager *SNetworkIpMacManager) ResourceScope() rbacscope.TRbacScope {
  64. return rbacscope.ScopeProject
  65. }
  66. func (self *SNetworkIpMac) GetOwnerId() mcclient.IIdentityProvider {
  67. iNetwork, _ := NetworkManager.FetchById(self.NetworkId)
  68. if iNetwork != nil {
  69. return iNetwork.GetOwnerId()
  70. }
  71. return nil
  72. }
  73. func (manager *SNetworkIpMacManager) NetworkMacAddrInUse(networkId, macAddr string) (bool, error) {
  74. count, err := manager.Query().
  75. Equals("network_id", networkId).
  76. Equals("mac_addr", macAddr).CountWithError()
  77. if err != nil {
  78. return false, err
  79. }
  80. return count > 0, nil
  81. }
  82. func (manager *SNetworkIpMacManager) NetworkIpAddrInUse(networkId, ipAddr string) (bool, error) {
  83. count, err := manager.Query().
  84. Equals("network_id", networkId).
  85. Equals("ip_addr", ipAddr).CountWithError()
  86. if err != nil {
  87. return false, err
  88. }
  89. return count > 0, nil
  90. }
  91. func (manager *SNetworkIpMacManager) ValidateCreateData(
  92. ctx context.Context, userCred mcclient.TokenCredential,
  93. ownerId mcclient.IIdentityProvider, query jsonutils.JSONObject, input api.NetworkIpMacCreateInput,
  94. ) (api.NetworkIpMacCreateInput, error) {
  95. if input.NetworkId == "" {
  96. return input, httperrors.NewMissingParameterError("network_id")
  97. }
  98. if input.IpAddr == "" {
  99. return input, httperrors.NewMissingParameterError("ip_addr")
  100. }
  101. if input.MacAddr == "" {
  102. return input, httperrors.NewMissingParameterError("mac_addr")
  103. }
  104. iNetwork, err := NetworkManager.FetchByIdOrName(ctx, userCred, input.NetworkId)
  105. if err == sql.ErrNoRows {
  106. return input, httperrors.NewNotFoundError("network %s not found", input.NetworkId)
  107. } else if err != nil {
  108. return input, errors.Wrap(err, "fetch network")
  109. }
  110. network := iNetwork.(*SNetwork)
  111. if network.ServerType != api.NETWORK_TYPE_GUEST {
  112. return input, httperrors.NewBadRequestError("network type %s can't set ip mac", network.ServerType)
  113. }
  114. input.NetworkId = network.Id
  115. input.MacAddr = strings.ToLower(input.MacAddr)
  116. return input, manager.validateIpMac(input.IpAddr, input.MacAddr, network)
  117. }
  118. func (self *SNetworkIpMac) ValidateUpdateData(
  119. ctx context.Context, userCred mcclient.TokenCredential,
  120. query jsonutils.JSONObject, input api.NetworkIpMacUpdateInput,
  121. ) (api.NetworkIpMacUpdateInput, error) {
  122. if input.IpAddr == "" && input.MacAddr == "" {
  123. return input, httperrors.NewInputParameterError("missing update field")
  124. }
  125. if input.IpAddr != "" && input.IpAddr != self.IpAddr {
  126. iNetwork, err := NetworkManager.FetchByIdOrName(ctx, userCred, self.NetworkId)
  127. if err != nil {
  128. return input, errors.Wrap(err, "fetch network")
  129. }
  130. network := iNetwork.(*SNetwork)
  131. if !network.Contains(input.IpAddr) {
  132. return input, errors.Errorf("network %s not contains ip addr %s", network.GetName(), input.IpAddr)
  133. }
  134. if ipInUse, err := NetworkIpMacManager.NetworkIpAddrInUse(self.NetworkId, input.IpAddr); err != nil {
  135. return input, errors.Wrap(err, "check ip addr in use")
  136. } else if ipInUse {
  137. return input, httperrors.NewBadRequestError("ip addr %s is in use", input.IpAddr)
  138. }
  139. } else {
  140. input.IpAddr = self.IpAddr
  141. }
  142. input.MacAddr = strings.ToLower(input.MacAddr)
  143. if input.MacAddr != "" && input.MacAddr != self.MacAddr {
  144. if !utils.IsMatchMacAddr(input.MacAddr) {
  145. return input, errors.Errorf("mac address %s is not valid", input.MacAddr)
  146. }
  147. if macInUse, err := NetworkIpMacManager.NetworkMacAddrInUse(self.NetworkId, input.MacAddr); err != nil {
  148. return input, errors.Wrap(err, "check mac addr in use")
  149. } else if macInUse {
  150. return input, httperrors.NewBadRequestError("mac addr %s is in use", input.MacAddr)
  151. }
  152. } else {
  153. input.MacAddr = self.MacAddr
  154. }
  155. if gn, err := GuestnetworkManager.getGuestNicByIP(self.NetworkId, input.IpAddr, api.AddressTypeIPv4); err != nil {
  156. return input, errors.Wrap(err, "failed get guest nic")
  157. } else if gn != nil && gn.MacAddr != input.MacAddr {
  158. return input, errors.Errorf("input ip mac conflict with guest %s nic %d", gn.GuestId, gn.Index)
  159. }
  160. return input, nil
  161. }
  162. func (manager *SNetworkIpMacManager) ListItemFilter(
  163. ctx context.Context,
  164. q *sqlchemy.SQuery,
  165. userCred mcclient.TokenCredential,
  166. input api.NetworkIpMacListInput,
  167. ) (*sqlchemy.SQuery, error) {
  168. var err error
  169. q, err = manager.SStandaloneAnonResourceBaseManager.ListItemFilter(ctx, q, userCred, input.StandaloneAnonResourceListInput)
  170. if err != nil {
  171. return nil, errors.Wrap(err, "SStandaloneAnonResourceBaseManager.ListItemFilter")
  172. }
  173. if input.NetworkId != "" {
  174. iNetwork, err := NetworkManager.FetchByIdOrName(ctx, userCred, input.NetworkId)
  175. if err != nil {
  176. return q, errors.Wrap(err, "fetch network")
  177. }
  178. q = q.Equals("network_id", iNetwork.GetId())
  179. }
  180. if input.MacAddr != nil {
  181. q = q.In("mac_addr", input.MacAddr)
  182. }
  183. if input.IpAddr != nil {
  184. q = q.In("ip_addr", input.IpAddr)
  185. }
  186. return q, nil
  187. }
  188. func (manager *SNetworkIpMacManager) GetMacFromIp(networkId, ipAddr string) string {
  189. q := manager.Query("mac_addr").Equals("network_id", networkId).Equals("ip_addr", ipAddr)
  190. if q.Count() != 1 {
  191. return ""
  192. }
  193. var nim = new(SNetworkIpMac)
  194. if err := q.First(nim); err != nil {
  195. log.Errorf("failed get mac addr form ip %s: %s", ipAddr, err)
  196. return ""
  197. }
  198. return nim.MacAddr
  199. }
  200. func (manager *SNetworkIpMacManager) validateIpMac(ip, mac string, network *SNetwork) error {
  201. if !network.Contains(ip) {
  202. return httperrors.NewBadRequestError("network %s not contains ip addr %s", network.GetName(), ip)
  203. }
  204. if ipInUse, err := manager.NetworkIpAddrInUse(network.Id, ip); err != nil {
  205. return errors.Wrap(err, "check ip addr in use")
  206. } else if ipInUse {
  207. return httperrors.NewBadRequestError("ip addr %s is in use", ip)
  208. }
  209. if !utils.IsMatchMacAddr(mac) {
  210. return httperrors.NewBadRequestError("mac address %s is not valid", mac)
  211. }
  212. if macInUse, err := manager.NetworkMacAddrInUse(network.Id, mac); err != nil {
  213. return errors.Wrap(err, "check mac addr in use")
  214. } else if macInUse {
  215. return httperrors.NewBadRequestError("mac addr %s is in use", mac)
  216. }
  217. if gn, err := GuestnetworkManager.getGuestNicByIP(network.Id, ip, api.AddressTypeIPv4); err != nil {
  218. return errors.Wrap(err, "failed get guest nic")
  219. } else if gn != nil && gn.MacAddr != mac {
  220. return httperrors.NewBadRequestError("input ip mac conflict with guest %s nic %d", gn.GuestId, gn.Index)
  221. }
  222. return nil
  223. }
  224. func (self *SNetworkIpMac) PostCreate(ctx context.Context, userCred mcclient.TokenCredential, ownerId mcclient.IIdentityProvider, query jsonutils.JSONObject, data jsonutils.JSONObject) {
  225. iNetwork, _ := NetworkManager.FetchByIdOrName(ctx, userCred, self.NetworkId)
  226. note := fmt.Sprintf("create ip %s mac %s bind", self.IpAddr, self.MacAddr)
  227. db.OpsLog.LogEvent(iNetwork, db.ACT_IP_MAC_BIND, note, userCred)
  228. logclient.AddActionLogWithContext(ctx, iNetwork, logclient.ACT_IP_MAC_BIND, note, userCred, true)
  229. }
  230. func (self *SNetworkIpMac) PostUpdate(ctx context.Context, userCred mcclient.TokenCredential, query, data jsonutils.JSONObject) {
  231. iNetwork, _ := NetworkManager.FetchByIdOrName(ctx, userCred, self.NetworkId)
  232. note := fmt.Sprintf("update ip %s mac %s bind", self.IpAddr, self.MacAddr)
  233. db.OpsLog.LogEvent(iNetwork, db.ACT_IP_MAC_BIND, note, userCred)
  234. logclient.AddActionLogWithContext(ctx, iNetwork, logclient.ACT_IP_MAC_BIND, note, userCred, true)
  235. }
  236. func (self *SNetworkIpMac) PostDelete(ctx context.Context, userCred mcclient.TokenCredential) {
  237. iNetwork, _ := NetworkManager.FetchByIdOrName(ctx, userCred, self.NetworkId)
  238. note := fmt.Sprintf("delete ip %s mac %s bind", self.IpAddr, self.MacAddr)
  239. db.OpsLog.LogEvent(iNetwork, db.ACT_IP_MAC_BIND, note, userCred)
  240. logclient.AddActionLogWithContext(ctx, iNetwork, logclient.ACT_IP_MAC_BIND, note, userCred, true)
  241. }
  242. func (manager *SNetworkIpMacManager) PerformBatchCreate(
  243. ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, input *api.NetworkIpMacBatchCreateInput,
  244. ) (jsonutils.JSONObject, error) {
  245. iNetwork, err := NetworkManager.FetchByIdOrName(ctx, userCred, input.NetworkId)
  246. if err != nil {
  247. return nil, errors.Wrap(err, "fetch network")
  248. }
  249. network := iNetwork.(*SNetwork)
  250. if network.ServerType != api.NETWORK_TYPE_GUEST {
  251. return nil, errors.Errorf("network type %s can't set ip mac", network.ServerType)
  252. }
  253. input.NetworkId = network.Id
  254. var errs = []error{}
  255. var insertedIpMacs = map[string]string{}
  256. for ip, mac := range input.IpMac {
  257. if err := manager.validateIpMac(ip, mac, network); err != nil {
  258. errs = append(errs, err)
  259. continue
  260. }
  261. nim := &SNetworkIpMac{
  262. NetworkId: input.NetworkId,
  263. IpAddr: ip,
  264. MacAddr: mac,
  265. }
  266. if err := manager.TableSpec().Insert(ctx, nim); err != nil {
  267. errs = append(errs, err)
  268. continue
  269. }
  270. insertedIpMacs[ip] = mac
  271. }
  272. note := fmt.Sprintf("create ip macs bind %v", insertedIpMacs)
  273. db.OpsLog.LogEvent(iNetwork, db.ACT_IP_MAC_BIND, note, userCred)
  274. logclient.AddActionLogWithContext(ctx, iNetwork, logclient.ACT_IP_MAC_BIND, note, userCred, true)
  275. if len(errs) == 0 {
  276. return nil, nil
  277. }
  278. return nil, errors.NewAggregate(errs)
  279. }
  280. func (manager *SNetworkIpMacManager) FetchCustomizeColumns(
  281. ctx context.Context,
  282. userCred mcclient.TokenCredential,
  283. query jsonutils.JSONObject,
  284. objs []interface{},
  285. fields stringutils2.SSortedStrings,
  286. isList bool,
  287. ) []api.NetworkIpMacDetails {
  288. rows := make([]api.NetworkIpMacDetails, len(objs))
  289. baseRows := manager.SStandaloneAnonResourceBaseManager.FetchCustomizeColumns(ctx, userCred, query, objs, fields, isList)
  290. for i := range rows {
  291. rows[i] = api.NetworkIpMacDetails{
  292. StandaloneAnonResourceDetails: baseRows[i],
  293. }
  294. }
  295. return rows
  296. }