server_util.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. compute_apis "yunion.io/x/onecloud/pkg/apis/compute"
  18. "yunion.io/x/onecloud/pkg/httperrors"
  19. "yunion.io/x/onecloud/pkg/mcclient"
  20. "yunion.io/x/onecloud/pkg/mcclient/auth"
  21. compute_modules "yunion.io/x/onecloud/pkg/mcclient/modules/compute"
  22. )
  23. type serverInfo struct {
  24. Server *compute_apis.ServerDetails
  25. // PrivateKey is the one corresponds to userCred when getting this
  26. // serverInfo instance. It can be empty
  27. PrivateKey string
  28. }
  29. func (si *serverInfo) GetNic() *compute_apis.GuestnetworkShortDesc {
  30. nic := si.getVPCNic()
  31. if nic != nil {
  32. return nic
  33. }
  34. for _, nic := range si.Server.Nics {
  35. if nic.IpAddr != "" && nic.VpcId == compute_apis.DEFAULT_VPC_ID {
  36. return &nic
  37. }
  38. }
  39. return nil
  40. }
  41. func (si *serverInfo) getVPCNic() *compute_apis.GuestnetworkShortDesc {
  42. for _, nic := range si.Server.Nics {
  43. if nic.IpAddr != "" && nic.VpcId != compute_apis.DEFAULT_VPC_ID {
  44. return &nic
  45. }
  46. }
  47. return nil
  48. }
  49. func getServerInfo(
  50. ctx context.Context,
  51. userCred mcclient.TokenCredential,
  52. serverId string,
  53. ) (*serverInfo, error) {
  54. sess := auth.GetSession(ctx, userCred, "")
  55. serverJson, err := compute_modules.Servers.Get(sess, serverId, nil)
  56. if err != nil {
  57. return nil, httperrors.NewGeneralError(err)
  58. }
  59. server := &compute_apis.ServerDetails{}
  60. if err := serverJson.Unmarshal(server); err != nil {
  61. return nil, httperrors.NewServerError("unmarshal server %s: %v", serverId, err)
  62. }
  63. privateKey, _ := compute_modules.Sshkeypairs.FetchPrivateKey(ctx, userCred)
  64. serverInfo := &serverInfo{
  65. Server: server,
  66. PrivateKey: privateKey,
  67. }
  68. return serverInfo, nil
  69. }