netinterfaces.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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. "yunion.io/x/cloudmux/pkg/apis/compute"
  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/util/regutils"
  25. api "yunion.io/x/onecloud/pkg/apis/compute"
  26. "yunion.io/x/onecloud/pkg/cloudcommon/db"
  27. "yunion.io/x/onecloud/pkg/cloudcommon/types"
  28. "yunion.io/x/onecloud/pkg/mcclient"
  29. )
  30. // +onecloud:swagger-gen-ignore
  31. type SNetInterface struct {
  32. db.SResourceBase
  33. // Mac地址
  34. Mac string `width:"36" charset:"ascii" primary:"true"` // Column(VARCHAR(36, charset='ascii'), primary_key=True)
  35. // VLAN ID
  36. VlanId int `nullable:"false" default:"1" primary:"true"`
  37. BaremetalId string `width:"36" charset:"ascii" nullable:"true"` // Column(VARCHAR(36, charset='ascii'), nullable=True)
  38. WireId string `width:"36" charset:"ascii" nullable:"true"` // Column(VARCHAR(36, charset='ascii'), nullable=True)
  39. Rate int `nullable:"true"` // Column(Integer, nullable=True) # Mbps
  40. NicType compute.TNicType `width:"36" charset:"ascii" nullable:"true"` // Column(VARCHAR(36, charset='ascii'), nullable=True)
  41. // SR-IOV nic index may exceed 256
  42. Index int `nullable:"true"` // Column(TINYINT, nullable=True)
  43. LinkUp bool `nullable:"true"` // Column(Boolean, nullable=True)
  44. Mtu int16 `nullable:"true"` // Column(SMALLINT, nullable=True)
  45. // Bridge名称
  46. Bridge string `width:"64" charset:"ascii" nullable:"true"`
  47. // 接口名称
  48. Interface string `width:"64" charset:"ascii" nullable:"true"`
  49. }
  50. // +onecloud:swagger-gen-ignore
  51. type SNetInterfaceManager struct {
  52. db.SResourceBaseManager
  53. }
  54. var NetInterfaceManager *SNetInterfaceManager
  55. func init() {
  56. NetInterfaceManager = &SNetInterfaceManager{
  57. SResourceBaseManager: db.NewResourceBaseManager(
  58. SNetInterface{},
  59. "netinterfaces_tbl",
  60. "netinterface",
  61. "netinterfaces",
  62. ),
  63. }
  64. NetInterfaceManager.SetVirtualObject(NetInterfaceManager)
  65. }
  66. func (netif SNetInterface) GetId() string {
  67. return fmt.Sprintf("%s-%d", netif.Mac, netif.VlanId)
  68. }
  69. func (manager *SNetInterfaceManager) FetchByMac(mac string) ([]SNetInterface, error) {
  70. q := manager.Query().Equals("mac", mac)
  71. ret := make([]SNetInterface, 0, 1)
  72. err := db.FetchModelObjects(manager, q, &ret)
  73. if err != nil {
  74. return nil, errors.Wrap(err, "FetchModelObjects")
  75. }
  76. return ret, nil
  77. }
  78. func (manager *SNetInterfaceManager) FetchByMacVlan(mac string, vlanId int) (*SNetInterface, error) {
  79. q := manager.Query().Equals("mac", mac).Equals("vlan_id", vlanId)
  80. ret := &SNetInterface{}
  81. err := q.First(ret)
  82. if err != nil {
  83. return nil, errors.Wrapf(err, "First")
  84. }
  85. ret.SetModelManager(manager, ret)
  86. return ret, nil
  87. }
  88. func (netif *SNetInterface) UnsetWire() error {
  89. _, err := db.Update(netif, func() error {
  90. netif.WireId = ""
  91. return nil
  92. })
  93. return err
  94. }
  95. func (netif *SNetInterface) GetWire() *SWire {
  96. if len(netif.WireId) > 0 {
  97. wireModel, _ := WireManager.FetchById(netif.WireId)
  98. if wireModel != nil {
  99. return wireModel.(*SWire)
  100. }
  101. }
  102. return nil
  103. }
  104. func (netif *SNetInterface) GetHost() *SHost {
  105. if len(netif.BaremetalId) > 0 {
  106. hostModel, _ := HostManager.FetchById(netif.BaremetalId)
  107. if hostModel != nil {
  108. return hostModel.(*SHost)
  109. }
  110. }
  111. return nil
  112. }
  113. func (netif *SNetInterface) GetHostNetwork() *SHostnetwork {
  114. bn := SHostnetwork{}
  115. bn.SetModelManager(HostnetworkManager, &bn)
  116. q := HostnetworkManager.Query()
  117. q = q.Equals("baremetal_id", netif.BaremetalId).Equals("mac_addr", netif.Mac).Equals("vlan_id", netif.VlanId)
  118. err := q.First(&bn)
  119. if err != nil {
  120. if errors.Cause(err) != sql.ErrNoRows {
  121. log.Errorf("fetch baremetal error: %s", err)
  122. }
  123. return nil
  124. }
  125. return &bn
  126. }
  127. /*func (netIf *SNetInterface) guestNetworkToJson(bn *SGuestnetwork) *jsonutils.JSONDict {
  128. jsonDesc := jsonutils.Marshal(netIf)
  129. desc := jsonDesc.(*jsonutils.JSONDict)
  130. if bn == nil {
  131. return desc
  132. } else {
  133. return netIf.networkToJson(bn.IpAddr, bn.GetNetwork(), desc)
  134. }
  135. }
  136. func (netIf *SNetInterface) hostNetworkToJson(bn *SHostnetwork) *jsonutils.JSONDict {
  137. jsonDesc := jsonutils.Marshal(netIf)
  138. desc := jsonDesc.(*jsonutils.JSONDict)
  139. if bn == nil {
  140. return desc
  141. } else {
  142. return netIf.networkToJson(bn.IpAddr, bn.GetNetwork(), desc)
  143. }
  144. }*/
  145. func (netIf *SNetInterface) networkToNic(ipAddr, ip6Addr string, network *SNetwork, nic *types.SNic) *types.SNic {
  146. if len(ipAddr) > 0 {
  147. nic.IpAddr = ipAddr
  148. }
  149. if len(ip6Addr) > 0 {
  150. nic.Ip6Addr = ip6Addr
  151. }
  152. if network != nil {
  153. if len(network.GuestGateway) > 0 && regutils.MatchIP4Addr(network.GuestGateway) {
  154. nic.Gateway = network.GuestGateway
  155. }
  156. nic.Dns = network.GetDNS("")
  157. nic.Domain = network.GetDomain()
  158. nic.Ntp = network.GetNTP()
  159. routes := network.GetRoutes()
  160. if len(routes) > 0 {
  161. nic.Routes = routes
  162. }
  163. nic.Masklen = network.GuestIpMask
  164. nic.Net = network.Name
  165. nic.NetId = network.Id
  166. nic.Masklen6 = network.GuestIp6Mask
  167. if len(network.GuestGateway6) > 0 && regutils.MatchIP6Addr(network.GuestGateway6) {
  168. nic.Gateway6 = network.GuestGateway6
  169. }
  170. }
  171. return nic
  172. }
  173. func (netIf *SNetInterface) getServernetwork() *SGuestnetwork {
  174. host := netIf.GetHost()
  175. if host == nil {
  176. return nil
  177. }
  178. server := host.GetBaremetalServer()
  179. if server == nil {
  180. return nil
  181. }
  182. obj, err := db.NewModelObject(GuestnetworkManager)
  183. if err != nil {
  184. log.Errorf("new fail %s", err)
  185. return nil
  186. }
  187. q := GuestnetworkManager.Query().Equals("guest_id", server.Id).Equals("mac_addr", netIf.Mac)
  188. err = q.First(obj)
  189. if err != nil {
  190. if err != sql.ErrNoRows {
  191. log.Errorf("query fail %s", err)
  192. }
  193. return nil
  194. }
  195. return obj.(*SGuestnetwork)
  196. }
  197. func (netIf *SNetInterface) getServerJsonDesc() *api.GuestnetworkJsonDesc {
  198. desc := &api.GuestnetworkJsonDesc{}
  199. jsonutils.Update(desc, netIf)
  200. gn := netIf.getServernetwork()
  201. if gn != nil {
  202. jsonutils.Update(desc, gn.getJsonDescAtBaremetal(netIf.GetHost()))
  203. desc.Index = netIf.Index // override, preserve orginal network interface index
  204. }
  205. return desc
  206. }
  207. func (netif *SNetInterface) getBaremetalJsonDesc() *types.SNic {
  208. nic := &types.SNic{
  209. Mac: netif.Mac,
  210. VlanId: netif.VlanId,
  211. Type: netif.NicType,
  212. Rate: netif.Rate,
  213. Mtu: netif.Mtu,
  214. LinkUp: netif.LinkUp,
  215. Interface: netif.Interface,
  216. Bridge: netif.Bridge,
  217. Index: netif.Index,
  218. }
  219. wire := netif.GetWire()
  220. if wire != nil {
  221. nic.WireId = wire.Id
  222. nic.Wire = wire.Name
  223. nic.Bandwidth = wire.Bandwidth
  224. }
  225. bn := netif.GetHostNetwork()
  226. if bn != nil {
  227. nic = netif.networkToNic(bn.IpAddr, bn.Ip6Addr, bn.GetNetwork(), nic)
  228. }
  229. return nic
  230. }
  231. func (netif *SNetInterface) Delete(ctx context.Context, userCred mcclient.TokenCredential) error {
  232. _, err := db.Update(netif, func() error {
  233. netif.WireId = ""
  234. netif.Bridge = ""
  235. netif.Interface = ""
  236. netif.BaremetalId = ""
  237. netif.Rate = 0
  238. netif.NicType = ""
  239. netif.Index = -1
  240. netif.LinkUp = false
  241. netif.Mtu = 0
  242. return nil
  243. })
  244. if err != nil {
  245. log.Errorf("Save Updates: %s", err)
  246. return errors.Wrap(err, "db.Update")
  247. }
  248. return netif.SResourceBase.Delete(ctx, userCred)
  249. }
  250. func (netIf *SNetInterface) GetCandidateNetworkForIp(ctx context.Context, userCred mcclient.TokenCredential, ownerId mcclient.IIdentityProvider, scope rbacscope.TRbacScope, ipAddr string) (*SNetwork, error) {
  251. wire := netIf.GetWire()
  252. if wire == nil {
  253. return nil, nil
  254. }
  255. log.Infof("ipAddr: %s, netiName: %s, wire: %s", ipAddr, netIf.GetName(), wire.GetName())
  256. return wire.GetCandidateNetworkForIp(ctx, userCred, ownerId, scope, ipAddr)
  257. }
  258. func (netIf *SNetInterface) GetCandidateNetworkForIp6(ctx context.Context, userCred mcclient.TokenCredential, ownerId mcclient.IIdentityProvider, scope rbacscope.TRbacScope, ip6Addr string) (*SNetwork, error) {
  259. wire := netIf.GetWire()
  260. if wire == nil {
  261. return nil, nil
  262. }
  263. log.Infof("ip6Addr: %s, netiName: %s, wire: %s", ip6Addr, netIf.GetName(), wire.GetName())
  264. return wire.GetCandidateNetworkForIp6(ctx, userCred, ownerId, scope, ip6Addr)
  265. }
  266. func (netif *SNetInterface) IsUsableServernic() bool {
  267. if netif.NicType == api.NIC_TYPE_IPMI {
  268. return false
  269. }
  270. if len(netif.WireId) == 0 {
  271. return false
  272. }
  273. if !netif.LinkUp {
  274. return false
  275. }
  276. if netif.getServernetwork() != nil {
  277. return false
  278. }
  279. return true
  280. }
  281. /*func (netif *SNetInterface) syncClassMetadata(ctx context.Context) error {
  282. host := netif.GetHost()
  283. wire := netif.GetWire()
  284. if host == nil {
  285. return errors.Wrap(errors.ErrInvalidStatus, "empty host")
  286. }
  287. if wire == nil {
  288. return errors.Wrap(errors.ErrInvalidStatus, "empty wire")
  289. }
  290. err := db.InheritFromTo(ctx, wire, host)
  291. if err != nil {
  292. log.Errorf("Inherit class metadata from host to wire fail: %s", err)
  293. return errors.Wrap(err, "InheritFromTo")
  294. }
  295. return nil
  296. }*/
  297. func (netif *SNetInterface) setNicType(tp compute.TNicType) error {
  298. _, err := db.Update(netif, func() error {
  299. netif.NicType = tp
  300. return nil
  301. })
  302. return errors.Wrap(err, "setNicType Update")
  303. }