usage.go 2.3 KB
Newer Older
D
Davies Liu 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/*
 * JuiceFS, Copyright (C) 2020 Juicedata, Inc.
 *
 * This program is free software: you can use, redistribute, and/or modify
 * it under the terms of the GNU Affero General Public License, version 3
 * or later ("AGPL"), as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

D
Davies Liu 已提交
16
package usage
D
Davies Liu 已提交
17 18 19 20 21 22 23 24 25 26 27

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"math/rand"
	"net/http"
	"time"

	"github.com/juicedata/juicefs/pkg/meta"
D
Davies Liu 已提交
28
	"github.com/juicedata/juicefs/pkg/utils"
D
Davies Liu 已提交
29 30
)

D
Davies Liu 已提交
31 32 33
const reportUrl = "https://juicefs.com/report-usage"

var logger = utils.GetLogger("juicefs")
D
Davies Liu 已提交
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66

type usage struct {
	VolumeID   string `json:"volumeID"`
	SessionID  int64  `json:"sessionID"`
	UsedSpace  int64  `json:"usedBytes"`
	UsedInodes int64  `json:"usedInodes"`
	Version    string `json:"version"`
	Uptime     int64  `json:"uptime"`
}

func sendUsage(u usage) error {
	body, err := json.Marshal(u)
	if err != nil {
		return err
	}
	req, err := http.NewRequest("POST", reportUrl, bytes.NewReader(body))
	if err != nil {
		return err
	}
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return err
	}
	if resp.StatusCode != 200 {
		return fmt.Errorf("got %s", resp.Status)
	}
	_, err = ioutil.ReadAll(resp.Body)
	if err != nil {
		return err
	}
	return nil
}

D
Davies Liu 已提交
67
// ReportUsage will send anonymous usage data to juicefs.io to help the team
D
Davies Liu 已提交
68 69
// understand how the community is using it. You can use `--no-usage-report`
// to disable this.
D
Davies Liu 已提交
70
func ReportUsage(m meta.Meta, version string) {
D
Davies Liu 已提交
71 72 73 74 75 76
	ctx := meta.Background
	var u usage
	if format, err := m.Load(); err == nil {
		u.VolumeID = format.UUID
	}
	u.SessionID = int64(rand.Uint32())
D
Davies Liu 已提交
77
	u.Version = version
D
Davies Liu 已提交
78 79 80
	var start = time.Now()
	for {
		var totalSpace, availSpace, iused, iavail uint64
81
		_ = m.StatFS(ctx, &totalSpace, &availSpace, &iused, &iavail)
D
Davies Liu 已提交
82 83 84 85 86 87 88 89 90 91
		u.Uptime = int64(time.Since(start).Seconds())
		u.UsedSpace = int64(totalSpace - availSpace)
		u.UsedInodes = int64(iused)

		if err := sendUsage(u); err != nil {
			logger.Debugf("send usage: %s", err)
		}
		time.Sleep(time.Minute * 10)
	}
}