fix: import path should be github.com/ooni/probe-cli/v3 (#200)

See https://github.com/ooni/probe/issues/1335#issuecomment-771499511
This commit is contained in:
Simone Basso
2021-02-02 10:32:46 +01:00
committed by GitHub
parent faa9308b1e
commit b1ce300c8d
68 changed files with 86 additions and 85 deletions
+14
View File
@@ -0,0 +1,14 @@
package nettests
// Dash test implementation
type Dash struct {
}
// Run starts the test
func (d Dash) Run(ctl *Controller) error {
builder, err := ctl.Session.NewExperimentBuilder("dash")
if err != nil {
return err
}
return ctl.Run(builder, []string{""})
}
@@ -0,0 +1,16 @@
package nettests
// FacebookMessenger test implementation
type FacebookMessenger struct {
}
// Run starts the test
func (h FacebookMessenger) Run(ctl *Controller) error {
builder, err := ctl.Session.NewExperimentBuilder(
"facebook_messenger",
)
if err != nil {
return err
}
return ctl.Run(builder, []string{""})
}
+52
View File
@@ -0,0 +1,52 @@
package nettests
// Group is a group of nettests
type Group struct {
Label string
Nettests []Nettest
UnattendedOK bool
}
// All contains all the nettests that can be run by the user
var All = map[string]Group{
"websites": {
Label: "Websites",
Nettests: []Nettest{
WebConnectivity{},
},
UnattendedOK: true,
},
"performance": {
Label: "Performance",
Nettests: []Nettest{
Dash{},
NDT{},
},
},
"middlebox": {
Label: "Middleboxes",
Nettests: []Nettest{
HTTPInvalidRequestLine{},
HTTPHeaderFieldManipulation{},
},
UnattendedOK: true,
},
"im": {
Label: "Instant Messaging",
Nettests: []Nettest{
FacebookMessenger{},
Telegram{},
WhatsApp{},
},
UnattendedOK: true,
},
"circumvention": {
Label: "Circumvention Tools",
Nettests: []Nettest{
Psiphon{},
RiseupVPN{},
Tor{},
},
UnattendedOK: true,
},
}
@@ -0,0 +1,16 @@
package nettests
// HTTPHeaderFieldManipulation test implementation
type HTTPHeaderFieldManipulation struct {
}
// Run starts the test
func (h HTTPHeaderFieldManipulation) Run(ctl *Controller) error {
builder, err := ctl.Session.NewExperimentBuilder(
"http_header_field_manipulation",
)
if err != nil {
return err
}
return ctl.Run(builder, []string{""})
}
@@ -0,0 +1,16 @@
package nettests
// HTTPInvalidRequestLine test implementation
type HTTPInvalidRequestLine struct {
}
// Run starts the test
func (h HTTPInvalidRequestLine) Run(ctl *Controller) error {
builder, err := ctl.Session.NewExperimentBuilder(
"http_invalid_request_line",
)
if err != nil {
return err
}
return ctl.Run(builder, []string{""})
}
+15
View File
@@ -0,0 +1,15 @@
package nettests
// NDT test implementation. We use v7 of NDT since 2020-03-12.
type NDT struct {
}
// Run starts the test
func (n NDT) Run(ctl *Controller) error {
// Since 2020-03-18 probe-engine exports v7 as "ndt".
builder, err := ctl.Session.NewExperimentBuilder("ndt")
if err != nil {
return err
}
return ctl.Run(builder, []string{""})
}
+219
View File
@@ -0,0 +1,219 @@
package nettests
import (
"database/sql"
"fmt"
"time"
"github.com/apex/log"
"github.com/fatih/color"
"github.com/ooni/probe-cli/v3/cmd/ooniprobe/internal/database"
"github.com/ooni/probe-cli/v3/cmd/ooniprobe/internal/ooni"
"github.com/ooni/probe-cli/v3/cmd/ooniprobe/internal/output"
engine "github.com/ooni/probe-engine"
"github.com/ooni/probe-engine/model"
"github.com/pkg/errors"
)
// Nettest interface. Every Nettest should implement this.
type Nettest interface {
Run(*Controller) error
}
// NewController creates a nettest controller
func NewController(
nt Nettest, probe *ooni.Probe, res *database.Result, sess *engine.Session) *Controller {
return &Controller{
Probe: probe,
nt: nt,
res: res,
Session: sess,
}
}
// Controller is passed to the run method of every Nettest
// each nettest instance has one controller
type Controller struct {
Probe *ooni.Probe
Session *engine.Session
res *database.Result
nt Nettest
ntCount int
ntIndex int
ntStartTime time.Time // used to calculate the eta
msmts map[int64]*database.Measurement
inputIdxMap map[int64]int64 // Used to map mk idx to database id
// InputFiles optionally contains the names of the input
// files to read inputs from (only for nettests that take
// inputs, of course)
InputFiles []string
// Inputs contains inputs to be tested. These are specified
// using the command line using the --input flag.
Inputs []string
// numInputs is the total number of inputs
numInputs int
// curInputIdx is the current input index
curInputIdx int
}
// SetInputIdxMap is used to set the mapping of index into input. This mapping
// is used to reference, for example, a particular URL based on the index inside
// of the input list and the index of it in the database.
func (c *Controller) SetInputIdxMap(inputIdxMap map[int64]int64) error {
c.inputIdxMap = inputIdxMap
return nil
}
// SetNettestIndex is used to set the current nettest index and total nettest
// count to compute a different progress percentage.
func (c *Controller) SetNettestIndex(i, n int) {
c.ntCount = n
c.ntIndex = i
}
// Run runs the selected nettest using the related experiment
// with the specified inputs.
//
// This function will continue to run in most cases but will
// immediately halt if something's wrong with the file system.
func (c *Controller) Run(builder *engine.ExperimentBuilder, inputs []string) error {
// This will configure the controller as handler for the callbacks
// called by ooni/probe-engine/experiment.Experiment.
builder.SetCallbacks(model.ExperimentCallbacks(c))
c.numInputs = len(inputs)
exp := builder.NewExperiment()
defer func() {
c.res.DataUsageDown += exp.KibiBytesReceived()
c.res.DataUsageUp += exp.KibiBytesSent()
}()
c.msmts = make(map[int64]*database.Measurement)
// These values are shared by every measurement
var reportID sql.NullString
resultID := c.res.ID
log.Debug(color.RedString("status.queued"))
log.Debug(color.RedString("status.started"))
if c.Probe.Config().Sharing.UploadResults {
if err := exp.OpenReport(); err != nil {
log.Debugf(
"%s: %s", color.RedString("failure.report_create"), err.Error(),
)
} else {
log.Debugf(color.RedString("status.report_create"))
reportID = sql.NullString{String: exp.ReportID(), Valid: true}
}
}
c.ntStartTime = time.Now()
for idx, input := range inputs {
if c.Probe.IsTerminated() == true {
log.Debug("isTerminated == true, breaking the input loop")
break
}
c.curInputIdx = idx // allow for precise progress
idx64 := int64(idx)
log.Debug(color.RedString("status.measurement_start"))
var urlID sql.NullInt64
if c.inputIdxMap != nil {
urlID = sql.NullInt64{Int64: c.inputIdxMap[idx64], Valid: true}
}
msmt, err := database.CreateMeasurement(
c.Probe.DB(), reportID, exp.Name(), c.res.MeasurementDir, idx, resultID, urlID,
)
if err != nil {
return errors.Wrap(err, "failed to create measurement")
}
c.msmts[idx64] = msmt
if input != "" {
c.OnProgress(0, fmt.Sprintf("processing input: %s", input))
}
measurement, err := exp.Measure(input)
if err != nil {
log.WithError(err).Debug(color.RedString("failure.measurement"))
if err := c.msmts[idx64].Failed(c.Probe.DB(), err.Error()); err != nil {
return errors.Wrap(err, "failed to mark measurement as failed")
}
// Even with a failed measurement, we want to continue. We want to
// record and submit the information we have. Saving the information
// is useful for local inspection. Submitting it is useful to us to
// undertsand what went wrong (censorship? bug? anomaly?).
}
saveToDisk := true
if c.Probe.Config().Sharing.UploadResults {
// Implementation note: SubmitMeasurement will fail here if we did fail
// to open the report but we still want to continue. There will be a
// bit of a spew in the logs, perhaps, but stopping seems less efficient.
if err := exp.SubmitAndUpdateMeasurement(measurement); err != nil {
log.Debug(color.RedString("failure.measurement_submission"))
if err := c.msmts[idx64].UploadFailed(c.Probe.DB(), err.Error()); err != nil {
return errors.Wrap(err, "failed to mark upload as failed")
}
} else if err := c.msmts[idx64].UploadSucceeded(c.Probe.DB()); err != nil {
return errors.Wrap(err, "failed to mark upload as succeeded")
} else {
// Everything went OK, don't save to disk
saveToDisk = false
}
}
// We only save the measurement to disk if we failed to upload the measurement
if saveToDisk == true {
if err := exp.SaveMeasurement(measurement, msmt.MeasurementFilePath.String); err != nil {
return errors.Wrap(err, "failed to save measurement on disk")
}
}
if err := c.msmts[idx64].Done(c.Probe.DB()); err != nil {
return errors.Wrap(err, "failed to mark measurement as done")
}
// We're not sure whether it's enough to log the error or we should
// instead also mark the measurement as failed. Strictly speaking this
// is an inconsistency between the code that generate the measurement
// and the code that process the measurement. We do have some data
// but we're not gonna have a summary. To be reconsidered.
tk, err := exp.GetSummaryKeys(measurement)
if err != nil {
log.WithError(err).Error("failed to obtain testKeys")
continue
}
log.Debugf("Fetching: %d %v", idx, c.msmts[idx64])
if err := database.AddTestKeys(c.Probe.DB(), c.msmts[idx64], tk); err != nil {
return errors.Wrap(err, "failed to add test keys to summary")
}
}
log.Debugf("status.end")
return nil
}
// OnProgress should be called when a new progress event is available.
func (c *Controller) OnProgress(perc float64, msg string) {
log.Debugf("OnProgress: %f - %s", perc, msg)
var eta float64
eta = -1.0
if c.numInputs > 1 {
// make the percentage relative to the current input over all inputs
floor := (float64(c.curInputIdx) / float64(c.numInputs))
step := 1.0 / float64(c.numInputs)
perc = floor + perc*step
if c.curInputIdx > 0 {
eta = (time.Now().Sub(c.ntStartTime).Seconds() / float64(c.curInputIdx)) * float64(c.numInputs-c.curInputIdx)
}
}
if c.ntCount > 0 {
// make the percentage relative to the current nettest over all nettests
perc = float64(c.ntIndex)/float64(c.ntCount) + perc/float64(c.ntCount)
}
key := fmt.Sprintf("%T", c.nt)
output.Progress(key, perc, eta, msg)
}
@@ -0,0 +1,52 @@
package nettests
import (
"io/ioutil"
"path"
"testing"
"github.com/ooni/probe-cli/v3/cmd/ooniprobe/internal/database"
"github.com/ooni/probe-cli/v3/cmd/ooniprobe/internal/ooni"
"github.com/ooni/probe-cli/v3/cmd/ooniprobe/internal/utils/shutil"
)
func newOONIProbe(t *testing.T) *ooni.Probe {
homePath, err := ioutil.TempDir("", "ooniprobetests")
if err != nil {
t.Fatal(err)
}
configPath := path.Join(homePath, "config.json")
testingConfig := path.Join("..", "..", "testdata", "testing-config.json")
shutil.Copy(testingConfig, configPath, false)
probe := ooni.NewProbe(configPath, homePath)
swName := "ooniprobe-cli-tests"
swVersion := "3.0.0-alpha"
err = probe.Init(swName, swVersion)
if err != nil {
t.Fatal(err)
}
return probe
}
func TestCreateContext(t *testing.T) {
newOONIProbe(t)
}
func TestRun(t *testing.T) {
probe := newOONIProbe(t)
sess, err := probe.NewSession()
if err != nil {
t.Fatal(err)
}
network, err := database.CreateNetwork(probe.DB(), sess)
if err != nil {
t.Fatal(err)
}
res, err := database.CreateResult(probe.DB(), probe.Home(), "middlebox", network.ID)
if err != nil {
t.Fatal(err)
}
nt := HTTPInvalidRequestLine{}
ctl := NewController(nt, probe, res, sess)
nt.Run(ctl)
}
@@ -0,0 +1,16 @@
package nettests
// Psiphon test implementation
type Psiphon struct {
}
// Run starts the test
func (h Psiphon) Run(ctl *Controller) error {
builder, err := ctl.Session.NewExperimentBuilder(
"psiphon",
)
if err != nil {
return err
}
return ctl.Run(builder, []string{""})
}
@@ -0,0 +1,17 @@
package nettests
// RiseupVPN test implementation
type RiseupVPN struct {
}
// Run starts the test
func (h RiseupVPN) Run(ctl *Controller) error {
builder, err := ctl.Session.NewExperimentBuilder(
"riseupvpn",
)
if err != nil {
return err
}
return ctl.Run(builder, []string{""})
}
+82
View File
@@ -0,0 +1,82 @@
package nettests
import (
"github.com/apex/log"
"github.com/ooni/probe-cli/v3/cmd/ooniprobe/internal/database"
"github.com/ooni/probe-cli/v3/cmd/ooniprobe/internal/ooni"
"github.com/pkg/errors"
)
// RunGroupConfig contains the settings for running a nettest group.
type RunGroupConfig struct {
GroupName string
Probe *ooni.Probe
InputFiles []string
Inputs []string
}
// RunGroup runs a group of nettests according to the specified config.
func RunGroup(config RunGroupConfig) error {
if config.Probe.IsTerminated() == true {
log.Debugf("context is terminated, stopping runNettestGroup early")
return nil
}
sess, err := config.Probe.NewSession()
if err != nil {
log.WithError(err).Error("Failed to create a measurement session")
return err
}
defer sess.Close()
err = sess.MaybeLookupLocation()
if err != nil {
log.WithError(err).Error("Failed to lookup the location of the probe")
return err
}
network, err := database.CreateNetwork(config.Probe.DB(), sess)
if err != nil {
log.WithError(err).Error("Failed to create the network row")
return err
}
if err := sess.MaybeLookupBackends(); err != nil {
log.WithError(err).Warn("Failed to discover OONI backends")
return err
}
group, ok := All[config.GroupName]
if !ok {
log.Errorf("No test group named %s", config.GroupName)
return errors.New("invalid test group name")
}
log.Debugf("Running test group %s", group.Label)
result, err := database.CreateResult(
config.Probe.DB(), config.Probe.Home(), config.GroupName, network.ID)
if err != nil {
log.Errorf("DB result error: %s", err)
return err
}
config.Probe.ListenForSignals()
config.Probe.MaybeListenForStdinClosed()
for i, nt := range group.Nettests {
if config.Probe.IsTerminated() == true {
log.Debugf("context is terminated, stopping group.Nettests early")
break
}
log.Debugf("Running test %T", nt)
ctl := NewController(nt, config.Probe, result, sess)
ctl.InputFiles = config.InputFiles
ctl.Inputs = config.Inputs
ctl.SetNettestIndex(i, len(group.Nettests))
if err = nt.Run(ctl); err != nil {
log.WithError(err).Errorf("Failed to run %s", group.Label)
}
}
if err = result.Finished(config.Probe.DB()); err != nil {
return err
}
return nil
}
@@ -0,0 +1,16 @@
package nettests
// Telegram test implementation
type Telegram struct {
}
// Run starts the test
func (h Telegram) Run(ctl *Controller) error {
builder, err := ctl.Session.NewExperimentBuilder(
"telegram",
)
if err != nil {
return err
}
return ctl.Run(builder, []string{""})
}
+16
View File
@@ -0,0 +1,16 @@
package nettests
// Tor test implementation
type Tor struct {
}
// Run starts the test
func (h Tor) Run(ctl *Controller) error {
builder, err := ctl.Session.NewExperimentBuilder(
"tor",
)
if err != nil {
return err
}
return ctl.Run(builder, []string{""})
}
@@ -0,0 +1,61 @@
package nettests
import (
"context"
"github.com/apex/log"
"github.com/ooni/probe-cli/v3/cmd/ooniprobe/internal/database"
engine "github.com/ooni/probe-engine"
)
func lookupURLs(ctl *Controller, limit int64, categories []string) ([]string, map[int64]int64, error) {
inputloader := engine.NewInputLoader(engine.InputLoaderConfig{
InputPolicy: engine.InputOrQueryTestLists,
Session: ctl.Session,
SourceFiles: ctl.InputFiles,
StaticInputs: ctl.Inputs,
URLCategories: categories,
URLLimit: limit,
})
testlist, err := inputloader.Load(context.Background())
var urls []string
urlIDMap := make(map[int64]int64)
if err != nil {
return nil, nil, err
}
for idx, url := range testlist {
log.Debugf("Going over URL %d", idx)
urlID, err := database.CreateOrUpdateURL(
ctl.Probe.DB(), url.URL, url.CategoryCode, url.CountryCode,
)
if err != nil {
log.Error("failed to add to the URL table")
return nil, nil, err
}
log.Debugf("Mapped URL %s to idx %d and urlID %d", url.URL, idx, urlID)
urlIDMap[int64(idx)] = urlID
urls = append(urls, url.URL)
}
return urls, urlIDMap, nil
}
// WebConnectivity test implementation
type WebConnectivity struct {
}
// Run starts the test
func (n WebConnectivity) Run(ctl *Controller) error {
log.Debugf("Enabled category codes are the following %v", ctl.Probe.Config().Nettests.WebsitesEnabledCategoryCodes)
urls, urlIDMap, err := lookupURLs(ctl, ctl.Probe.Config().Nettests.WebsitesURLLimit, ctl.Probe.Config().Nettests.WebsitesEnabledCategoryCodes)
if err != nil {
return err
}
ctl.SetInputIdxMap(urlIDMap)
builder, err := ctl.Session.NewExperimentBuilder(
"web_connectivity",
)
if err != nil {
return err
}
return ctl.Run(builder, urls)
}
@@ -0,0 +1,16 @@
package nettests
// WhatsApp test implementation
type WhatsApp struct {
}
// Run starts the test
func (h WhatsApp) Run(ctl *Controller) error {
builder, err := ctl.Session.NewExperimentBuilder(
"whatsapp",
)
if err != nil {
return err
}
return ctl.Run(builder, []string{""})
}