net.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. /*
  2. Copyright 2015 The Kubernetes Authors.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package util
  14. import (
  15. "os"
  16. "strings"
  17. "github.com/pkg/errors"
  18. )
  19. // GetHostname returns OS's hostname if 'hostnameOverride' is empty; otherwise, return 'hostnameOverride'
  20. // NOTE: This function copied from pkg/util/node package to avoid external kubeadm dependency
  21. func GetHostname(hostnameOverride string) (string, error) {
  22. hostName := hostnameOverride
  23. if len(hostName) == 0 {
  24. nodeName, err := os.Hostname()
  25. if err != nil {
  26. return "", errors.Wrap(err, "couldn't determine hostname")
  27. }
  28. hostName = nodeName
  29. }
  30. // Trim whitespaces first to avoid getting an empty hostname
  31. // For linux, the hostname is read from file /proc/sys/kernel/hostname directly
  32. hostName = strings.TrimSpace(hostName)
  33. if len(hostName) == 0 {
  34. return "", errors.New("empty hostname is invalid")
  35. }
  36. return strings.ToLower(hostName), nil
  37. }