예제 #1
0
// 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
0
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
0
파일: marathon.go 프로젝트: imjerrybao/nixy
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
0
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
0
파일: ZkClient.go 프로젝트: kevin8096/go-zk
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
0
파일: web.go 프로젝트: ruo91/go-http-mdns
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
0
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
0
파일: client.go 프로젝트: aergonaut/hub
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 %s@%s %d", n, h, num), nil
	}

	return fmt.Sprintf("hub for %s@%s", n, h), nil
}
예제 #9
0
func buildHost() string {
	h, err := os.Hostname()
	if err != nil {
		return "unknown-host"
	}
	return h
}
예제 #10
0
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
0
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
0
func getHostname() string {
	hostname, err := os.Hostname()
	if err != nil {
		hostname = "hostname"
	}
	return hostname
}
예제 #13
0
파일: setting.go 프로젝트: weisd/api
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
0
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
0
파일: config.go 프로젝트: kluppy/syncthing
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
}
예제 #16
0
파일: push.go 프로젝트: Griesbacher/nagflux
// HostnameGroupingKey returns a label map with the only entry
// {instance="<hostname>"}. This can be conveniently used as the grouping
// parameter if metrics should be pushed with the hostname as label. The
// returned map is created upon each call so that the caller is free to add more
// labels to the map.
func HostnameGroupingKey() map[string]string {
	hostname, err := os.Hostname()
	if err != nil {
		return map[string]string{"instance": "unknown"}
	}
	return map[string]string{"instance": hostname}
}
예제 #17
0
func loadHostName() string {
	hostname, err := os.Hostname()
	if err != nil {
		hostname = "unknown"
	}
	return hostname
}
예제 #18
0
// DeleteNetwork deletes a network by named identifier
func (d *OvsDriver) DeleteNetwork(id, nwType, encap string, pktTag, extPktTag int, gateway string, tenant string) error {
	log.Infof("delete net %s, nwType %s, encap %s, tags: %d/%d", id, nwType, encap, pktTag, extPktTag)

	// Find the switch based on network type
	var sw *OvsSwitch
	if encap == "vxlan" {
		sw = d.switchDb["vxlan"]
	} else {
		sw = d.switchDb["vlan"]
	}

	// Delete infra nw endpoint if present
	if nwType == "infra" {
		hostName, _ := os.Hostname()
		epID := id + "-" + hostName

		epOper := OvsOperEndpointState{}
		epOper.StateDriver = d.oper.StateDriver
		err := epOper.Read(epID)
		if err == nil {
			err = sw.DeletePort(&epOper, true)
			if err != nil {
				log.Errorf("Error deleting endpoint: %+v. Err: %v", epOper, err)
			}
			epOper.Clear()
		}
	}

	return sw.DeleteNetwork(uint16(pktTag), uint32(extPktTag), gateway, tenant)
}
예제 #19
0
파일: kite.go 프로젝트: BobbWu/kite
func init() {
	var err error
	hostname, err = os.Hostname()
	if err != nil {
		panic(fmt.Sprintf("kite: cannot get hostname: %s", err.Error()))
	}
}
예제 #20
0
파일: lock.go 프로젝트: ckemper67/restic
// Stale returns true if the lock is stale. A lock is stale if the timestamp is
// older than 30 minutes or if it was created on the current machine and the
// process isn't alive any more.
func (l *Lock) Stale() bool {
	debug.Log("testing if lock %v for process %d is stale", l, l.PID)
	if time.Since(l.Time) > staleTimeout {
		debug.Log("lock is stale, timestamp is too old: %v\n", l.Time)
		return true
	}

	hn, err := os.Hostname()
	if err != nil {
		debug.Log("unable to find current hostnanme: %v", err)
		// since we cannot find the current hostname, assume that the lock is
		// not stale.
		return false
	}

	if hn != l.Hostname {
		// lock was created on a different host, assume the lock is not stale.
		return false
	}

	// check if we can reach the process retaining the lock
	exists := l.processExists()
	if !exists {
		debug.Log("could not reach process, %d, lock is probably stale\n", l.PID)
		return true
	}

	debug.Log("lock not stale\n")
	return false
}
예제 #21
0
파일: server.go 프로젝트: ngaut/logbase
// Currently makes a linux kill file.
func MakeKillFile() error {
	err := os.RemoveAll(KILLFILE_PATH)
	if err != nil {
		return err
	}
	file, err2 :=
		os.OpenFile(
			KILLFILE_PATH,
			os.O_CREATE|
				os.O_APPEND|
				os.O_RDWR,
			0744)
	defer file.Close()
	if err2 != nil {
		return err2
	}
	_, err = fmt.Fprintln(file, "#!/bin/bash")
	if err != nil {
		fmt.Println("Problem creating the kill file: ", err)
		return err
	}
	host, _ := os.Hostname()
	pid := os.Getpid()
	fmt.Fprintf(file, "# host %s\n", host)
	fmt.Fprintf(file, "pkill -SIGKILL -P %d # Terminate subprocesses\n", pid)
	_, err = fmt.Fprintf(file, "kill -SIGKILL %d # Terminate parent\n", pid)
	return err
}
예제 #22
0
파일: main.go 프로젝트: weaveworks/mesh
func mustHostname() string {
	hostname, err := os.Hostname()
	if err != nil {
		panic(err)
	}
	return hostname
}
예제 #23
0
func TestDeviceAddressesStatic(t *testing.T) {
	name, _ := os.Hostname()
	expected := map[protocol.DeviceID]DeviceConfiguration{
		device1: {
			DeviceID:  device1,
			Addresses: []string{"tcp://192.0.2.1", "tcp://192.0.2.2"},
		},
		device2: {
			DeviceID:  device2,
			Addresses: []string{"tcp://192.0.2.3:6070", "tcp://[2001:db8::42]:4242"},
		},
		device3: {
			DeviceID:  device3,
			Addresses: []string{"tcp://[2001:db8::44]:4444", "tcp://192.0.2.4:6090"},
		},
		device4: {
			DeviceID:    device4,
			Name:        name, // Set when auto created
			Addresses:   []string{"dynamic"},
			Compression: protocol.CompressMetadata,
		},
	}

	cfg, err := Load("testdata/deviceaddressesstatic.xml", device4)
	if err != nil {
		t.Error(err)
	}

	actual := cfg.Devices()
	if diff, equal := messagediff.PrettyDiff(expected, actual); !equal {
		t.Errorf("Devices differ. Diff:\n%s", diff)
	}
}
예제 #24
0
// ServerInfo - get server info.
func (web *webAPIHandlers) ServerInfo(r *http.Request, args *WebGenericArgs, reply *ServerInfoRep) error {
	if !isJWTReqAuthenticated(r) {
		return toJSONError(errAuthentication)
	}
	host, err := os.Hostname()
	if err != nil {
		host = ""
	}
	memstats := &runtime.MemStats{}
	runtime.ReadMemStats(memstats)
	mem := fmt.Sprintf("Used: %s | Allocated: %s | Used-Heap: %s | Allocated-Heap: %s",
		humanize.Bytes(memstats.Alloc),
		humanize.Bytes(memstats.TotalAlloc),
		humanize.Bytes(memstats.HeapAlloc),
		humanize.Bytes(memstats.HeapSys))
	platform := fmt.Sprintf("Host: %s | OS: %s | Arch: %s",
		host,
		runtime.GOOS,
		runtime.GOARCH)
	goruntime := fmt.Sprintf("Version: %s | CPUs: %s", runtime.Version(), strconv.Itoa(runtime.NumCPU()))

	reply.MinioEnvVars = os.Environ()
	reply.MinioVersion = Version
	reply.MinioMemory = mem
	reply.MinioPlatform = platform
	reply.MinioRuntime = goruntime
	reply.UIVersion = miniobrowser.UIVersion
	return nil
}
예제 #25
0
// Handle writes the error from the context into the HttpResponseWriter with a
// 500 http.StatusInternalServerError status code.
func (h *DefaultErrorHandler) Handle(ctx context.Context) (stop bool, err error) {

	var handlerError HandlerError = ctx.Data().Get(DataKeyForError).(HandlerError)
	hostname, _ := os.Hostname()

	w := ctx.HttpResponseWriter()

	// write the error out
	w.Header().Set("Content-Type", "text/html")
	w.WriteHeader(http.StatusInternalServerError)
	w.Write([]byte("<!DOCTYPE html><html><head>"))
	w.Write([]byte("<style>"))
	w.Write([]byte("h1 { font-size: 17px }"))
	w.Write([]byte("h1 strong {text-decoration:underline}"))
	w.Write([]byte("h2 { background-color: #ffd; padding: 20px }"))
	w.Write([]byte("footer { margin-top: 20px; border-top:1px solid black; padding:10px; font-size:0.9em }"))
	w.Write([]byte("</style>"))
	w.Write([]byte("</head><body>"))
	w.Write([]byte(fmt.Sprintf("<h1>Error in <code>%s</code></h1><h2>%s</h2>", handlerError.Handler, handlerError)))
	w.Write([]byte(fmt.Sprintf("<h3><code>%s</code> error in Handler <code>%v</code></h3> <code><pre>%s</pre></code>", reflect.TypeOf(handlerError.OriginalError), &handlerError.Handler, handlerError.Handler)))
	w.Write([]byte(fmt.Sprintf("on %s", hostname)))
	w.Write([]byte("<footer>Learn more about <a href='http://github.com/stretchr/goweb' target='_blank'>Goweb</a></footer>"))
	w.Write([]byte("</body></html>"))

	// responses are actually ignored
	return false, nil
}
예제 #26
0
파일: reader.go 프로젝트: rif/golang-stuff
// NewReader creates a new instance of Reader for the specified topic/channel
//
// The returned Reader instance is setup with sane default values.  To modify
// configuration, update the values on the returned instance before connecting.
func NewReader(topic string, channel string) (*Reader, error) {
	if !IsValidTopicName(topic) {
		return nil, errors.New("invalid topic name")
	}

	if !IsValidChannelName(channel) {
		return nil, errors.New("invalid channel name")
	}

	hostname, err := os.Hostname()
	if err != nil {
		log.Fatalf("ERROR: unable to get hostname %s", err.Error())
	}
	q := &Reader{
		TopicName:           topic,
		ChannelName:         channel,
		incomingMessages:    make(chan *incomingMessage),
		ExitChan:            make(chan int),
		nsqConnections:      make(map[string]*nsqConn),
		MaxAttemptCount:     5,
		LookupdPollInterval: 120 * time.Second,
		lookupdExitChan:     make(chan int),
		lookupdRecheckChan:  make(chan int, 1), // used at connection close to force a possible reconnect
		DefaultRequeueDelay: 90 * time.Second,
		MaxRequeueDelay:     15 * time.Minute,
		ShortIdentifier:     strings.Split(hostname, ".")[0],
		LongIdentifier:      hostname,
		ReadTimeout:         DefaultClientTimeout,
		WriteTimeout:        time.Second,
		maxInFlight:         1,
	}
	q.SetMaxBackoffDuration(120 * time.Second)
	return q, nil
}
예제 #27
0
// GET /info
func getInfo(c *context, w http.ResponseWriter, r *http.Request) {
	info := dockerclient.Info{
		Containers:        int64(len(c.cluster.Containers())),
		Images:            int64(len(c.cluster.Images().Filter(cluster.ImageFilterOptions{}))),
		DriverStatus:      c.statusHandler.Status(),
		NEventsListener:   int64(c.eventsHandler.Size()),
		Debug:             c.debug,
		MemoryLimit:       true,
		SwapLimit:         true,
		IPv4Forwarding:    true,
		BridgeNfIptables:  true,
		BridgeNfIp6tables: true,
		NCPU:              c.cluster.TotalCpus(),
		MemTotal:          c.cluster.TotalMemory(),
		HttpProxy:         os.Getenv("http_proxy"),
		HttpsProxy:        os.Getenv("https_proxy"),
		NoProxy:           os.Getenv("no_proxy"),
		SystemTime:        time.Now().Format(time.RFC3339Nano),
	}

	if hostname, err := os.Hostname(); err == nil {
		info.Name = hostname
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(info)
}
예제 #28
0
func HostInfo() (*HostInfoStat, error) {
	ret := &HostInfoStat{
		OS: runtime.GOOS,
	}

	hostname, err := os.Hostname()
	if err == nil {
		ret.Hostname = hostname
	}

	platform, family, version, err := GetPlatformInformation()
	if err == nil {
		ret.Platform = platform
		ret.PlatformFamily = family
		ret.PlatformVersion = version
	} else {
		return ret, err
	}

	ret.Uptime, err = BootTime()
	if err != nil {
		return ret, err
	}

	procs, err := process.Pids()
	if err != nil {
		return ret, err
	}

	ret.Procs = uint64(len(procs))

	return ret, nil
}
예제 #29
0
// OtherSystemInfo retrieves information from the system like hostname, IPv4 address, pagesize,
// target architecture and target operating system.
func OtherSystemInfo() map[string]string {
	otherInfoMap := make(map[string]string)

	// Hostname
	hostname, err := os.Hostname()
	if err != nil {
		otherInfoMap["hostname"] = "Error: The hostname for the current system could not be retrieved."
	} else {
		otherInfoMap["hostname"] = hostname
	}

	// IP address
	addresses, err := net.LookupHost(hostname)
	if err != nil {
		otherInfoMap["ipv4_address"] = "Error: The IPv4 address for the current system could not be retrieved."
	} else {
		for _, address := range addresses {
			ipv4_address := net.ParseIP(address).To4()
			if ipv4_address != nil {
				otherInfoMap["ipv4_address"] = address
			}
		}
	}

	otherInfoMap["os_pagesize"] = strconv.Itoa(os.Getpagesize())
	otherInfoMap["target_architecture"] = runtime.GOARCH
	otherInfoMap["target_os"] = runtime.GOOS
	return otherInfoMap
}
예제 #30
0
func main() {
	hostname, err := os.Hostname()
	if err != nil {
		hostname = "unknown"
	}

	flag.StringVar(&prefix, "p", fmt.Sprintf("bucky-pickle-relay.%s", hostname),
		"Prefix for internally generated metrics.")
	flag.StringVar(&bindTo, "b", ":2004",
		"Address to bind to for incoming connections.")
	flag.BoolVar(&debug, "d", false,
		"Debug mode.")
	flag.IntVar(&pickleTimeout, "t", 300,
		"Timeout in seconds on incoming pickle protocol TCP connections.")
	flag.IntVar(&sendTimeout, "s", 30,
		"TCP timeout in seconds for outgoing line protocol connections.")
	flag.IntVar(&maxPickleSize, "x", 1*1024*1024,
		"Maximum pickle size accepted.")
	flag.IntVar(&pickleQueueSize, "q", 0,
		"Internal buffer sizes.")
	flag.DurationVar(&metricInterval, "i", 60,
		"Interval in seconds between reporting of internal metrics.")
	flag.Parse()
	if flag.NArg() != 1 {
		usage()
	}

	log.Printf("bucky-pickle-relay Copyright 2015 42 Lines, Inc.")
	carbonRelay = flag.Arg(0)
	log.Printf("Sending line protocol data to %s", carbonRelay)
	log.Printf("Reporting internal metrics under %s", prefix)

	metrics := serveForever()
	plainTextOut(metrics)
}