hcnnetwork.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. //go:build windows
  2. package hcn
  3. import (
  4. "encoding/json"
  5. "errors"
  6. "github.com/Microsoft/go-winio/pkg/guid"
  7. "github.com/Microsoft/hcsshim/internal/interop"
  8. "github.com/sirupsen/logrus"
  9. )
  10. // Route is associated with a subnet.
  11. type Route struct {
  12. NextHop string `json:",omitempty"`
  13. DestinationPrefix string `json:",omitempty"`
  14. Metric uint16 `json:",omitempty"`
  15. }
  16. // Subnet is associated with a Ipam.
  17. type Subnet struct {
  18. IpAddressPrefix string `json:",omitempty"`
  19. Policies []json.RawMessage `json:",omitempty"`
  20. Routes []Route `json:",omitempty"`
  21. }
  22. // Ipam (Internet Protocol Address Management) is associated with a network
  23. // and represents the address space(s) of a network.
  24. type Ipam struct {
  25. Type string `json:",omitempty"` // Ex: Static, DHCP
  26. Subnets []Subnet `json:",omitempty"`
  27. }
  28. // MacRange is associated with MacPool and respresents the start and end addresses.
  29. type MacRange struct {
  30. StartMacAddress string `json:",omitempty"`
  31. EndMacAddress string `json:",omitempty"`
  32. }
  33. // MacPool is associated with a network and represents pool of MacRanges.
  34. type MacPool struct {
  35. Ranges []MacRange `json:",omitempty"`
  36. }
  37. // Dns (Domain Name System is associated with a network).
  38. type Dns struct {
  39. Domain string `json:",omitempty"`
  40. Search []string `json:",omitempty"`
  41. ServerList []string `json:",omitempty"`
  42. Options []string `json:",omitempty"`
  43. }
  44. // NetworkType are various networks.
  45. type NetworkType string
  46. // NetworkType const
  47. const (
  48. NAT NetworkType = "NAT"
  49. Transparent NetworkType = "Transparent"
  50. L2Bridge NetworkType = "L2Bridge"
  51. L2Tunnel NetworkType = "L2Tunnel"
  52. ICS NetworkType = "ICS"
  53. Private NetworkType = "Private"
  54. Overlay NetworkType = "Overlay"
  55. )
  56. // NetworkFlags are various network flags.
  57. type NetworkFlags uint32
  58. // NetworkFlags const
  59. const (
  60. None NetworkFlags = 0
  61. EnableNonPersistent NetworkFlags = 8
  62. )
  63. // HostComputeNetwork represents a network
  64. type HostComputeNetwork struct {
  65. Id string `json:"ID,omitempty"`
  66. Name string `json:",omitempty"`
  67. Type NetworkType `json:",omitempty"`
  68. Policies []NetworkPolicy `json:",omitempty"`
  69. MacPool MacPool `json:",omitempty"`
  70. Dns Dns `json:",omitempty"`
  71. Ipams []Ipam `json:",omitempty"`
  72. Flags NetworkFlags `json:",omitempty"` // 0: None
  73. Health Health `json:",omitempty"`
  74. SchemaVersion SchemaVersion `json:",omitempty"`
  75. }
  76. // NetworkResourceType are the 3 different Network settings resources.
  77. type NetworkResourceType string
  78. var (
  79. // NetworkResourceTypePolicy is for Network's policies. Ex: RemoteSubnet
  80. NetworkResourceTypePolicy NetworkResourceType = "Policy"
  81. // NetworkResourceTypeDNS is for Network's DNS settings.
  82. NetworkResourceTypeDNS NetworkResourceType = "DNS"
  83. // NetworkResourceTypeExtension is for Network's extension settings.
  84. NetworkResourceTypeExtension NetworkResourceType = "Extension"
  85. )
  86. // ModifyNetworkSettingRequest is the structure used to send request to modify an network.
  87. // Used to update DNS/extension/policy on an network.
  88. type ModifyNetworkSettingRequest struct {
  89. ResourceType NetworkResourceType `json:",omitempty"` // Policy, DNS, Extension
  90. RequestType RequestType `json:",omitempty"` // Add, Remove, Update, Refresh
  91. Settings json.RawMessage `json:",omitempty"`
  92. }
  93. type PolicyNetworkRequest struct {
  94. Policies []NetworkPolicy `json:",omitempty"`
  95. }
  96. func getNetwork(networkGUID guid.GUID, query string) (*HostComputeNetwork, error) {
  97. // Open network.
  98. var (
  99. networkHandle hcnNetwork
  100. resultBuffer *uint16
  101. propertiesBuffer *uint16
  102. )
  103. hr := hcnOpenNetwork(&networkGUID, &networkHandle, &resultBuffer)
  104. if err := checkForErrors("hcnOpenNetwork", hr, resultBuffer); err != nil {
  105. return nil, err
  106. }
  107. // Query network.
  108. hr = hcnQueryNetworkProperties(networkHandle, query, &propertiesBuffer, &resultBuffer)
  109. if err := checkForErrors("hcnQueryNetworkProperties", hr, resultBuffer); err != nil {
  110. return nil, err
  111. }
  112. properties := interop.ConvertAndFreeCoTaskMemString(propertiesBuffer)
  113. // Close network.
  114. hr = hcnCloseNetwork(networkHandle)
  115. if err := checkForErrors("hcnCloseNetwork", hr, nil); err != nil {
  116. return nil, err
  117. }
  118. // Convert output to HostComputeNetwork
  119. var outputNetwork HostComputeNetwork
  120. // If HNS sets the network type to NAT (i.e. '0' in HNS.Schema.Network.NetworkMode),
  121. // the value will be omitted from the JSON blob. We therefore need to initialize NAT here before
  122. // unmarshaling the JSON blob.
  123. outputNetwork.Type = NAT
  124. if err := json.Unmarshal([]byte(properties), &outputNetwork); err != nil {
  125. return nil, err
  126. }
  127. return &outputNetwork, nil
  128. }
  129. func enumerateNetworks(query string) ([]HostComputeNetwork, error) {
  130. // Enumerate all Network Guids
  131. var (
  132. resultBuffer *uint16
  133. networkBuffer *uint16
  134. )
  135. hr := hcnEnumerateNetworks(query, &networkBuffer, &resultBuffer)
  136. if err := checkForErrors("hcnEnumerateNetworks", hr, resultBuffer); err != nil {
  137. return nil, err
  138. }
  139. networks := interop.ConvertAndFreeCoTaskMemString(networkBuffer)
  140. var networkIds []guid.GUID
  141. if err := json.Unmarshal([]byte(networks), &networkIds); err != nil {
  142. return nil, err
  143. }
  144. var outputNetworks []HostComputeNetwork
  145. for _, networkGUID := range networkIds {
  146. network, err := getNetwork(networkGUID, query)
  147. if err != nil {
  148. return nil, err
  149. }
  150. outputNetworks = append(outputNetworks, *network)
  151. }
  152. return outputNetworks, nil
  153. }
  154. func createNetwork(settings string) (*HostComputeNetwork, error) {
  155. // Create new network.
  156. var (
  157. networkHandle hcnNetwork
  158. resultBuffer *uint16
  159. propertiesBuffer *uint16
  160. )
  161. networkGUID := guid.GUID{}
  162. hr := hcnCreateNetwork(&networkGUID, settings, &networkHandle, &resultBuffer)
  163. if err := checkForErrors("hcnCreateNetwork", hr, resultBuffer); err != nil {
  164. return nil, err
  165. }
  166. // Query network.
  167. hcnQuery := defaultQuery()
  168. query, err := json.Marshal(hcnQuery)
  169. if err != nil {
  170. return nil, err
  171. }
  172. hr = hcnQueryNetworkProperties(networkHandle, string(query), &propertiesBuffer, &resultBuffer)
  173. if err := checkForErrors("hcnQueryNetworkProperties", hr, resultBuffer); err != nil {
  174. return nil, err
  175. }
  176. properties := interop.ConvertAndFreeCoTaskMemString(propertiesBuffer)
  177. // Close network.
  178. hr = hcnCloseNetwork(networkHandle)
  179. if err := checkForErrors("hcnCloseNetwork", hr, nil); err != nil {
  180. return nil, err
  181. }
  182. // Convert output to HostComputeNetwork
  183. var outputNetwork HostComputeNetwork
  184. // If HNS sets the network type to NAT (i.e. '0' in HNS.Schema.Network.NetworkMode),
  185. // the value will be omitted from the JSON blob. We therefore need to initialize NAT here before
  186. // unmarshaling the JSON blob.
  187. outputNetwork.Type = NAT
  188. if err := json.Unmarshal([]byte(properties), &outputNetwork); err != nil {
  189. return nil, err
  190. }
  191. return &outputNetwork, nil
  192. }
  193. func modifyNetwork(networkID string, settings string) (*HostComputeNetwork, error) {
  194. networkGUID, err := guid.FromString(networkID)
  195. if err != nil {
  196. return nil, errInvalidNetworkID
  197. }
  198. // Open Network
  199. var (
  200. networkHandle hcnNetwork
  201. resultBuffer *uint16
  202. propertiesBuffer *uint16
  203. )
  204. hr := hcnOpenNetwork(&networkGUID, &networkHandle, &resultBuffer)
  205. if err := checkForErrors("hcnOpenNetwork", hr, resultBuffer); err != nil {
  206. return nil, err
  207. }
  208. // Modify Network
  209. hr = hcnModifyNetwork(networkHandle, settings, &resultBuffer)
  210. if err := checkForErrors("hcnModifyNetwork", hr, resultBuffer); err != nil {
  211. return nil, err
  212. }
  213. // Query network.
  214. hcnQuery := defaultQuery()
  215. query, err := json.Marshal(hcnQuery)
  216. if err != nil {
  217. return nil, err
  218. }
  219. hr = hcnQueryNetworkProperties(networkHandle, string(query), &propertiesBuffer, &resultBuffer)
  220. if err := checkForErrors("hcnQueryNetworkProperties", hr, resultBuffer); err != nil {
  221. return nil, err
  222. }
  223. properties := interop.ConvertAndFreeCoTaskMemString(propertiesBuffer)
  224. // Close network.
  225. hr = hcnCloseNetwork(networkHandle)
  226. if err := checkForErrors("hcnCloseNetwork", hr, nil); err != nil {
  227. return nil, err
  228. }
  229. // Convert output to HostComputeNetwork
  230. var outputNetwork HostComputeNetwork
  231. // If HNS sets the network type to NAT (i.e. '0' in HNS.Schema.Network.NetworkMode),
  232. // the value will be omitted from the JSON blob. We therefore need to initialize NAT here before
  233. // unmarshaling the JSON blob.
  234. outputNetwork.Type = NAT
  235. if err := json.Unmarshal([]byte(properties), &outputNetwork); err != nil {
  236. return nil, err
  237. }
  238. return &outputNetwork, nil
  239. }
  240. func deleteNetwork(networkID string) error {
  241. networkGUID, err := guid.FromString(networkID)
  242. if err != nil {
  243. return errInvalidNetworkID
  244. }
  245. var resultBuffer *uint16
  246. hr := hcnDeleteNetwork(&networkGUID, &resultBuffer)
  247. if err := checkForErrors("hcnDeleteNetwork", hr, resultBuffer); err != nil {
  248. return err
  249. }
  250. return nil
  251. }
  252. // ListNetworks makes a call to list all available networks.
  253. func ListNetworks() ([]HostComputeNetwork, error) {
  254. hcnQuery := defaultQuery()
  255. networks, err := ListNetworksQuery(hcnQuery)
  256. if err != nil {
  257. return nil, err
  258. }
  259. return networks, nil
  260. }
  261. // ListNetworksQuery makes a call to query the list of available networks.
  262. func ListNetworksQuery(query HostComputeQuery) ([]HostComputeNetwork, error) {
  263. queryJSON, err := json.Marshal(query)
  264. if err != nil {
  265. return nil, err
  266. }
  267. networks, err := enumerateNetworks(string(queryJSON))
  268. if err != nil {
  269. return nil, err
  270. }
  271. return networks, nil
  272. }
  273. // GetNetworkByID returns the network specified by Id.
  274. func GetNetworkByID(networkID string) (*HostComputeNetwork, error) {
  275. hcnQuery := defaultQuery()
  276. mapA := map[string]string{"ID": networkID}
  277. filter, err := json.Marshal(mapA)
  278. if err != nil {
  279. return nil, err
  280. }
  281. hcnQuery.Filter = string(filter)
  282. networks, err := ListNetworksQuery(hcnQuery)
  283. if err != nil {
  284. return nil, err
  285. }
  286. if len(networks) == 0 {
  287. return nil, NetworkNotFoundError{NetworkID: networkID}
  288. }
  289. return &networks[0], err
  290. }
  291. // GetNetworkByName returns the network specified by Name.
  292. func GetNetworkByName(networkName string) (*HostComputeNetwork, error) {
  293. hcnQuery := defaultQuery()
  294. mapA := map[string]string{"Name": networkName}
  295. filter, err := json.Marshal(mapA)
  296. if err != nil {
  297. return nil, err
  298. }
  299. hcnQuery.Filter = string(filter)
  300. networks, err := ListNetworksQuery(hcnQuery)
  301. if err != nil {
  302. return nil, err
  303. }
  304. if len(networks) == 0 {
  305. return nil, NetworkNotFoundError{NetworkName: networkName}
  306. }
  307. return &networks[0], err
  308. }
  309. // Create Network.
  310. func (network *HostComputeNetwork) Create() (*HostComputeNetwork, error) {
  311. logrus.Debugf("hcn::HostComputeNetwork::Create id=%s", network.Id)
  312. for _, ipam := range network.Ipams {
  313. for _, subnet := range ipam.Subnets {
  314. if subnet.IpAddressPrefix != "" {
  315. hasDefault := false
  316. for _, route := range subnet.Routes {
  317. if route.NextHop == "" {
  318. return nil, errors.New("network create error, subnet has address prefix but no gateway specified")
  319. }
  320. if route.DestinationPrefix == "0.0.0.0/0" || route.DestinationPrefix == "::/0" {
  321. hasDefault = true
  322. }
  323. }
  324. if !hasDefault {
  325. return nil, errors.New("network create error, no default gateway")
  326. }
  327. }
  328. }
  329. }
  330. jsonString, err := json.Marshal(network)
  331. if err != nil {
  332. return nil, err
  333. }
  334. logrus.Debugf("hcn::HostComputeNetwork::Create JSON: %s", jsonString)
  335. network, hcnErr := createNetwork(string(jsonString))
  336. if hcnErr != nil {
  337. return nil, hcnErr
  338. }
  339. return network, nil
  340. }
  341. // Delete Network.
  342. func (network *HostComputeNetwork) Delete() error {
  343. logrus.Debugf("hcn::HostComputeNetwork::Delete id=%s", network.Id)
  344. if err := deleteNetwork(network.Id); err != nil {
  345. return err
  346. }
  347. return nil
  348. }
  349. // ModifyNetworkSettings updates the Policy for a network.
  350. func (network *HostComputeNetwork) ModifyNetworkSettings(request *ModifyNetworkSettingRequest) error {
  351. logrus.Debugf("hcn::HostComputeNetwork::ModifyNetworkSettings id=%s", network.Id)
  352. networkSettingsRequest, err := json.Marshal(request)
  353. if err != nil {
  354. return err
  355. }
  356. _, err = modifyNetwork(network.Id, string(networkSettingsRequest))
  357. if err != nil {
  358. return err
  359. }
  360. return nil
  361. }
  362. // AddPolicy applies a Policy (ex: RemoteSubnet) on the Network.
  363. func (network *HostComputeNetwork) AddPolicy(networkPolicy PolicyNetworkRequest) error {
  364. logrus.Debugf("hcn::HostComputeNetwork::AddPolicy id=%s", network.Id)
  365. settingsJSON, err := json.Marshal(networkPolicy)
  366. if err != nil {
  367. return err
  368. }
  369. requestMessage := &ModifyNetworkSettingRequest{
  370. ResourceType: NetworkResourceTypePolicy,
  371. RequestType: RequestTypeAdd,
  372. Settings: settingsJSON,
  373. }
  374. return network.ModifyNetworkSettings(requestMessage)
  375. }
  376. // RemovePolicy removes a Policy (ex: RemoteSubnet) from the Network.
  377. func (network *HostComputeNetwork) RemovePolicy(networkPolicy PolicyNetworkRequest) error {
  378. logrus.Debugf("hcn::HostComputeNetwork::RemovePolicy id=%s", network.Id)
  379. settingsJSON, err := json.Marshal(networkPolicy)
  380. if err != nil {
  381. return err
  382. }
  383. requestMessage := &ModifyNetworkSettingRequest{
  384. ResourceType: NetworkResourceTypePolicy,
  385. RequestType: RequestTypeRemove,
  386. Settings: settingsJSON,
  387. }
  388. return network.ModifyNetworkSettings(requestMessage)
  389. }
  390. // CreateEndpoint creates an endpoint on the Network.
  391. func (network *HostComputeNetwork) CreateEndpoint(endpoint *HostComputeEndpoint) (*HostComputeEndpoint, error) {
  392. isRemote := endpoint.Flags&EndpointFlagsRemoteEndpoint != 0
  393. logrus.Debugf("hcn::HostComputeNetwork::CreatEndpoint, networkId=%s remote=%t", network.Id, isRemote)
  394. endpoint.HostComputeNetwork = network.Id
  395. endpointSettings, err := json.Marshal(endpoint)
  396. if err != nil {
  397. return nil, err
  398. }
  399. newEndpoint, err := createEndpoint(network.Id, string(endpointSettings))
  400. if err != nil {
  401. return nil, err
  402. }
  403. return newEndpoint, nil
  404. }
  405. // CreateRemoteEndpoint creates a remote endpoint on the Network.
  406. func (network *HostComputeNetwork) CreateRemoteEndpoint(endpoint *HostComputeEndpoint) (*HostComputeEndpoint, error) {
  407. endpoint.Flags = EndpointFlagsRemoteEndpoint | endpoint.Flags
  408. return network.CreateEndpoint(endpoint)
  409. }