本文整理汇总了Golang中os.Hostname函数的典型用法代码示例。如果您正苦于以下问题:Golang Hostname函数的具体用法?Golang Hostname怎么用?Golang Hostname使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Hostname函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: CollectMetrics
// CollectMetrics collects metrics for testing
func (f *Mock) CollectMetrics(mts []plugin.PluginMetricType) ([]plugin.PluginMetricType, error) {
for _, p := range mts {
log.Printf("collecting %+v", p)
}
rand.Seed(time.Now().UTC().UnixNano())
metrics := []plugin.PluginMetricType{}
for i := range mts {
if mts[i].Namespace()[2] == "*" {
hostname, _ := os.Hostname()
for j := 0; j < 10; j++ {
v := fmt.Sprintf("host%d", j)
data := randInt(65, 90)
mt := plugin.PluginMetricType{
Data_: data,
Namespace_: []string{"intel", "mock", v, "baz"},
Source_: hostname,
Timestamp_: time.Now(),
Labels_: mts[i].Labels(),
Version_: mts[i].Version(),
}
metrics = append(metrics, mt)
}
} else {
data := randInt(65, 90)
mts[i].Data_ = data
mts[i].Source_, _ = os.Hostname()
mts[i].Timestamp_ = time.Now()
metrics = append(metrics, mts[i])
}
}
return metrics, nil
}
示例2: NewStorageDriver
func NewStorageDriver(driverName string) (storage.StorageDriver, error) {
var storageDriver storage.StorageDriver
var err error
// TODO(vmarmol): We shouldn't need the housekeeping interval here and it shouldn't be public.
samplesToCache := int(*argDbBufferDuration / *manager.HousekeepingInterval)
if samplesToCache < statsRequestedByUI {
// The UI requests the most recent 60 stats by default.
samplesToCache = statsRequestedByUI
}
switch driverName {
case "":
// empty string by default is the in memory store
fallthrough
case "memory":
storageDriver = memory.New(*argSampleSize, int(*argDbBufferDuration))
return storageDriver, nil
case "influxdb":
var hostname string
hostname, err = os.Hostname()
if err != nil {
return nil, err
}
storageDriver, err = influxdb.New(
hostname,
"stats",
*argDbName,
*argDbUsername,
*argDbPassword,
*argDbHost,
*argDbIsSecure,
*argDbBufferDuration,
// TODO(monnand): One hour? Or user-defined?
1*time.Hour,
)
glog.V(2).Infof("Caching %d recent stats in memory\n", samplesToCache)
storageDriver = cache.MemoryCache(samplesToCache, samplesToCache, storageDriver)
case "bigquery":
var hostname string
hostname, err = os.Hostname()
if err != nil {
return nil, err
}
storageDriver, err = bigquery.New(
hostname,
"cadvisor",
*argDbName,
1*time.Hour,
)
glog.V(2).Infof("Caching %d recent stats in memory\n", samplesToCache)
storageDriver = cache.MemoryCache(samplesToCache, samplesToCache, storageDriver)
default:
err = fmt.Errorf("Unknown database driver: %v", *argDbDriver)
}
if err != nil {
return nil, err
}
return storageDriver, nil
}
示例3: eventWorker
func eventWorker() {
go func() {
// a ticker channel to limit reloads to marathon, 1s is enough for now.
ticker := time.NewTicker(1 * time.Second)
for {
select {
case <-ticker.C:
<-eventqueue
start := time.Now()
err := reload()
elapsed := time.Since(start)
if err != nil {
log.Println("config update failed")
if config.Statsd != "" {
go func() {
hostname, _ := os.Hostname()
statsd.Counter(1.0, "nixy."+hostname+".reload.failed", 1)
}()
}
} else {
log.Printf("config update took %s\n", elapsed)
if config.Statsd != "" {
go func(elapsed time.Duration) {
hostname, _ := os.Hostname()
statsd.Counter(1.0, "nixy."+hostname+".reload.success", 1)
statsd.Timing(1.0, "nixy."+hostname+".reload.time", elapsed)
}(elapsed)
}
}
}
}
}()
}
示例4: NewStorageDriver
func NewStorageDriver(driverName string) (*memory.InMemoryStorage, error) {
var storageDriver *memory.InMemoryStorage
var backendStorage storage.StorageDriver
var err error
// TODO(vmarmol): We shouldn't need the housekeeping interval here and it shouldn't be public.
samplesToCache := int(*argDbBufferDuration / *manager.HousekeepingInterval)
if samplesToCache < statsRequestedByUI {
// The UI requests the most recent 60 stats by default.
samplesToCache = statsRequestedByUI
}
switch driverName {
case "":
backendStorage = nil
case "influxdb":
var hostname string
hostname, err = os.Hostname()
if err != nil {
return nil, err
}
backendStorage, err = influxdb.New(
hostname,
"stats",
*argDbName,
*argDbUsername,
*argDbPassword,
*argDbHost,
*argDbIsSecure,
*argDbBufferDuration,
// TODO(monnand): One hour? Or user-defined?
1*time.Hour,
)
case "bigquery":
var hostname string
hostname, err = os.Hostname()
if err != nil {
return nil, err
}
backendStorage, err = bigquery.New(
hostname,
"cadvisor",
*argDbName,
1*time.Hour,
)
default:
err = fmt.Errorf("Unknown database driver: %v", *argDbDriver)
}
if err != nil {
return nil, err
}
glog.Infof("Caching %d recent stats in memory; using \"%v\" storage driver\n", samplesToCache, driverName)
storageDriver = memory.New(samplesToCache, samplesToCache, backendStorage)
return storageDriver, nil
}
示例5: main
func main() {
http.HandleFunc("/zk", getNodeInfo)
os.Hostname()
hostName, err := os.Hostname()
if err != nil {
panic(err)
}
errr := http.ListenAndServe(hostName+":"+config.HttpPort, nil)
if errr != nil {
panic(errr)
}
}
示例6: main
func main() {
c.Hostname, _ = os.Hostname()
for _, e := range os.Environ() {
pair := strings.Split(e, "=")
c.Env = append(c.Env, EnvVar{pair[0], pair[1]})
}
fmt.Println(c)
static := web.New()
static.Get("/static/*", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
http.Handle("/static/", static)
goji.Get("/", renderIndex)
// Setup our service export
host, _ := os.Hostname()
info := []string{"simple peer discovery test"}
service, _ := mdns.NewMDNSService(host, "_http._tcp", "", "", 8000, nil, info)
// Create the mDNS server, defer shutdown
fmt.Println("Creating mDNS server")
server, _ := mdns.NewServer(&mdns.Config{Zone: service})
defer server.Shutdown()
// Make a channel for results and start listening
peers := make(chan *mdns.ServiceEntry, 4)
go func() {
fmt.Println("Waiting for peers")
for entry := range peers {
known := false
for _, e := range c.Peers {
if entry.Name == e {
known = true
}
}
if known == false {
fmt.Println("Got new peer", entry.Name)
c.Peers = append(c.Peers, entry.Name)
}
}
}()
fmt.Println("Creating mDNS listener")
//mdns.Lookup("_googlecast._tcp", peers)
// this will panic without IF_MULTICAST, causing the program to exit
mdns.Lookup("_http._tcp", peers)
fmt.Println("Creating HTTP server")
goji.Serve() // port 8000 by default
close(peers)
}
示例7: NewFileLogger
func NewFileLogger(gzipEnabled bool, compressionLevel int, filenameFormat, topic string) (*FileLogger, error) {
if gzipEnabled && strings.Index(filenameFormat, "<GZIPREV>") == -1 {
return nil, errors.New("missing <GZIPREV> in filenameFormat")
}
hostname, err := os.Hostname()
if err != nil {
return nil, err
}
shortHostname := strings.Split(hostname, ".")[0]
identifier := shortHostname
if len(*hostIdentifier) != 0 {
identifier = strings.Replace(*hostIdentifier, "<SHORT_HOST>", shortHostname, -1)
identifier = strings.Replace(identifier, "<HOSTNAME>", hostname, -1)
}
filenameFormat = strings.Replace(filenameFormat, "<TOPIC>", topic, -1)
filenameFormat = strings.Replace(filenameFormat, "<HOST>", identifier, -1)
if gzipEnabled && !strings.HasSuffix(filenameFormat, ".gz") {
filenameFormat = filenameFormat + ".gz"
}
f := &FileLogger{
logChan: make(chan *Message, 1),
compressionLevel: compressionLevel,
filenameFormat: filenameFormat,
gzipEnabled: gzipEnabled,
ExitChan: make(chan int),
termChan: make(chan bool),
hupChan: make(chan bool),
}
return f, nil
}
示例8: authTokenNote
func authTokenNote(num int) (string, error) {
n := os.Getenv("USER")
if n == "" {
n = os.Getenv("USERNAME")
}
if n == "" {
whoami := exec.Command("whoami")
whoamiOut, err := whoami.Output()
if err != nil {
return "", err
}
n = strings.TrimSpace(string(whoamiOut))
}
h, err := os.Hostname()
if err != nil {
return "", err
}
if num > 1 {
return fmt.Sprintf("hub for %[email protected]%s %d", n, h, num), nil
}
return fmt.Sprintf("hub for %[email protected]%s", n, h), nil
}
示例9: buildHost
func buildHost() string {
h, err := os.Hostname()
if err != nil {
return "unknown-host"
}
return h
}
示例10: startMetrics
func startMetrics(appName, graphiteServer string) {
if graphiteServer == "" {
glog.Warningf("No metrics server specified.")
return
}
addr, err := net.ResolveTCPAddr("tcp", graphiteServer)
if err != nil {
glog.Fatalf("Unable to resolve metrics server address: %s", err)
}
// Get the hostname and create the app-prefix.
hostName, err := os.Hostname()
if err != nil {
glog.Fatalf("Unable to retrieve hostname: %s", err)
}
appPrefix := fmt.Sprintf("%s.%s", appName, strings.Replace(hostName, ".", "-", -1))
// Runtime metrics.
metrics.RegisterRuntimeMemStats(metrics.DefaultRegistry)
go metrics.CaptureRuntimeMemStats(metrics.DefaultRegistry, SAMPLE_PERIOD)
go graphite.Graphite(metrics.DefaultRegistry, SAMPLE_PERIOD, appPrefix, addr)
// Uptime.
uptimeGuage := metrics.GetOrRegisterGaugeFloat64("uptime", metrics.DefaultRegistry)
go func() {
startTime := time.Now()
uptimeGuage.Update(0)
for _ = range time.Tick(SAMPLE_PERIOD) {
uptimeGuage.Update(time.Since(startTime).Seconds())
}
}()
}
示例11: init
func init() {
// Set up builtin middlewarez
OnBeforeNotify(httpRequestMiddleware)
// Default configuration
Config.update(&Configuration{
APIKey: "",
Endpoint: "https://notify.bugsnag.com/",
Hostname: "",
AppVersion: "",
ReleaseStage: "",
ParamsFilters: []string{"password", "secret"},
// * for app-engine
ProjectPackages: []string{"main*"},
NotifyReleaseStages: nil,
Logger: log.New(os.Stdout, log.Prefix(), log.Flags()),
PanicHandler: defaultPanicHandler,
Transport: http.DefaultTransport,
})
hostname, err := os.Hostname()
if err == nil {
Config.Hostname = hostname
}
}
示例12: getHostname
func getHostname() string {
hostname, err := os.Hostname()
if err != nil {
hostname = "hostname"
}
return hostname
}
示例13: InitConfig
func InitConfig() {
var err error
WorkDir, err = com.WorkDir()
if err != nil {
panic(err)
}
ConfigPath = path.Join(WorkDir, "conf")
Hostname, err := os.Hostname()
if err != nil {
panic(err)
}
fmt.Println(Hostname)
err = initHosts()
if err != nil {
panic(err)
}
fmt.Println(Cfg)
UserPath = path.Join(ConfigPath, Cfg.GetUserDir(Hostname))
fmt.Println(ConfigPath, UserPath)
InitServices()
}
示例14: Handle
func (*hostnameHandler) Handle(ctx context.Context, prev <-chan ql.Line, next chan<- ql.Line, config map[string]interface{}) error {
field := "hostname"
ok := true
fieldIface := config["field"]
if fieldIface != nil {
field, ok = fieldIface.(string)
if !ok {
log.Log(ctx).Warn("Could not parse hostname config, using field=hostname")
field = "hostname"
}
}
log.Log(ctx).Debug("Starting filter handler", "handler", "hostname", "field", field)
hostname, _ := os.Hostname()
go func() {
for {
select {
case line := <-prev:
line.Data[field] = hostname
next <- line
case <-ctx.Done():
return
}
}
}()
return nil
}
示例15: prepare
func (cfg *Configuration) prepare(myID protocol.DeviceID) error {
var myName string
// Ensure this device is present in the config
for _, device := range cfg.Devices {
if device.DeviceID == myID {
goto found
}
}
myName, _ = os.Hostname()
cfg.Devices = append(cfg.Devices, DeviceConfiguration{
DeviceID: myID,
Name: myName,
})
found:
if err := cfg.clean(); err != nil {
return err
}
// Ensure that we are part of the devices
for i := range cfg.Folders {
cfg.Folders[i].Devices = ensureDevicePresent(cfg.Folders[i].Devices, myID)
}
return nil
}