bosun.org@v0.0.0-20210513094433-e25bc3e69a1f/host/manager.go (about) 1 package host 2 3 import ( 4 "os" 5 6 "bosun.org/name" 7 "github.com/pkg/errors" 8 ) 9 10 type manager struct { 11 nameProcessor name.Processor 12 host Host 13 } 14 15 // Manager is an interface for types which manage hosts 16 // 17 // GetNameProcessor returns a name.Processor which is suitable for hosts 18 // 19 // GetHost returns the Host that represents the machine which the process is running on 20 // 21 // GetHostName returns the name of the managed host - is simply more convenient than calling manager.GetHost().GetName() 22 type Manager interface { 23 GetNameProcessor() name.Processor 24 GetHost() Host 25 GetHostName() string 26 } 27 28 var hostname = os.Hostname 29 30 // NewManager constructs a new Manager for a host which is named by the operating system 31 func NewManager(preserveFullHostName bool) (Manager, error) { 32 n, err := hostname() 33 // Prob better to return an error but this is established behavior not worth introducing a breaking change for 34 if err != nil { 35 n = "unknown" 36 } 37 38 return NewManagerForHostname(n, preserveFullHostName) 39 } 40 41 // NewManagerForHostname constructs a new Manager for a host which is named according to the 'hostname' parameter 42 func NewManagerForHostname(hostname string, preserveFullHostName bool) (Manager, error) { 43 if hostname == "" { 44 return nil, errors.New("No 'hostname' provided") 45 } 46 47 processor, err := NewHostNameProcessor(preserveFullHostName) 48 if err != nil { 49 return nil, errors.Wrap(err, "Failed to create host name processor") 50 } 51 52 host, err := NewHost(hostname, processor) 53 if err != nil { 54 return nil, errors.Wrap(err, "Failed to construct host") 55 } 56 57 f := &manager{nameProcessor: processor, host: host} 58 59 return f, nil 60 } 61 62 // GetNameProcessor returns a name.Processor which is suitable for hosts 63 func (m *manager) GetNameProcessor() name.Processor { 64 return m.nameProcessor 65 } 66 67 // GetHost returns the Host that represents the machine which the process is running on 68 func (m *manager) GetHost() Host { 69 return m.host 70 } 71 72 // GetHostName returns the name of the managed host - is simply more convenient than calling m.GetHost().GetName() 73 func (m *manager) GetHostName() string { 74 return m.host.GetName() 75 }