Example #1
0
func TestProvideModel(t *testing.T) {
	r := Resource{}
	assertNoErr(db.Save(&r).Error)

	router = gin.New()
	router.GET("/r/:id", res.ProvideModel(func(c *gin.Context, s resources.DBModel) {
		if s == nil {
			t.Fatal("ProvideModel passed a nil DBModel")
		}
		c.String(200, "OK")
	}))

	tests := []struct {
		Code int
		ID   string
	}{
		{200, strconv.FormatUint(uint64(r.ID), 10)},
		// We only have one resource, so this shouldn't exist
		{404, strconv.FormatUint(uint64(r.ID+1), 10)},
		{404, "0"},
		{404, "not-an-id"},
	}

	for _, test := range tests {
		path := fmt.Sprintf("/r/%s", test.ID)
		res := doRequest(t, "GET", path, nil)

		if res.Code != test.Code {
			t.Fatalf("Error finding resource at %s, expected %d, got %d: %v", path, test.Code, res.Code, res)
		}
	}
}
Example #2
0
// ExtractTar extracts a tarball (from a io.Reader) into the given directory
// if pwl is not nil, only the paths in the map are extracted.
// If overwrite is true, existing files will be overwritten.
// The extraction is executed by fork/exec()ing a new process. The new process
// needs the CAP_SYS_CHROOT capability.
func ExtractTar(rs io.Reader, dir string, overwrite bool, uidRange *user.UidRange, pwl PathWhitelistMap) error {
	r, w, err := os.Pipe()
	if err != nil {
		return err
	}
	defer w.Close()
	enc := json.NewEncoder(w)
	cmd := mcEntrypoint.Cmd(dir, strconv.FormatBool(overwrite),
		strconv.FormatUint(uint64(uidRange.Shift), 10),
		strconv.FormatUint(uint64(uidRange.Count), 10))
	cmd.ExtraFiles = []*os.File{r}

	cmd.Stdin = rs
	encodeCh := make(chan error)
	go func() {
		encodeCh <- enc.Encode(pwl)
	}()

	out, err := cmd.CombinedOutput()

	// read from blocking encodeCh to release the goroutine
	encodeErr := <-encodeCh
	if err != nil {
		return fmt.Errorf("extracttar error: %v, output: %s", err, out)
	}
	if encodeErr != nil {
		return errwrap.Wrap(errors.New("extracttar failed to json encode filemap"), encodeErr)
	}
	return nil
}
Example #3
0
func programMangle(vni uint32, add bool) (err error) {
	var (
		p      = strconv.FormatUint(uint64(vxlanPort), 10)
		c      = fmt.Sprintf("0>>22&0x3C@12&0xFFFFFF00=%d", int(vni)<<8)
		m      = strconv.FormatUint(uint64(mark), 10)
		chain  = "OUTPUT"
		rule   = []string{"-p", "udp", "--dport", p, "-m", "u32", "--u32", c, "-j", "MARK", "--set-mark", m}
		a      = "-A"
		action = "install"
	)

	if add == iptables.Exists(iptables.Mangle, chain, rule...) {
		return
	}

	if !add {
		a = "-D"
		action = "remove"
	}

	if err = iptables.RawCombinedOutput(append([]string{"-t", string(iptables.Mangle), a, chain}, rule...)...); err != nil {
		logrus.Warnf("could not %s mangle rule: %v", action, err)
	}

	return
}
Example #4
0
func (p Port) PortPathsFor() (base string, path string) {
	root := Device("1").DevicePath()
	prefix := p / portsPerBlock
	base = filepath.Join(root, strconv.FormatUint(uint64(prefix), 10))
	path = filepath.Join(base, strconv.FormatUint(uint64(p), 10))
	return
}
Example #5
0
func (a *Auditor) Insert(r *RequestBundle, key, ip string, user User, from, to map[string]interface{}) error {
	changes := []Change{}
	for k, v := range to {
		id, err := r.GetID()
		if err != nil {
			return err
		}
		change := Change{
			ID:        id,
			Key:       key,
			From:      from[k],
			To:        v,
			Field:     k,
			Timestamp: time.Now(),
			IP:        ip,
			User:      user,
		}
		changes = append(changes, change)
	}
	reply := a.client.MultiCall(func(mc *redis.MultiCall) {
		for _, change := range changes {
			user_str := ""
			if change.User.ID != 0 {
				user_str = strconv.FormatUint(change.User.ID, 10)
			}
			mc.Hmset("audit:"+change.Key+":item:"+strconv.FormatUint(change.ID, 10), "from", change.From, "to", change.To, "field", change.Field, "timestamp", change.Timestamp.Format(time.RFC3339), "user", user_str)
			mc.Lpush("audit:"+key, change.ID)
		}
	})
	return reply.Err
}
Example #6
0
func monitor() {
	go logStatus()

	if len(*flaghttp) == 0 {
		return
	}
	go hub.run()
	go httpHandler()

	lastQueryCount := qCounter
	for {
		newQueries := qCounter - lastQueryCount
		lastQueryCount = qCounter

		status := map[string]string{}
		status["up"] = strconv.Itoa(int(time.Since(timeStarted).Seconds()))
		status["qs"] = strconv.FormatUint(qCounter, 10)
		status["qps"] = strconv.FormatUint(newQueries, 10)

		message, err := json.Marshal(status)

		if err == nil {
			hub.broadcast <- string(message)
		}
		time.Sleep(1 * time.Second)
	}
}
Example #7
0
// encode metadata to context in grpc specific way
func (f *framework) makeGRPCContext(ctx context.Context) context.Context {
	md := metadata.MD{
		"taskID": strconv.FormatUint(f.taskID, 10),
		"epoch":  strconv.FormatUint(f.epoch, 10),
	}
	return metadata.NewContext(ctx, md)
}
Example #8
0
func ToStr(value interface{}, args ...int) (s string) {
	switch v := value.(type) {
	case bool:
		s = strconv.FormatBool(v)
	case float32:
		s = strconv.FormatFloat(float64(v), 'f', argInt(args).Get(0, -1), argInt(args).Get(1, 32))
	case float64:
		s = strconv.FormatFloat(v, 'f', argInt(args).Get(0, -1), argInt(args).Get(1, 64))
	case int:
		s = strconv.FormatInt(int64(v), argInt(args).Get(0, 10))
	case int16:
		s = strconv.FormatInt(int64(v), argInt(args).Get(0, 10))
	case int32:
		s = strconv.FormatInt(int64(v), argInt(args).Get(0, 10))
	case int64:
		s = strconv.FormatInt(v, argInt(args).Get(0, 10))
	case uint:
		s = strconv.FormatUint(uint64(v), argInt(args).Get(0, 10))
	case uint16:
		s = strconv.FormatUint(uint64(v), argInt(args).Get(0, 10))
	case uint32:
		s = strconv.FormatUint(uint64(v), argInt(args).Get(0, 10))
	case uint64:
		s = strconv.FormatUint(v, argInt(args).Get(0, 10))
	case string:
		s = v
	default:
		s = fmt.Sprintf("%v", v)
	}
	return s
}
Example #9
0
func (r *RequestBundle) storeSubscription(userID uint64, subscription *Subscription) error {
	// start instrumentation
	changes := map[string]interface{}{}
	from := map[string]interface{}{}
	old_user, err := r.GetUser(userID)
	// add repo call to instrumentation
	if err != nil {
		return err
	}
	old_sub := old_user.Subscription
	if old_sub.Expires != subscription.Expires {
		changes["subscription_expires"] = subscription.Expires.Format(time.RFC3339)
		from["subscription_expires"] = old_sub.Expires.Format(time.RFC3339)
	}
	if old_sub.ID != subscription.ID {
		changes["subscription_id"] = subscription.ID
		from["subscription_id"] = old_sub.ID
	}
	reply := r.Repo.client.MultiCall(func(mc *redis.MultiCall) {
		mc.Hmset("users:"+strconv.FormatUint(userID, 10), changes)
		mc.Zadd("users_by_subscription_expiration", subscription.Expires.Unix(), userID)
	})
	// add repo call to instrumentation
	if reply.Err != nil {
		r.Log.Error(reply.Err.Error())
		return reply.Err
	}
	r.AuditMap("users:"+strconv.FormatUint(userID, 10), from, changes)
	// stop instrumentation
	return nil
}
Example #10
0
// Heartbeat checks the status of a follower.
func (t *HTTPTransport) Heartbeat(uri *url.URL, term, commitIndex, leaderID uint64) (uint64, error) {
	// Construct URL.
	u := *uri
	u.Path = path.Join(u.Path, "raft/heartbeat")

	// Set URL parameters.
	v := &url.Values{}
	v.Set("term", strconv.FormatUint(term, 10))
	v.Set("commitIndex", strconv.FormatUint(commitIndex, 10))
	v.Set("leaderID", strconv.FormatUint(leaderID, 10))
	u.RawQuery = v.Encode()

	// Send HTTP request.
	resp, err := http.Get(u.String())
	if err != nil {
		return 0, err
	}
	_ = resp.Body.Close()

	// Parse returned index.
	newIndexString := resp.Header.Get("X-Raft-Index")
	newIndex, err := strconv.ParseUint(newIndexString, 10, 64)
	if err != nil {
		return 0, fmt.Errorf("invalid index: %q", newIndexString)
	}

	// Parse returned error.
	if s := resp.Header.Get("X-Raft-Error"); s != "" {
		return newIndex, errors.New(s)
	}

	return newIndex, nil
}
Example #11
0
func (c *channel) createSubChannel(direction direction) (libchan.Sender, libchan.Receiver, error) {
	if c.direction == inbound {
		return nil, nil, errors.New("cannot create sub channel of an inbound channel")
	}
	referenceID := c.session.nextReferenceID()
	headers := http.Header{}
	headers.Set("libchan-ref", strconv.FormatUint(referenceID, 10))
	headers.Set("libchan-parent-ref", strconv.FormatUint(c.referenceID, 10))

	stream, streamErr := c.stream.CreateSubStream(headers, false)
	if streamErr != nil {
		return nil, nil, streamErr
	}
	subChannel := &channel{
		referenceID: referenceID,
		parentID:    c.referenceID,
		stream:      stream,
		session:     c.session,
		direction:   direction,
	}

	c.session.channelC.L.Lock()
	c.session.channels[referenceID] = subChannel
	c.session.channelC.L.Unlock()

	return subChannel, subChannel, nil
}
Example #12
0
func (vr *VersionRecord) String() string {
	buf := new(bytes.Buffer)
	buf.WriteString(vr.stamp.Format(time.RFC3339Nano))
	buf.WriteString(Delimiter1)
	buf.WriteString(vr.cmd)
	buf.WriteString(Delimiter1)
	buf.WriteString(vr.ra.String())
	buf.WriteString(Delimiter1)
	buf.WriteString(vr.la.String())
	buf.WriteString(Delimiter1)
	buf.WriteString(strconv.FormatInt(int64(vr.version), 10))
	buf.WriteString(Delimiter1)
	buf.WriteString(strconv.FormatUint(vr.services, 10))
	buf.WriteString(Delimiter1)
	buf.WriteString(strconv.FormatInt(vr.sent.Unix(), 10))
	buf.WriteString(Delimiter1)
	buf.WriteString(vr.raddr.String())
	buf.WriteString(Delimiter1)
	buf.WriteString(vr.laddr.String())
	buf.WriteString(Delimiter1)
	buf.WriteString(strconv.FormatInt(int64(vr.block), 10))
	buf.WriteString(Delimiter1)
	buf.WriteString(strconv.FormatBool(vr.relay))
	buf.WriteString(Delimiter1)
	buf.WriteString(strconv.FormatUint(vr.nonce, 10))
	buf.WriteString(Delimiter1)
	buf.WriteString(vr.agent)

	return buf.String()
}
Example #13
0
// Unsubscribe unsubscribes a replica from a topic on the broker.
func (c *Client) Unsubscribe(replicaID, topicID uint64) error {
	var resp *http.Response
	var err error

	u := *c.LeaderURL()
	for {
		u.Path = "/messaging/subscriptions"
		u.RawQuery = url.Values{
			"replicaID": {strconv.FormatUint(replicaID, 10)},
			"topicID":   {strconv.FormatUint(topicID, 10)},
		}.Encode()
		req, _ := http.NewRequest("DELETE", u.String(), nil)
		resp, err = http.DefaultClient.Do(req)
		if err != nil {
			return err
		}
		defer func() { _ = resp.Body.Close() }()

		// If a temporary redirect occurs then update the leader and retry.
		// If a non-204 status is returned then an error occurred.
		if resp.StatusCode == http.StatusTemporaryRedirect {
			redirectURL, err := url.Parse(resp.Header.Get("Location"))
			if err != nil {
				return fmt.Errorf("bad redirect: %s", resp.Header.Get("Location"))
			}
			u = *redirectURL
			continue
		} else if resp.StatusCode != http.StatusNoContent {
			return errors.New(resp.Header.Get("X-Broker-Error"))
		}
		break
	}

	return nil
}
Example #14
0
func DeviceInodeString(dev, ino uint64) string {
	if dev == 0 && ino == 0 {
		return ""
	} else {
		return strconv.FormatUint(dev, 10) + ":" + strconv.FormatUint(ino, 10)
	}
}
Example #15
0
// ReadFrom streams the log from a leader.
func (t *HTTPTransport) ReadFrom(uri *url.URL, id, term, index uint64) (io.ReadCloser, error) {
	// Construct URL.
	u := *uri
	u.Path = path.Join(u.Path, "raft/stream")

	// Set URL parameters.
	v := &url.Values{}
	v.Set("id", strconv.FormatUint(id, 10))
	v.Set("term", strconv.FormatUint(term, 10))
	v.Set("index", strconv.FormatUint(index, 10))
	u.RawQuery = v.Encode()

	// Send HTTP request.
	resp, err := http.Get(u.String())
	if err != nil {
		return nil, err
	}

	// Parse returned error.
	if s := resp.Header.Get("X-Raft-Error"); s != "" {
		_ = resp.Body.Close()
		return nil, errors.New(s)
	}

	return resp.Body, nil
}
Example #16
0
func (c Client) New(params *stripe.PlanParams) (*stripe.Plan, error) {
	body := &url.Values{
		"id":       {params.ID},
		"name":     {params.Name},
		"amount":   {strconv.FormatUint(params.Amount, 10)},
		"currency": {string(params.Currency)},
		"interval": {string(params.Interval)},
	}

	if params.IntervalCount > 0 {
		body.Add("interval_count", strconv.FormatUint(params.IntervalCount, 10))
	}

	if params.TrialPeriod > 0 {
		body.Add("trial_period_days", strconv.FormatUint(params.TrialPeriod, 10))
	}

	if len(params.Statement) > 0 {
		body.Add("statement_descriptor", params.Statement)
	}
	params.AppendTo(body)

	plan := &stripe.Plan{}
	err := c.B.Call("POST", "/plans", c.Key, body, &params.Params, plan)

	return plan, err
}
Example #17
0
// RequestVote requests a vote for a candidate in a given term.
func (t *HTTPTransport) RequestVote(uri *url.URL, term, candidateID, lastLogIndex, lastLogTerm uint64) (uint64, error) {
	// Construct URL.
	u := *uri
	u.Path = path.Join(u.Path, "raft/vote")

	// Set URL parameters.
	v := &url.Values{}
	v.Set("term", strconv.FormatUint(term, 10))
	v.Set("candidateID", strconv.FormatUint(candidateID, 10))
	v.Set("lastLogIndex", strconv.FormatUint(lastLogIndex, 10))
	v.Set("lastLogTerm", strconv.FormatUint(lastLogTerm, 10))
	u.RawQuery = v.Encode()

	// Send HTTP request.
	resp, err := http.Get(u.String())
	if err != nil {
		return 0, err
	}
	_ = resp.Body.Close()

	// Parse returned term.
	newTermString := resp.Header.Get("X-Raft-Term")
	newTerm, err := strconv.ParseUint(newTermString, 10, 64)
	if err != nil {
		return 0, fmt.Errorf("invalid term: %q", newTermString)
	}

	// Parse returned error.
	if s := resp.Header.Get("X-Raft-Error"); s != "" {
		return newTerm, errors.New(s)
	}

	return newTerm, nil
}
Example #18
0
func (t *Trade) GetStatus() (*Status, error) {
	return t.postWithStatus(t.baseUrl+"tradestatus/", map[string]string{
		"sessionid": t.sessionId,
		"logpos":    strconv.FormatUint(uint64(t.LogPos), 10),
		"version":   strconv.FormatUint(uint64(t.Version), 10),
	})
}
Example #19
0
func (s *Transport) createSubStream(parentID uint64) (*stream, error) {
	referenceID := atomic.AddUint64(&s.referenceCounter, 1)
	headers := http.Header{}
	headers.Set("libchan-ref", strconv.FormatUint(referenceID, 10))
	if parentID > 0 {
		headers.Set("libchan-parent-ref", strconv.FormatUint(parentID, 10))
	}

	providedStream, err := s.provider.NewStream(headers)
	if err != nil {
		return nil, err
	}

	newStream := &stream{
		referenceID: referenceID,
		parentID:    parentID,
		stream:      providedStream,
		session:     s,
	}

	// TODO: Do not store reference
	s.streamC.L.Lock()
	s.streams[referenceID] = newStream
	s.streamC.L.Unlock()

	return newStream, nil

}
Example #20
0
func saveData(events []uint, timeNow uint) {
	filename := "ofcdata" + strconv.FormatUint(uint64(timeNow), 10) + ".txt"

	if _, err := os.Stat(filename); err != nil {
		if os.IsNotExist(err) {
			// file does not exist
		} else {
			// other error
			os.Remove(filename)
		}
	}

	f, err := os.OpenFile(filename, os.O_CREATE|os.O_RDWR, 0666)
	if err != nil {
		log.Fatal(err)
	}
	for u := uint(0); u < uint(len(events)); u++ {
		if events[u] > 0 {
			dataOut := "" + strconv.FormatUint(uint64(u), 10) + "     " + strconv.FormatUint(uint64(events[u]), 10) + "\n"
			fmt.Print(dataOut)
			io.WriteString(f, dataOut)
		}
	}
	f.Close()
}
Example #21
0
func (m *Memory) describe(buf *bytes.Buffer, tree map[string]*Node, depth int) {
	sorted := make([]string, 0, len(tree))
	for k, _ := range tree {
		sorted = append(sorted, k)
	}
	sort.Strings(sorted)
	for _, k := range sorted {
		pad := make([]rune, depth)
		for i, _ := range pad {
			pad[i] = ' '
		}
		n := tree[k]
		if n.Dir {
			buf.WriteString(string(pad))
			buf.WriteString(n.Key)
			buf.WriteString(":")
			buf.WriteString(strconv.FormatUint(n.Index, 10))
			buf.WriteString("\n")
			m.describe(buf, n.nodes, depth+1)
		} else {
			buf.WriteString(string(pad))
			buf.WriteString(n.Key)
			buf.WriteString(":")
			buf.WriteString(n.Value)
			buf.WriteString(":")
			buf.WriteString(strconv.FormatUint(n.Index, 10))
			buf.WriteString("\n")
		}
	}
}
Example #22
0
func (r *RequestBundle) updateDevicePusherLastUsed(device Device, pusher string) error {
	// start instrumentation
	if pusher != "gcm" && pusher != "websockets" {
		return InvalidPusherType
	}
	var was time.Time
	now := time.Now()
	if pusher == "gcm" {
		if device.Pushers != nil && device.Pushers.GCM != nil {
			was = device.Pushers.GCM.LastUsed
		}
	} else if pusher == "websockets" {
		if device.Pushers != nil && device.Pushers.WebSockets != nil {
			was = device.Pushers.WebSockets.LastUsed
		}
	}
	reply := r.Repo.client.Hset("devices:"+strconv.FormatUint(device.ID, 10), pusher+"_last_used", now.Format(time.RFC3339))
	// add repo call to instrumentation
	if reply.Err != nil {
		r.Log.Error(reply.Err.Error())
		return reply.Err
	}
	r.Audit("devices:"+strconv.FormatUint(device.ID, 10), pusher+"_last_used", was.Format(time.RFC3339), now.Format(time.RFC3339))
	// add repo call to instrumentation
	// stop instrumentation
	return nil
}
Example #23
0
// Coerce types (string,int,int64, float, []byte) into String type
func CoerceString(v interface{}) (string, error) {
	switch val := v.(type) {
	case string:
		if val == "null" || val == "NULL" {
			return "", nil
		}
		return val, nil
	case int:
		return strconv.Itoa(val), nil
	case int32:
		return strconv.FormatInt(int64(val), 10), nil
	case int64:
		return strconv.FormatInt(val, 10), nil
	case uint32:
		return strconv.FormatUint(uint64(val), 10), nil
	case uint64:
		return strconv.FormatUint(val, 10), nil
	case float32:
		return strconv.FormatFloat(float64(val), 'f', -1, 32), nil
	case float64:
		return strconv.FormatFloat(val, 'f', -1, 64), nil
	case []byte:
		if string(val) == "null" || string(val) == "NULL" {
			return "", nil
		}
		return string(val), nil
	case json.RawMessage:
		if string(val) == "null" || string(val) == "NULL" {
			return "", nil
		}
		return string(val), nil
	}
	return "", fmt.Errorf("Could not coerce to string: %v", v)
}
Example #24
0
File: ipvs.go Project: kobolog/gorb
func (s *Service) ToString() string {
	if s.VIP != "" {
		port := strconv.FormatUint(uint64(s.Port), 10)
		proto := ""
		switch s.Proto {
		case syscall.IPPROTO_TCP:
			proto = "tcp"
		case syscall.IPPROTO_UDP:
			proto = "udp"
		default:
			proto = "unknown"
		}
		return strings.Join([]string{s.VIP, proto, port}, ":")
	} else {
		//fwmark based service
		fwmark := strconv.FormatUint(uint64(s.FWMark), 10)
		proto := ""
		switch s.AF {
		case syscall.AF_INET:
			proto = "ipv4"
		case syscall.AF_INET6:
			proto = "ipv6"
		default:
			proto = "unknown"
		}
		return strings.Join([]string{"fwmark", proto, fwmark}, ":")
	}
}
Example #25
0
func (s *Transport) createSubStream(parentID uint64) (*stream, error) {
	referenceID := atomic.AddUint64(&s.referenceCounter, 1)
	headers := http.Header{}
	headers.Set("libchan-ref", strconv.FormatUint(referenceID, 10))
	if parentID > 0 {
		headers.Set("libchan-parent-ref", strconv.FormatUint(parentID, 10))
	}

	providedStream, err := s.provider.NewStream(headers)
	if err != nil {
		return nil, err
	}

	newStream := &stream{
		referenceID: referenceID,
		parentID:    parentID,
		stream:      providedStream,
		session:     s,
	}

	// TODO: hold reference to the newly created stream
	// for possible cleanup. This stream should not be put
	// in the streams maps which holds remotely created
	// streams and will can have reference id conflicts.

	return newStream, nil

}
Example #26
0
func TestSyncPodsDoesNothing(t *testing.T) {
	dm, fakeDocker := newTestDockerManager()
	container := api.Container{Name: "bar"}
	pod := &api.Pod{
		ObjectMeta: api.ObjectMeta{
			UID:       "12345678",
			Name:      "foo",
			Namespace: "new",
		},
		Spec: api.PodSpec{
			Containers: []api.Container{
				container,
			},
		},
	}
	fakeDocker.SetFakeRunningContainers([]*docker.Container{
		{
			ID:   "1234",
			Name: "/k8s_bar." + strconv.FormatUint(kubecontainer.HashContainer(&container), 16) + "_foo_new_12345678_0",
		},
		{
			ID:   "9876",
			Name: "/k8s_POD." + strconv.FormatUint(generatePodInfraContainerHash(pod), 16) + "_foo_new_12345678_0",
		}})

	runSyncPod(t, dm, fakeDocker, pod, nil, false)

	verifyCalls(t, fakeDocker, []string{
		// Check the pod infra container.
		"inspect_container",
	})
}
Example #27
0
func constructBlkioArgs(volumeMap []string, blkioLimit string) string {
	if blkioLimit == "" {
		return ""
	}
	if len(volumeMap) == 0 {
		volumeMap = append(volumeMap, "/var/lib/docker")
	}
	var dupRemovalMap = make(map[string]bool)
	for _, volumeMapping := range volumeMap {
		splitArr := strings.Split(volumeMapping, ":")
		f, _ := os.Open(splitArr[0])
		fi, _ := f.Stat()
		s := fi.Sys()
		switch s := s.(type) {
		default:
			fmt.Printf("unexpected type %T", s)
		case *syscall.Stat_t:
			majorMinorStr := strconv.FormatUint(Major(s.Dev), 10) + ":" + strconv.FormatUint(Minor(s.Dev), 10)
			dupRemovalMap[majorMinorStr] = true
		}
	}

	blkioArg := ""
	for key, _ := range dupRemovalMap {
		blkioArg = blkioArg + key + " " + blkioLimit + "\n"
	}
	return blkioArg
}
Example #28
0
// PushStringToStack push interface to stack and return resulted Stack
func PushStringToStack(data interface{}, stack Stack) Stack {
	switch reflect.TypeOf(data).Kind() {
	case reflect.Uint8:
		stack.Push(Token{Number, strconv.FormatUint(uint64(data.(uint8)), 10), Stack{}})
	case reflect.Uint16:
		stack.Push(Token{Number, strconv.FormatUint(uint64(data.(uint16)), 10), Stack{}})
	case reflect.Uint32:
		stack.Push(Token{Number, strconv.FormatUint(uint64(data.(uint32)), 10), Stack{}})
	case reflect.Uint64:
		stack.Push(Token{Number, strconv.FormatUint(data.(uint64), 10), Stack{}})
	case reflect.Uint:
		stack.Push(Token{Number, strconv.FormatUint(uint64(data.(uint)), 10), Stack{}})
	case reflect.Int8:
		stack.Push(Token{Number, strconv.FormatInt(int64(data.(int8)), 10), Stack{}})
	case reflect.Int16:
		stack.Push(Token{Number, strconv.FormatInt(int64(data.(int16)), 10), Stack{}})
	case reflect.Int32:
		stack.Push(Token{Number, strconv.FormatInt(int64(data.(int32)), 10), Stack{}})
	case reflect.Int64:
		stack.Push(Token{Number, strconv.FormatInt(data.(int64), 10), Stack{}})
	case reflect.Int:
		stack.Push(Token{Number, strconv.Itoa(data.(int)), Stack{}})
	case reflect.Float64:
		stack.Push(Token{Number, strconv.FormatFloat(data.(float64), 'f', 2, 64), Stack{}})
	case reflect.String:
		stack.Push(Token{Number, data.(string), Stack{}})
	case reflect.Bool:
		stack.Push(Token{Number, strconv.FormatBool(data.(bool)), Stack{}})
	}
	return stack
}
Example #29
0
// Status returns information about the ZFS filesystem. It returns a two dimensional array of information
// such as pool name, dataset name, disk usage, parent quota and compression used.
// Currently it return 'Zpool', 'Zpool Health', 'Parent Dataset', 'Space Used By Parent',
// 'Space Available', 'Parent Quota' and 'Compression'.
func (d *Driver) Status() [][2]string {
	parts := strings.Split(d.dataset.Name, "/")
	pool, err := zfs.GetZpool(parts[0])

	var poolName, poolHealth string
	if err == nil {
		poolName = pool.Name
		poolHealth = pool.Health
	} else {
		poolName = fmt.Sprintf("error while getting pool information %v", err)
		poolHealth = "not available"
	}

	quota := "no"
	if d.dataset.Quota != 0 {
		quota = strconv.FormatUint(d.dataset.Quota, 10)
	}

	return [][2]string{
		{"Zpool", poolName},
		{"Zpool Health", poolHealth},
		{"Parent Dataset", d.dataset.Name},
		{"Space Used By Parent", strconv.FormatUint(d.dataset.Used, 10)},
		{"Space Available", strconv.FormatUint(d.dataset.Avail, 10)},
		{"Parent Quota", quota},
		{"Compression", d.dataset.Compression},
	}
}
Example #30
0
func (f *StorageFingerprint) Fingerprint(cfg *config.Config, node *structs.Node) (bool, error) {

	// Initialize these to empty defaults
	node.Attributes["unique.storage.volume"] = ""
	node.Attributes["unique.storage.bytestotal"] = ""
	node.Attributes["unique.storage.bytesfree"] = ""
	if node.Resources == nil {
		node.Resources = &structs.Resources{}
	}

	// Guard against unset AllocDir
	storageDir := cfg.AllocDir
	if storageDir == "" {
		var err error
		storageDir, err = os.Getwd()
		if err != nil {
			return false, fmt.Errorf("unable to get CWD from filesystem: %s", err)
		}
	}

	volume, total, free, err := f.diskFree(storageDir)
	if err != nil {
		return false, fmt.Errorf("failed to determine disk space for %s: %v", storageDir, err)
	}

	node.Attributes["unique.storage.volume"] = volume
	node.Attributes["unique.storage.bytestotal"] = strconv.FormatUint(total, 10)
	node.Attributes["unique.storage.bytesfree"] = strconv.FormatUint(free, 10)

	node.Resources.DiskMB = int(free / bytesPerMegabyte)

	return true, nil
}