<commit_before>package flickr

import (
	"testing"
)

func TestNewUploadParams(t *testing.T) {
	params := NewUploadParams()
	Expect(t, params.Title, "")
	Expect(t, params.Description, "")
	Expect(t, len(params.Tags), 0)
	Expect(t, params.IsPublic, false)
	Expect(t, params.IsFamily, false)
	Expect(t, params.IsFriend, false)
	Expect(t, params.ContentType, 1)
	Expect(t, params.Hidden, 2)
	Expect(t, params.SafetyLevel, 1)
}

func TestFillArgsWithParams(t *testing.T) {
	client := GetTestClient()
	params := NewUploadParams()
	fillArgsWithParams(client, params)

	Expect(t, client.Args.Get("title"), "")
	Expect(t, client.Args.Get("description"), "")
	Expect(t, client.Args.Get("tags"), "")
	Expect(t, client.Args.Get("is_public"), "0")
	Expect(t, client.Args.Get("is_friend"), "0")
	Expect(t, client.Args.Get("is_family"), "0")
	Expect(t, client.Args.Get("content_type"), "1")
	Expect(t, client.Args.Get("hidden"), "2")
	Expect(t, client.Args.Get("safety_level"), "1")

	params.Title = "foo"
	params.Description = "a long description"
	params.Tags = []string{"a", "b", "c"}
	params.IsPublic = true
	params.IsFamily = true
	params.IsFriend = true
	params.ContentType = 100
	params.Hidden = 100
	params.SafetyLevel = 100
	client.ClearArgs()
	fillArgsWithParams(client, params)
	Expect(t, client.Args.Get("title"), "foo")
	Expect(t, client.Args.Get("description"), "a long description")
	Expect(t, client.Args.Get("tags"), "a b c")
	Expect(t, client.Args.Get("is_public"), "1")
	Expect(t, client.Args.Get("is_friend"), "1")
	Expect(t, client.Args.Get("is_family"), "1")
	Expect(t, client.Args.Get("content_type"), "")
	Expect(t, client.Args.Get("hidden"), "")
	Expect(t, client.Args.Get("safety_level"), "")
}

func TestGetUploadBody(t *testing.T) {
	client := GetTestClient()

}
<commit_msg>more tests<commit_after>package flickr

import (
	"bytes"
	"io"
	"io/ioutil"
	"os"
	"strings"
	"testing"

	flickErr "github.com/masci/flickr.go/flickr/error"
)

func TestNewUploadParams(t *testing.T) {
	params := NewUploadParams()
	Expect(t, params.Title, "")
	Expect(t, params.Description, "")
	Expect(t, len(params.Tags), 0)
	Expect(t, params.IsPublic, false)
	Expect(t, params.IsFamily, false)
	Expect(t, params.IsFriend, false)
	Expect(t, params.ContentType, 1)
	Expect(t, params.Hidden, 2)
	Expect(t, params.SafetyLevel, 1)
}

func TestFillArgsWithParams(t *testing.T) {
	client := GetTestClient()
	params := NewUploadParams()
	fillArgsWithParams(client, params)

	Expect(t, client.Args.Get("title"), "")
	Expect(t, client.Args.Get("description"), "")
	Expect(t, client.Args.Get("tags"), "")
	Expect(t, client.Args.Get("is_public"), "0")
	Expect(t, client.Args.Get("is_friend"), "0")
	Expect(t, client.Args.Get("is_family"), "0")
	Expect(t, client.Args.Get("content_type"), "1")
	Expect(t, client.Args.Get("hidden"), "2")
	Expect(t, client.Args.Get("safety_level"), "1")

	params.Title = "foo"
	params.Description = "a long description"
	params.Tags = []string{"a", "b", "c"}
	params.IsPublic = true
	params.IsFamily = true
	params.IsFriend = true
	params.ContentType = 100
	params.Hidden = 100
	params.SafetyLevel = 100
	client.ClearArgs()
	fillArgsWithParams(client, params)
	Expect(t, client.Args.Get("title"), "foo")
	Expect(t, client.Args.Get("description"), "a long description")
	Expect(t, client.Args.Get("tags"), "a b c")
	Expect(t, client.Args.Get("is_public"), "1")
	Expect(t, client.Args.Get("is_friend"), "1")
	Expect(t, client.Args.Get("is_family"), "1")
	Expect(t, client.Args.Get("content_type"), "")
	Expect(t, client.Args.Get("hidden"), "")
	Expect(t, client.Args.Get("safety_level"), "")
}

func TestGetUploadBody(t *testing.T) {
	client := GetTestClient()
	photo := bytes.NewBufferString("foo")
	body, ctype, err := getUploadBody(client, photo, "fnam")

	Expect(t, err, nil)
	Expect(t, strings.Contains(ctype, "multipart/form-data; boundary="), true)
	Expect(t, strings.Contains(body.String(), "foo"), true)
}

func TestUploadPhoto(t *testing.T) {
	fclient := GetTestClient()
	server, client := FlickrMock(200, `<?xml version="1.0" encoding="utf-8" ?><rsp stat="ok"></rsp>`, "")
	defer server.Close()
	fclient.HTTPClient = client
	params := NewUploadParams()

	resp, err := UploadPhoto(fclient, "", params)
	Expect(t, resp == nil, true) // comparing nil interfaces would fail
	_, ok := err.(*os.PathError)
	Expect(t, ok, true)

	fooFile, err := ioutil.TempFile("", "flickr.go")
	defer fooFile.Close()
	Expect(t, err, nil)
	resp, err = UploadPhoto(fclient, fooFile.Name(), params)
	Expect(t, resp.HasErrors(), false)
}

func TestUploadPhotoKo(t *testing.T) {
	fclient := GetTestClient()
	server, client := FlickrMock(200, `<?xml version="1.0" encoding="utf-8" ?><rsp stat="fail"></rsp>`, "")
	defer server.Close()
	fclient.HTTPClient = client

	fooFile, err := ioutil.TempFile("", "flickr.go")
	defer fooFile.Close()
	resp, err := UploadPhoto(fclient, fooFile.Name(), nil)
	_, ok := err.(*flickErr.Error)
	Expect(t, ok, true)
	Expect(t, resp.HasErrors(), true)
}

func TestUploadPhotoPOSTKo(t *testing.T) {
	fclient := GetTestClient()
	server, client := FlickrMock(200, "a_non_rest_error", "")
	defer server.Close()
	fclient.HTTPClient = client

	fooFile, err := ioutil.TempFile("", "flickr.go")
	defer fooFile.Close()
	resp, err := UploadPhoto(fclient, fooFile.Name(), nil)
	Expect(t, err, io.EOF)
	Expect(t, resp == nil, true)
}
<|endoftext|>


<commit_before>package page

import (
	html "svc-wiki-showepisodes/lib/htmlplus"
	"fmt"
)

func init() {
	addSeriesOverview(process2S2EFLAm,
		html.HeaderRow{"Season", "Season", "Episodes", "Episodes", "Originally aired", "Originally aired", "Nielsen ratings", "Nielsen ratings"},
		html.HeaderRow{"Season", "Season", "Episodes", "Episodes", "First aired" /**/, "Last aired" /* */, "Rank" /* . . .*/, "Average viewers|||(in millions)"})
}

func process2S2EFLAm(pTable *html.Table) ([]*season, error) {
	fmt.Println("2S2EFLAm")
	return populateFromSOT(pTable,newSOTrowProcessors().
		add(newSimpleSOTrowProcessor(sSOTcellIgnored, sSTOcellSeasonNumber, sSTOcellEpisodeCount.colspan(2), sSTOcellFirstAirDate, sSTOcellLastAirDate, sSOTcellIgnored, sSOTcellIgnored)))
}

<commit_msg>Updated File...<commit_after>package page

import (
	html "svc-wiki-showepisodes/lib/htmlplus"
)

func init() {
	addSeriesOverview(process2S2EFLRAm, "2S2EFLRAm",
		html.HeaderRow{"Season", "Season", "Episodes", "Episodes", "Originally aired", "Originally aired", "Nielsen ratings", "Nielsen ratings"},
		html.HeaderRow{"Season", "Season", "Episodes", "Episodes", "First aired" /**/, "Last aired" /* */, "Rank" /* . . .*/, "Average viewers|||(in millions)"})
}

func process2S2EFLRAm(pTable *html.Table) ([]*season, error) {
	return populateFromSOT(pTable, newSOTrowProcessors().
			add(newSimpleSOTrowProcessor(sSOTcellIgnored, sSTOcellSeasonNumber, sSTOcellEpisodeCount.colspan(2), sSTOcellFirstAirDate, sSTOcellLastAirDate, sSOTcellIgnored, sSOTcellIgnored)))
}

<|endoftext|>


<commit_before>// Package sqlite_rw reads and updates sqlite databases using consumers
// from the github.com/keep94/goconsume package.
package sqlite_rw

import (
  "errors"
  "fmt"
  "hash/fnv"

  "github.com/keep94/goconsume"
  "github.com/keep94/gosqlite/sqlite"
)

const (
  LastRowIdSQL = "select last_insert_rowid()"
)

// RowForReading reads a database row into its business object.
// RowForReading instances can optionally implement EtagSetter if
// its business object has an etag.
type RowForReading interface {

  // ValuePtr returns the pointer to this instance's business object.
  ValuePtr() interface{}

  // Ptrs returns the pointers to be passed to Scan to read the database row.
  Ptrs() []interface{}

  // Unmarshall updates this instance's business object with the values
  // stored in the pointers that Ptrs returned.
  Unmarshall() error
}

// EtagSetter sets the etag on its business objecct
type EtagSetter interface {

  // Values returns column values from database with Id column last
  Values() []interface{}

  // SetEtag sets the etag on this instance's business object
  SetEtag(etag uint64)
}

// RowForWriting writes its business object to a database row.
type RowForWriting interface {

  // Values returns the column values for the database with Id column last.
  Values() []interface{}

  // Marshall updates the values that Values() returns using this instance's
  // business object
  Marshall() error
}

// SimpleRow provides empty Marshall / Unmarshall for implementations of
// RowForReading and RowForWriting
type SimpleRow struct {
}

func (s SimpleRow) Marshall() error {
  return nil
}

func (s SimpleRow) Unmarshall() error {
  return nil
}

// ReadSingle executes sql and reads a single row into row's business object.
// ReadSingle returns noSuchRow if no rows were found. params provides the
// values for the question mark (?) place holders in sql.
func ReadSingle(
    conn *sqlite.Conn,
    row RowForReading,
    noSuchRow error,
    sql string,
    params ...interface{}) error {
  stmt, err := conn.Prepare(sql)
  if err != nil {
    return err
  }
  defer stmt.Finalize()
  if err = stmt.Exec(params...); err != nil {
    return err
  }
  return FirstOnly(row, stmt, noSuchRow)
}

// FirstOnly reads one row from stmt into row's business object. FirstOnly
// returns noSuchRow if stmt has no rows.
func FirstOnly(
    row RowForReading,
    stmt *sqlite.Stmt,
    noSuchRow error) error {
  ptrs := row.Ptrs()
  if stmt.Next() {
    if err := readRow(row, stmt, ptrs); err != nil {
      return err
    }
    return nil
  }
  return noSuchRow
}

// ReadRows reads many rows from stmt. For each row read, ReadRows adds
// row's business object to consumer.
func ReadRows(
    row RowForReading,
    stmt *sqlite.Stmt,
    consumer goconsume.Consumer) error {
  ptrs := row.Ptrs()
  for stmt.Next() && consumer.CanConsume() {
    if err := readRow(row, stmt, ptrs); err != nil {
      return err
    }
    consumer.Consume(row.ValuePtr())
  }
  return nil
}

// ReadMultiple executes sql and reads multiple rows. Each time a row
// is read, row's business object is added to consumer. params provides
// values for question mark (?) place holders in sql.
func ReadMultiple(
    conn *sqlite.Conn,
    row RowForReading,
    consumer goconsume.Consumer,
    sql string,
    params ...interface{}) error {
  stmt, err := conn.Prepare(sql)
  if err != nil {
    return err
  }
  defer stmt.Finalize()
  if err = stmt.Exec(params...); err != nil {
    return err
  }
  return ReadRows(row, stmt, consumer)
}

// AddRow adds row's business object as a new row in database.
// The row being added must have auto increment id field. AddRow stores the
// id of the new row at rowId.
func AddRow(
    conn *sqlite.Conn,
    row RowForWriting,
    rowId *int64,
    sql string) error {
  values, err := InsertValues(row)
  if err != nil {
    return err
  }
  if err = conn.Exec(sql, values...); err != nil {
    return err
  }
  *rowId, err = LastRowId(conn)
  return err
}

// UpdateRow updates a row's business object in the database.
func UpdateRow(
    conn *sqlite.Conn,
    row RowForWriting,
    sql string) error {
  values, err := UpdateValues(row)
  if err != nil {
    return err
  }
  return conn.Exec(sql, values...)
}

// LastRowId fetches the id of last inserted row.
func LastRowId(conn *sqlite.Conn) (id int64, err error) {
  stmt, err := conn.Prepare(LastRowIdSQL)
  if err != nil {
    return
  }
  defer stmt.Finalize()
  return LastRowIdFromStmt(stmt)
}

// LastRowIdFromStmt fetches the last inserted row id. stmt must be
// created from LastRowIdSQL.
func LastRowIdFromStmt(stmt *sqlite.Stmt) (id int64, err error) {
  if err = stmt.Exec(); err != nil {
    return
  }
  if !stmt.Next() {
    err = errors.New("sqlite_db2: Could not fetch inserted row id")
    return
  }
  err = stmt.Scan(&id)
  return
}

// UpdateValues returns the values of the SQL columns to update row
func UpdateValues(row RowForWriting) (
    values []interface{}, err error) {
  if err = row.Marshall(); err != nil {
    return
  }
  return row.Values(), nil
}

// InsertValues returns the values of the SQL columns to add a new row
func InsertValues(row RowForWriting) (
    values []interface{}, err error) {
  var valuesForUpdate []interface{}
  if valuesForUpdate, err = UpdateValues(row); err != nil {
    return
  }
  return valuesForUpdate[:len(valuesForUpdate) - 1], nil
}

func doEtag(row EtagSetter) error {
  etag, err := computeEtag(row.Values())
  if err != nil {
    return err
  }
  row.SetEtag(etag)
  return nil
}

func computeEtag(values interface{}) (uint64, error) {
  h := fnv.New64a()
  s := fmt.Sprintf("%v", values)
  _, err := h.Write(([]byte)(s))
  if err != nil {
    return 0, err
  }
  return h.Sum64(), nil
}

func readRow(
    row RowForReading, stmt *sqlite.Stmt, ptrs []interface{}) error {
  if err := stmt.Scan(ptrs...); err != nil {
    return err
  }
  etagSetter, isEtagSetter := row.(EtagSetter)
  if isEtagSetter {
    if err := doEtag(etagSetter); err != nil {
      return err
    }
  }
  if err := row.Unmarshall(); err != nil {
    return err
  }
  return nil
}
<commit_msg>Remove LastRowId artifiacts from db/sqlite_rw.<commit_after>// Package sqlite_rw reads and updates sqlite databases using consumers
// from the github.com/keep94/goconsume package.
package sqlite_rw

import (
  "fmt"
  "hash/fnv"

  "github.com/keep94/appcommon/db/sqlite_db"
  "github.com/keep94/goconsume"
  "github.com/keep94/gosqlite/sqlite"
)

// RowForReading reads a database row into its business object.
// RowForReading instances can optionally implement EtagSetter if
// its business object has an etag.
type RowForReading interface {

  // ValuePtr returns the pointer to this instance's business object.
  ValuePtr() interface{}

  // Ptrs returns the pointers to be passed to Scan to read the database row.
  Ptrs() []interface{}

  // Unmarshall updates this instance's business object with the values
  // stored in the pointers that Ptrs returned.
  Unmarshall() error
}

// EtagSetter sets the etag on its business objecct
type EtagSetter interface {

  // Values returns column values from database with Id column last
  Values() []interface{}

  // SetEtag sets the etag on this instance's business object
  SetEtag(etag uint64)
}

// RowForWriting writes its business object to a database row.
type RowForWriting interface {

  // Values returns the column values for the database with Id column last.
  Values() []interface{}

  // Marshall updates the values that Values() returns using this instance's
  // business object
  Marshall() error
}

// SimpleRow provides empty Marshall / Unmarshall for implementations of
// RowForReading and RowForWriting
type SimpleRow struct {
}

func (s SimpleRow) Marshall() error {
  return nil
}

func (s SimpleRow) Unmarshall() error {
  return nil
}

// ReadSingle executes sql and reads a single row into row's business object.
// ReadSingle returns noSuchRow if no rows were found. params provides the
// values for the question mark (?) place holders in sql.
func ReadSingle(
    conn *sqlite.Conn,
    row RowForReading,
    noSuchRow error,
    sql string,
    params ...interface{}) error {
  stmt, err := conn.Prepare(sql)
  if err != nil {
    return err
  }
  defer stmt.Finalize()
  if err = stmt.Exec(params...); err != nil {
    return err
  }
  return FirstOnly(row, stmt, noSuchRow)
}

// FirstOnly reads one row from stmt into row's business object. FirstOnly
// returns noSuchRow if stmt has no rows.
func FirstOnly(
    row RowForReading,
    stmt *sqlite.Stmt,
    noSuchRow error) error {
  ptrs := row.Ptrs()
  if stmt.Next() {
    if err := readRow(row, stmt, ptrs); err != nil {
      return err
    }
    return nil
  }
  return noSuchRow
}

// ReadRows reads many rows from stmt. For each row read, ReadRows adds
// row's business object to consumer.
func ReadRows(
    row RowForReading,
    stmt *sqlite.Stmt,
    consumer goconsume.Consumer) error {
  ptrs := row.Ptrs()
  for stmt.Next() && consumer.CanConsume() {
    if err := readRow(row, stmt, ptrs); err != nil {
      return err
    }
    consumer.Consume(row.ValuePtr())
  }
  return nil
}

// ReadMultiple executes sql and reads multiple rows. Each time a row
// is read, row's business object is added to consumer. params provides
// values for question mark (?) place holders in sql.
func ReadMultiple(
    conn *sqlite.Conn,
    row RowForReading,
    consumer goconsume.Consumer,
    sql string,
    params ...interface{}) error {
  stmt, err := conn.Prepare(sql)
  if err != nil {
    return err
  }
  defer stmt.Finalize()
  if err = stmt.Exec(params...); err != nil {
    return err
  }
  return ReadRows(row, stmt, consumer)
}

// AddRow adds row's business object as a new row in database.
// The row being added must have auto increment id field. AddRow stores the
// id of the new row at rowId.
func AddRow(
    conn *sqlite.Conn,
    row RowForWriting,
    rowId *int64,
    sql string) error {
  values, err := InsertValues(row)
  if err != nil {
    return err
  }
  if err = conn.Exec(sql, values...); err != nil {
    return err
  }
  *rowId, err = sqlite_db.LastRowId(conn)
  return err
}

// UpdateRow updates a row's business object in the database.
func UpdateRow(
    conn *sqlite.Conn,
    row RowForWriting,
    sql string) error {
  values, err := UpdateValues(row)
  if err != nil {
    return err
  }
  return conn.Exec(sql, values...)
}

// UpdateValues returns the values of the SQL columns to update row
func UpdateValues(row RowForWriting) (
    values []interface{}, err error) {
  if err = row.Marshall(); err != nil {
    return
  }
  return row.Values(), nil
}

// InsertValues returns the values of the SQL columns to add a new row
func InsertValues(row RowForWriting) (
    values []interface{}, err error) {
  var valuesForUpdate []interface{}
  if valuesForUpdate, err = UpdateValues(row); err != nil {
    return
  }
  return valuesForUpdate[:len(valuesForUpdate) - 1], nil
}

func doEtag(row EtagSetter) error {
  etag, err := computeEtag(row.Values())
  if err != nil {
    return err
  }
  row.SetEtag(etag)
  return nil
}

func computeEtag(values interface{}) (uint64, error) {
  h := fnv.New64a()
  s := fmt.Sprintf("%v", values)
  _, err := h.Write(([]byte)(s))
  if err != nil {
    return 0, err
  }
  return h.Sum64(), nil
}

func readRow(
    row RowForReading, stmt *sqlite.Stmt, ptrs []interface{}) error {
  if err := stmt.Scan(ptrs...); err != nil {
    return err
  }
  etagSetter, isEtagSetter := row.(EtagSetter)
  if isEtagSetter {
    if err := doEtag(etagSetter); err != nil {
      return err
    }
  }
  if err := row.Unmarshall(); err != nil {
    return err
  }
  return nil
}
<|endoftext|>


<commit_before>package common

import (
	"testing"

	"github.com/samonzeweb/godb"
)

func RawSQLTests(db *godb.DB, t *testing.T) {
	// Enable logger if needed
	//db.SetLogger(log.New(os.Stderr, "", 0))

	// Fixtures
	booksToInsert := setAllBooks[:]
	err := db.BulkInsert(&booksToInsert).Do()
	if err != nil {
		t.Fatal(err)
	}
	if getReturningBuilder(db) != nil {
		for _, book := range booksToInsert {
			if book.Id == 0 {
				t.Fatalf("Id was not set for the book %v", book)
			}
		}
	}

	// Test & assertions
	books := make([]Book, 0, 0)
	err = db.RawSQL("select * from books where author = ?", authorAssimov).Do(&books)
	if err != nil {
		t.Fatal(err)
	}

	if len(books) != len(setFoundation) {
		t.Fatalf("Wrong books count : %d", len(books))
	}
}
<commit_msg>Added a complex raw query test using SQLBuilder<commit_after>package common

import (
	"testing"

	"github.com/samonzeweb/godb"
)

func RawSQLTests(db *godb.DB, t *testing.T) {
	// Enable logger if needed
	//db.SetLogger(log.New(os.Stderr, "", 0))

	// Fixtures
	booksToInsert := setAllBooks[:]
	err := db.BulkInsert(&booksToInsert).Do()
	if err != nil {
		t.Fatal(err)
	}
	if getReturningBuilder(db) != nil {
		for _, book := range booksToInsert {
			if book.Id == 0 {
				t.Fatalf("Id was not set for the book %v", book)
			}
		}
	}

	// Tests & assertions
	books := make([]Book, 0, 0)
	err = db.RawSQL("select * from books where author = ?", authorAssimov).Do(&books)
	if err != nil {
		t.Fatal(err)
	}

	if len(books) != len(setFoundation) {
		t.Fatalf("Wrong books count : %d", len(books))
	}

	subQuery := godb.NewSQLBuffer(0, 0). // of course size can be zero
						Write("select author ").
						Write("from books ").
						WriteCondition(godb.Q("where title = ?", bookFoundation.Title))

	queryBuffer := godb.NewSQLBuffer(64, 0). // approximate size
							Write("select * ").
							Write("from books ").
							Write("where author in (").
							Append(subQuery).
							Write(")")

	if queryBuffer.Err() != nil {
		t.Fatalf("Raw query building produce an error : %v", queryBuffer.Err())
	}

	err = db.RawSQL(queryBuffer.SQL(), queryBuffer.Arguments()...).Do(&books)
	if err != nil {
		t.Fatal(err)
	}

	if len(books) != len(setFoundation) {
		t.Fatalf("Wrong books count : %d", len(books))
	}
}
<|endoftext|>


<commit_before>package tests_test

import (
	"fmt"

	. "github.com/onsi/ginkgo"
	"github.com/onsi/ginkgo/extensions/table"
	. "github.com/onsi/gomega"

	v1 "kubevirt.io/client-go/api/v1"
	"kubevirt.io/client-go/kubecli"
	virtconfig "kubevirt.io/kubevirt/pkg/virt-config"
	"kubevirt.io/kubevirt/tests"
	"kubevirt.io/kubevirt/tests/framework/checks"
	"kubevirt.io/kubevirt/tests/libvmi"
	"kubevirt.io/kubevirt/tests/util"
)

var _ = Describe("[sig-compute]NonRoot feature", func() {

	var virtClient kubecli.KubevirtClient
	var err error

	BeforeEach(func() {
		virtClient, err = kubecli.GetKubevirtClient()
		util.PanicOnError(err)

		if !checks.HasFeature(virtconfig.NonRoot) {
			Skip("Test specific to NonRoot featureGate that is not enabled")
		}

		tests.BeforeTestCleanup()
	})

	sriovVM := func() *v1.VirtualMachineInstance {
		name := "test"
		withVmiOptions := []libvmi.Option{
			libvmi.WithInterface(libvmi.InterfaceDeviceWithSRIOVBinding(name)),
			libvmi.WithNetwork(libvmi.MultusNetwork(name)),
		}

		return libvmi.NewSriovFedora(withVmiOptions...)
	}

	virtioFsVM := func() *v1.VirtualMachineInstance {
		name := "test"
		return tests.NewRandomVMIWithPVCFS(name)
	}

	table.DescribeTable("should cause fail in creating of vmi with", func(createVMI func() *v1.VirtualMachineInstance, neededFeature, feature string) {
		if neededFeature != "" && !checks.HasFeature(neededFeature) {
			Skip(fmt.Sprintf("Missing %s, enable %s featureGate.", neededFeature, neededFeature))
		}

		vmi := createVMI()
		_, err = virtClient.VirtualMachineInstance(util.NamespaceTestDefault).Create(vmi)
		Expect(err).To(HaveOccurred())
		Expect(err.Error()).To(And(ContainSubstring(feature), ContainSubstring("nonroot")))

	},
		table.Entry("SRIOV", sriovVM, "", "SRIOV"),
		table.Entry("VirtioFS", virtioFsVM, virtconfig.VirtIOFSGate, "VirtioFS"),
	)
})
<commit_msg>Add testid's for NonRoot virt-launcher Tests<commit_after>package tests_test

import (
	"fmt"

	. "github.com/onsi/ginkgo"
	"github.com/onsi/ginkgo/extensions/table"
	. "github.com/onsi/gomega"

	v1 "kubevirt.io/client-go/api/v1"
	"kubevirt.io/client-go/kubecli"
	virtconfig "kubevirt.io/kubevirt/pkg/virt-config"
	"kubevirt.io/kubevirt/tests"
	"kubevirt.io/kubevirt/tests/framework/checks"
	"kubevirt.io/kubevirt/tests/libvmi"
	"kubevirt.io/kubevirt/tests/util"
)

var _ = Describe("[sig-compute]NonRoot feature", func() {

	var virtClient kubecli.KubevirtClient
	var err error

	BeforeEach(func() {
		virtClient, err = kubecli.GetKubevirtClient()
		util.PanicOnError(err)

		if !checks.HasFeature(virtconfig.NonRoot) {
			Skip("Test specific to NonRoot featureGate that is not enabled")
		}

		tests.BeforeTestCleanup()
	})

	sriovVM := func() *v1.VirtualMachineInstance {
		name := "test"
		withVmiOptions := []libvmi.Option{
			libvmi.WithInterface(libvmi.InterfaceDeviceWithSRIOVBinding(name)),
			libvmi.WithNetwork(libvmi.MultusNetwork(name)),
		}

		return libvmi.NewSriovFedora(withVmiOptions...)
	}

	virtioFsVM := func() *v1.VirtualMachineInstance {
		name := "test"
		return tests.NewRandomVMIWithPVCFS(name)
	}

	table.DescribeTable("should cause fail in creating of vmi with", func(createVMI func() *v1.VirtualMachineInstance, neededFeature, feature string) {
		if neededFeature != "" && !checks.HasFeature(neededFeature) {
			Skip(fmt.Sprintf("Missing %s, enable %s featureGate.", neededFeature, neededFeature))
		}

		vmi := createVMI()
		_, err = virtClient.VirtualMachineInstance(util.NamespaceTestDefault).Create(vmi)
		Expect(err).To(HaveOccurred())
		Expect(err.Error()).To(And(ContainSubstring(feature), ContainSubstring("nonroot")))

	},
		table.Entry("[test_id:7126]SRIOV", sriovVM, "", "SRIOV"),
		table.Entry("[test_id:7127]VirtioFS", virtioFsVM, virtconfig.VirtIOFSGate, "VirtioFS"),
	)
})
<|endoftext|>


<commit_before>package db_models

import (
	"time"

	"github.com/go-xorm/xorm"
)

const ParameterValueTypeFqdn = "FQDN"
const ParameterValueTypeUri = "URI"
const ParameterValueTypeE164 = "E_164"
const ParameterValueTypeTrafficProtocol = "TRAFFIC_PROTOCOL"
const ParameterValueTypeAlias = "ALIAS"
const ParameterValueTypeTargetProtocol = "TARGET_PROTOCOL"

type ParameterValue struct {
	Id                int64     `xorm:"'id'"`
	CustomerId        int       `xorm:"'customer_id'"`
	IdentifierId      int64     `xorm:"'identifier_id'"`
	MitigationScopeId int64     `xorm:"'mitigation_scope_id'"`
	Type              string    `xorm:"'type' enum('FQDN','URI','E_164','TRAFFIC_PROTOCOL','ALIAS','TARGET_PROTOCOL') not null"`
	StringValue       string    `xorm:"'string_value'"`
	IntValue          int       `xorm:"'int_value'"`
	Created           time.Time `xorm:"created"`
	Updated           time.Time `xorm:"updated"`
}

func contains(stringList []string, target string) bool {
	for _, s := range stringList {
		if s == target {
			return true
		}
	}
	return false
}

const ParameterValueFieldTrafficProtocol = "TrafficProtocol"

var valueTypesString = []string{ParameterValueTypeFqdn, ParameterValueTypeUri, ParameterValueTypeE164}
var valueTypesInt = []string{ParameterValueFieldTrafficProtocol}

func CreateParameterValue(value interface{}, typeString string, identifierId int64) *ParameterValue {
	parameterValue := &ParameterValue{Type: typeString, IdentifierId: identifierId}
	if contains(valueTypesString, typeString) {
		parameterValue.StringValue = value.(string)
	} else if contains(valueTypesInt, typeString) {
		parameterValue.IntValue = value.(int)
	} else { // invalid input
		return nil
	}

	return parameterValue
}

func CreateFqdnParam(fqdn string) (param *ParameterValue) {
	param = new(ParameterValue)
	param.Type = ParameterValueTypeFqdn
	param.StringValue = fqdn
	return
}

func GetFqdnValue(param *ParameterValue) string {
	return param.StringValue
}

func CreateUriParam(uri string) (param *ParameterValue) {
	param = new(ParameterValue)
	param.Type = ParameterValueTypeUri
	param.StringValue = uri
	return
}

func GetUriValue(param *ParameterValue) string {
	return param.StringValue
}

func CreateE164Param(e164 string) (param *ParameterValue) {
	param = new(ParameterValue)
	param.Type = ParameterValueTypeE164
	param.StringValue = e164
	return
}

func GetE164Value(param *ParameterValue) string {
	return param.StringValue
}

func CreateTrafficProtocolParam(trafficProtocol int) (param *ParameterValue) {
	param = new(ParameterValue)
	param.Type = ParameterValueTypeTrafficProtocol
	param.IntValue = trafficProtocol
	return
}

func GetTrafficProtocolValue(param *ParameterValue) int {
	return param.IntValue
}

func CreateAliasParam(alias string) (param *ParameterValue) {
	param = new(ParameterValue)
	param.Type = ParameterValueTypeAlias
	param.StringValue = alias
	return
}

func GetAliasValue(param *ParameterValue) string {
	return param.StringValue
}

func CreateTargetProtocolParam(targetProtocol int) (param *ParameterValue) {
	param = new(ParameterValue)
	param.Type = ParameterValueTypeTargetProtocol
	param.IntValue = targetProtocol
	return
}

func GetTargetProtocolValue(param *ParameterValue) int {
	return param.IntValue
}

func DeleteCustomerParameterValue(session *xorm.Session, customerId int) (err error) {
	_, err = session.Delete(&ParameterValue{CustomerId: customerId})
	return
}

func DeleteMitigationScopeParameterValue(session *xorm.Session, mitigationScopeId int64) (err error) {
	_, err = session.Delete(&ParameterValue{MitigationScopeId: mitigationScopeId})
	return
}

func DeleteIdentifierParameterValue(session *xorm.Session, identifierId int64) (err error) {
	_, err = session.Delete(&ParameterValue{IdentifierId: identifierId})
	return
}
<commit_msg>fixed the parameter vlaue type<commit_after>package db_models

import (
	"time"

	"github.com/go-xorm/xorm"
)

const ParameterValueTypeFqdn = "FQDN"
const ParameterValueTypeUri = "URI"
const ParameterValueTypeE164 = "E_164"
const ParameterValueTypeTrafficProtocol = "TRAFFIC_PROTOCOL"
const ParameterValueTypeAlias = "ALIAS"
const ParameterValueTypeTargetProtocol = "TARGET_PROTOCOL"

type ParameterValue struct {
	Id                int64     `xorm:"'id'"`
	CustomerId        int       `xorm:"'customer_id'"`
	IdentifierId      int64     `xorm:"'identifier_id'"`
	MitigationScopeId int64     `xorm:"'mitigation_scope_id'"`
	Type              string    `xorm:"'type' enum('FQDN','URI','E_164','TRAFFIC_PROTOCOL','ALIAS','TARGET_PROTOCOL') not null"`
	StringValue       string    `xorm:"'string_value'"`
	IntValue          int       `xorm:"'int_value'"`
	Created           time.Time `xorm:"created"`
	Updated           time.Time `xorm:"updated"`
}

func contains(stringList []string, target string) bool {
	for _, s := range stringList {
		if s == target {
			return true
		}
	}
	return false
}

const ParameterValueFieldTrafficProtocol = "TrafficProtocol"

var valueTypesString = []string{ParameterValueTypeFqdn, ParameterValueTypeUri, ParameterValueTypeE164}
var valueTypesInt = []string{ParameterValueFieldTrafficProtocol}

func CreateParameterValue(value interface{}, typeString string, identifierId int64) *ParameterValue {
	parameterValue := &ParameterValue{Type: typeString, IdentifierId: identifierId}
	if contains(valueTypesString, typeString) {
		parameterValue.StringValue = value.(string)
	} else if contains(valueTypesInt, typeString) {
		if typeString == ParameterValueFieldTrafficProtocol {
			parameterValue.Type = ParameterValueTypeTargetProtocol
		}
		parameterValue.IntValue = value.(int)
	} else { // invalid input
		return nil
	}

	return parameterValue
}

func CreateFqdnParam(fqdn string) (param *ParameterValue) {
	param = new(ParameterValue)
	param.Type = ParameterValueTypeFqdn
	param.StringValue = fqdn
	return
}

func GetFqdnValue(param *ParameterValue) string {
	return param.StringValue
}

func CreateUriParam(uri string) (param *ParameterValue) {
	param = new(ParameterValue)
	param.Type = ParameterValueTypeUri
	param.StringValue = uri
	return
}

func GetUriValue(param *ParameterValue) string {
	return param.StringValue
}

func CreateE164Param(e164 string) (param *ParameterValue) {
	param = new(ParameterValue)
	param.Type = ParameterValueTypeE164
	param.StringValue = e164
	return
}

func GetE164Value(param *ParameterValue) string {
	return param.StringValue
}

func CreateTrafficProtocolParam(trafficProtocol int) (param *ParameterValue) {
	param = new(ParameterValue)
	param.Type = ParameterValueTypeTrafficProtocol
	param.IntValue = trafficProtocol
	return
}

func GetTrafficProtocolValue(param *ParameterValue) int {
	return param.IntValue
}

func CreateAliasParam(alias string) (param *ParameterValue) {
	param = new(ParameterValue)
	param.Type = ParameterValueTypeAlias
	param.StringValue = alias
	return
}

func GetAliasValue(param *ParameterValue) string {
	return param.StringValue
}

func CreateTargetProtocolParam(targetProtocol int) (param *ParameterValue) {
	param = new(ParameterValue)
	param.Type = ParameterValueTypeTargetProtocol
	param.IntValue = targetProtocol
	return
}

func GetTargetProtocolValue(param *ParameterValue) int {
	return param.IntValue
}

func DeleteCustomerParameterValue(session *xorm.Session, customerId int) (err error) {
	_, err = session.Delete(&ParameterValue{CustomerId: customerId})
	return
}

func DeleteMitigationScopeParameterValue(session *xorm.Session, mitigationScopeId int64) (err error) {
	_, err = session.Delete(&ParameterValue{MitigationScopeId: mitigationScopeId})
	return
}

func DeleteIdentifierParameterValue(session *xorm.Session, identifierId int64) (err error) {
	_, err = session.Delete(&ParameterValue{IdentifierId: identifierId})
	return
}
<|endoftext|>


<commit_before>package lfs

import (
	"bytes"
	"encoding/base64"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/cheggaaa/pb"
	"github.com/rubyist/tracerx"
	"io"
	"io/ioutil"
	"net/http"
	"os"
	"path/filepath"
	"regexp"
	"strconv"
)

const (
	mediaType = "application/vnd.git-lfs+json; charset-utf-8"
)

var (
	lfsMediaTypeRE             = regexp.MustCompile(`\Aapplication/vnd\.git\-lfs\+json(;|\z)`)
	mediaMediaTypeRE           = regexp.MustCompile(`\Aapplication/json(;|\z)`)
	objectRelationDoesNotExist = errors.New("relation does not exist")
	hiddenHeaders              = map[string]bool{
		"Authorization": true,
	}

	// 401 and 403 print the same default error message
	defaultErrors = map[int]string{
		400: "Client error: %s",
		401: "Authorization error: %s\nCheck that you have proper access to the repository",
		404: "Repository or object not found: %s\nCheck that it exists and that you have proper access to it",
		500: "Server error: %s",
	}
)

type objectResource struct {
	Oid   string                   `json:"oid,omitempty"`
	Size  int64                    `json:"size,omitempty"`
	Links map[string]*linkRelation `json:"_links,omitempty"`
}

func (o *objectResource) NewRequest(relation, method string) (*http.Request, Creds, error) {
	rel, ok := o.Rel(relation)
	if !ok {
		return nil, nil, objectRelationDoesNotExist
	}

	req, creds, err := newClientRequest(method, rel.Href)
	if err != nil {
		return nil, nil, err
	}

	for h, v := range rel.Header {
		req.Header.Set(h, v)
	}

	return req, creds, nil
}

func (o *objectResource) Rel(name string) (*linkRelation, bool) {
	if o.Links == nil {
		return nil, false
	}

	rel, ok := o.Links[name]
	return rel, ok
}

type linkRelation struct {
	Href   string            `json:"href"`
	Header map[string]string `json:"header,omitempty"`
}

type ClientError struct {
	Message          string `json:"message"`
	DocumentationUrl string `json:"documentation_url,omitempty"`
	RequestId        string `json:"request_id,omitempty"`
}

func (e *ClientError) Error() string {
	msg := e.Message
	if len(e.DocumentationUrl) > 0 {
		msg += "\nDocs: " + e.DocumentationUrl
	}
	if len(e.RequestId) > 0 {
		msg += "\nRequest ID: " + e.RequestId
	}
	return msg
}

func Download(oid string) (io.ReadCloser, int64, *WrappedError) {
	req, creds, err := newApiRequest("GET", oid)
	if err != nil {
		return nil, 0, Error(err)
	}

	res, obj, wErr := doApiRequest(req, creds)
	if wErr != nil {
		return nil, 0, wErr
	}

	req, creds, err = obj.NewRequest("download", "GET")
	if err != nil {
		return nil, 0, Error(err)
	}

	res, wErr = doHttpRequest(req, creds)
	if wErr != nil {
		return nil, 0, wErr
	}

	return res.Body, res.ContentLength, nil
}

func Upload(oidPath, filename string, cb CopyCallback) *WrappedError {
	oid := filepath.Base(oidPath)
	file, err := os.Open(oidPath)
	if err != nil {
		return Error(err)
	}
	defer file.Close()

	stat, err := file.Stat()
	if err != nil {
		return Error(err)
	}

	reqObj := &objectResource{
		Oid:  oid,
		Size: stat.Size(),
	}

	by, err := json.Marshal(reqObj)
	if err != nil {
		return Error(err)
	}

	req, creds, err := newApiRequest("POST", "")
	if err != nil {
		return Error(err)
	}

	req.Header.Set("Content-Type", mediaType)
	req.Header.Set("Content-Length", strconv.Itoa(len(by)))
	req.ContentLength = int64(len(by))
	req.Body = ioutil.NopCloser(bytes.NewReader(by))

	tracerx.Printf("api: uploading %s (%s)", filename, oid)
	res, obj, wErr := doApiRequest(req, creds)
	if wErr != nil {
		return wErr
	}

	if res.StatusCode == 200 {
		return nil
	}

	req, creds, err = obj.NewRequest("upload", "PUT")
	if err != nil {
		return Error(err)
	}

	if len(req.Header.Get("Content-Type")) == 0 {
		req.Header.Set("Content-Type", "application/octet-stream")
	}
	req.Header.Set("Content-Length", strconv.FormatInt(reqObj.Size, 10))
	req.ContentLength = reqObj.Size

	reader := &CallbackReader{
		C:         cb,
		TotalSize: reqObj.Size,
		Reader:    file,
	}

	bar := pb.New64(reqObj.Size)
	bar.SetUnits(pb.U_BYTES)
	bar.Start()

	req.Body = ioutil.NopCloser(bar.NewProxyReader(reader))

	res, wErr = doHttpRequest(req, creds)
	if wErr != nil {
		return wErr
	}

	if res.StatusCode > 299 {
		return Errorf(nil, "Invalid status for %s %s: %d", req.Method, req.URL, res.StatusCode)
	}

	io.Copy(ioutil.Discard, res.Body)
	res.Body.Close()

	req, creds, err = obj.NewRequest("verify", "POST")
	if err == objectRelationDoesNotExist {
		return nil
	} else if err != nil {
		return Error(err)
	}

	req.Header.Set("Content-Type", mediaType)
	req.Header.Set("Content-Length", strconv.Itoa(len(by)))
	req.ContentLength = int64(len(by))
	req.Body = ioutil.NopCloser(bytes.NewReader(by))
	res, wErr = doHttpRequest(req, creds)

	io.Copy(ioutil.Discard, res.Body)
	res.Body.Close()

	return wErr
}

func doHttpRequest(req *http.Request, creds Creds) (*http.Response, *WrappedError) {
	res, err := DoHTTP(Config, req)

	var wErr *WrappedError

	if err != nil {
		wErr = Errorf(err, "Error for %s %s", res.Request.Method, res.Request.URL)
	} else {
		if creds != nil {
			saveCredentials(creds, res)
		}

		wErr = handleResponse(res)
	}

	if wErr != nil {
		if res != nil {
			setErrorResponseContext(wErr, res)
		} else {
			setErrorRequestContext(wErr, req)
		}
	}

	return res, wErr
}

func doApiRequest(req *http.Request, creds Creds) (*http.Response, *objectResource, *WrappedError) {
	res, wErr := doHttpRequest(req, creds)
	if wErr != nil {
		return res, nil, wErr
	}

	obj := &objectResource{}
	wErr = decodeApiResponse(res, obj)

	if wErr != nil {
		setErrorResponseContext(wErr, res)
	}

	return res, obj, wErr
}

func handleResponse(res *http.Response) *WrappedError {
	if res.StatusCode < 400 {
		return nil
	}

	defer func() {
		io.Copy(ioutil.Discard, res.Body)
		res.Body.Close()
	}()

	cliErr := &ClientError{}
	wErr := decodeApiResponse(res, cliErr)
	if wErr == nil {
		if len(cliErr.Message) == 0 {
			wErr = defaultError(res)
		} else {
			wErr = Error(cliErr)
		}
	}

	wErr.Panic = res.StatusCode > 499 && res.StatusCode != 501 && res.StatusCode != 509
	return wErr
}

func decodeApiResponse(res *http.Response, obj interface{}) *WrappedError {
	ctype := res.Header.Get("Content-Type")
	if !(lfsMediaTypeRE.MatchString(ctype) || mediaMediaTypeRE.MatchString(ctype)) {
		return nil
	}

	err := json.NewDecoder(res.Body).Decode(obj)
	io.Copy(ioutil.Discard, res.Body)
	res.Body.Close()

	if err != nil {
		return Errorf(err, "Unable to parse HTTP response for %s %s", res.Request.Method, res.Request.URL)
	}

	return nil
}

func defaultError(res *http.Response) *WrappedError {
	var msgFmt string

	if f, ok := defaultErrors[res.StatusCode]; ok {
		msgFmt = f
	} else if res.StatusCode < 500 {
		msgFmt = defaultErrors[400] + fmt.Sprintf(" from HTTP %d", res.StatusCode)
	} else {
		msgFmt = defaultErrors[500] + fmt.Sprintf(" from HTTP %d", res.StatusCode)
	}

	return Error(fmt.Errorf(msgFmt, res.Request.URL))
}

func saveCredentials(creds Creds, res *http.Response) {
	if creds == nil {
		return
	}

	if res.StatusCode < 300 {
		execCreds(creds, "approve")
	} else if res.StatusCode == 401 {
		execCreds(creds, "reject")
	}
}

func newApiRequest(method, oid string) (*http.Request, Creds, error) {
	u, err := Config.ObjectUrl(oid)
	if err != nil {
		return nil, nil, err
	}

	req, creds, err := newClientRequest(method, u.String())
	if err == nil {
		req.Header.Set("Accept", mediaType)
	}
	return req, creds, err
}

func newClientRequest(method, rawurl string) (*http.Request, Creds, error) {
	req, err := http.NewRequest(method, rawurl, nil)
	if err != nil {
		return req, nil, err
	}

	req.Header.Set("User-Agent", UserAgent)
	creds, err := getCreds(req)
	return req, creds, err
}

func getCreds(req *http.Request) (Creds, error) {
	if len(req.Header.Get("Authorization")) > 0 {
		return nil, nil
	}

	apiUrl, err := Config.ObjectUrl("")
	if err != nil {
		return nil, err
	}

	if req.URL.Scheme == apiUrl.Scheme &&
		req.URL.Host == apiUrl.Host {
		creds, err := credentials(req.URL)
		if err != nil {
			return nil, err
		}

		token := fmt.Sprintf("%s:%s", creds["username"], creds["password"])
		auth := "Basic " + base64.URLEncoding.EncodeToString([]byte(token))
		req.Header.Set("Authorization", auth)
		return creds, nil
	}

	return nil, nil
}

func setErrorRequestContext(err *WrappedError, req *http.Request) {
	err.Set("Endpoint", Config.Endpoint())
	err.Set("URL", fmt.Sprintf("%s %s", req.Method, req.URL.String()))
	setErrorHeaderContext(err, "Response", req.Header)
}

func setErrorResponseContext(err *WrappedError, res *http.Response) {
	err.Set("Status", res.Status)
	setErrorHeaderContext(err, "Request", res.Header)
	setErrorRequestContext(err, res.Request)
}

func setErrorHeaderContext(err *WrappedError, prefix string, head http.Header) {
	for key, _ := range head {
		contextKey := fmt.Sprintf("%s:%s", prefix, key)
		if _, skip := hiddenHeaders[key]; skip {
			err.Set(contextKey, "--")
		} else {
			err.Set(contextKey, head.Get(key))
		}
	}
}

func init() {
	defaultErrors[403] = defaultErrors[401]
}
<commit_msg>fix weird variable name<commit_after>package lfs

import (
	"bytes"
	"encoding/base64"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/cheggaaa/pb"
	"github.com/rubyist/tracerx"
	"io"
	"io/ioutil"
	"net/http"
	"os"
	"path/filepath"
	"regexp"
	"strconv"
)

const (
	mediaType = "application/vnd.git-lfs+json; charset-utf-8"
)

var (
	lfsMediaTypeRE             = regexp.MustCompile(`\Aapplication/vnd\.git\-lfs\+json(;|\z)`)
	jsonMediaTypeRE            = regexp.MustCompile(`\Aapplication/json(;|\z)`)
	objectRelationDoesNotExist = errors.New("relation does not exist")
	hiddenHeaders              = map[string]bool{
		"Authorization": true,
	}

	// 401 and 403 print the same default error message
	defaultErrors = map[int]string{
		400: "Client error: %s",
		401: "Authorization error: %s\nCheck that you have proper access to the repository",
		404: "Repository or object not found: %s\nCheck that it exists and that you have proper access to it",
		500: "Server error: %s",
	}
)

type objectResource struct {
	Oid   string                   `json:"oid,omitempty"`
	Size  int64                    `json:"size,omitempty"`
	Links map[string]*linkRelation `json:"_links,omitempty"`
}

func (o *objectResource) NewRequest(relation, method string) (*http.Request, Creds, error) {
	rel, ok := o.Rel(relation)
	if !ok {
		return nil, nil, objectRelationDoesNotExist
	}

	req, creds, err := newClientRequest(method, rel.Href)
	if err != nil {
		return nil, nil, err
	}

	for h, v := range rel.Header {
		req.Header.Set(h, v)
	}

	return req, creds, nil
}

func (o *objectResource) Rel(name string) (*linkRelation, bool) {
	if o.Links == nil {
		return nil, false
	}

	rel, ok := o.Links[name]
	return rel, ok
}

type linkRelation struct {
	Href   string            `json:"href"`
	Header map[string]string `json:"header,omitempty"`
}

type ClientError struct {
	Message          string `json:"message"`
	DocumentationUrl string `json:"documentation_url,omitempty"`
	RequestId        string `json:"request_id,omitempty"`
}

func (e *ClientError) Error() string {
	msg := e.Message
	if len(e.DocumentationUrl) > 0 {
		msg += "\nDocs: " + e.DocumentationUrl
	}
	if len(e.RequestId) > 0 {
		msg += "\nRequest ID: " + e.RequestId
	}
	return msg
}

func Download(oid string) (io.ReadCloser, int64, *WrappedError) {
	req, creds, err := newApiRequest("GET", oid)
	if err != nil {
		return nil, 0, Error(err)
	}

	res, obj, wErr := doApiRequest(req, creds)
	if wErr != nil {
		return nil, 0, wErr
	}

	req, creds, err = obj.NewRequest("download", "GET")
	if err != nil {
		return nil, 0, Error(err)
	}

	res, wErr = doHttpRequest(req, creds)
	if wErr != nil {
		return nil, 0, wErr
	}

	return res.Body, res.ContentLength, nil
}

func Upload(oidPath, filename string, cb CopyCallback) *WrappedError {
	oid := filepath.Base(oidPath)
	file, err := os.Open(oidPath)
	if err != nil {
		return Error(err)
	}
	defer file.Close()

	stat, err := file.Stat()
	if err != nil {
		return Error(err)
	}

	reqObj := &objectResource{
		Oid:  oid,
		Size: stat.Size(),
	}

	by, err := json.Marshal(reqObj)
	if err != nil {
		return Error(err)
	}

	req, creds, err := newApiRequest("POST", "")
	if err != nil {
		return Error(err)
	}

	req.Header.Set("Content-Type", mediaType)
	req.Header.Set("Content-Length", strconv.Itoa(len(by)))
	req.ContentLength = int64(len(by))
	req.Body = ioutil.NopCloser(bytes.NewReader(by))

	tracerx.Printf("api: uploading %s (%s)", filename, oid)
	res, obj, wErr := doApiRequest(req, creds)
	if wErr != nil {
		return wErr
	}

	if res.StatusCode == 200 {
		return nil
	}

	req, creds, err = obj.NewRequest("upload", "PUT")
	if err != nil {
		return Error(err)
	}

	if len(req.Header.Get("Content-Type")) == 0 {
		req.Header.Set("Content-Type", "application/octet-stream")
	}
	req.Header.Set("Content-Length", strconv.FormatInt(reqObj.Size, 10))
	req.ContentLength = reqObj.Size

	reader := &CallbackReader{
		C:         cb,
		TotalSize: reqObj.Size,
		Reader:    file,
	}

	bar := pb.New64(reqObj.Size)
	bar.SetUnits(pb.U_BYTES)
	bar.Start()

	req.Body = ioutil.NopCloser(bar.NewProxyReader(reader))

	res, wErr = doHttpRequest(req, creds)
	if wErr != nil {
		return wErr
	}

	if res.StatusCode > 299 {
		return Errorf(nil, "Invalid status for %s %s: %d", req.Method, req.URL, res.StatusCode)
	}

	io.Copy(ioutil.Discard, res.Body)
	res.Body.Close()

	req, creds, err = obj.NewRequest("verify", "POST")
	if err == objectRelationDoesNotExist {
		return nil
	} else if err != nil {
		return Error(err)
	}

	req.Header.Set("Content-Type", mediaType)
	req.Header.Set("Content-Length", strconv.Itoa(len(by)))
	req.ContentLength = int64(len(by))
	req.Body = ioutil.NopCloser(bytes.NewReader(by))
	res, wErr = doHttpRequest(req, creds)

	io.Copy(ioutil.Discard, res.Body)
	res.Body.Close()

	return wErr
}

func doHttpRequest(req *http.Request, creds Creds) (*http.Response, *WrappedError) {
	res, err := DoHTTP(Config, req)

	var wErr *WrappedError

	if err != nil {
		wErr = Errorf(err, "Error for %s %s", res.Request.Method, res.Request.URL)
	} else {
		if creds != nil {
			saveCredentials(creds, res)
		}

		wErr = handleResponse(res)
	}

	if wErr != nil {
		if res != nil {
			setErrorResponseContext(wErr, res)
		} else {
			setErrorRequestContext(wErr, req)
		}
	}

	return res, wErr
}

func doApiRequest(req *http.Request, creds Creds) (*http.Response, *objectResource, *WrappedError) {
	res, wErr := doHttpRequest(req, creds)
	if wErr != nil {
		return res, nil, wErr
	}

	obj := &objectResource{}
	wErr = decodeApiResponse(res, obj)

	if wErr != nil {
		setErrorResponseContext(wErr, res)
	}

	return res, obj, wErr
}

func handleResponse(res *http.Response) *WrappedError {
	if res.StatusCode < 400 {
		return nil
	}

	defer func() {
		io.Copy(ioutil.Discard, res.Body)
		res.Body.Close()
	}()

	cliErr := &ClientError{}
	wErr := decodeApiResponse(res, cliErr)
	if wErr == nil {
		if len(cliErr.Message) == 0 {
			wErr = defaultError(res)
		} else {
			wErr = Error(cliErr)
		}
	}

	wErr.Panic = res.StatusCode > 499 && res.StatusCode != 501 && res.StatusCode != 509
	return wErr
}

func decodeApiResponse(res *http.Response, obj interface{}) *WrappedError {
	ctype := res.Header.Get("Content-Type")
	if !(lfsMediaTypeRE.MatchString(ctype) || jsonMediaTypeRE.MatchString(ctype)) {
		return nil
	}

	err := json.NewDecoder(res.Body).Decode(obj)
	io.Copy(ioutil.Discard, res.Body)
	res.Body.Close()

	if err != nil {
		return Errorf(err, "Unable to parse HTTP response for %s %s", res.Request.Method, res.Request.URL)
	}

	return nil
}

func defaultError(res *http.Response) *WrappedError {
	var msgFmt string

	if f, ok := defaultErrors[res.StatusCode]; ok {
		msgFmt = f
	} else if res.StatusCode < 500 {
		msgFmt = defaultErrors[400] + fmt.Sprintf(" from HTTP %d", res.StatusCode)
	} else {
		msgFmt = defaultErrors[500] + fmt.Sprintf(" from HTTP %d", res.StatusCode)
	}

	return Error(fmt.Errorf(msgFmt, res.Request.URL))
}

func saveCredentials(creds Creds, res *http.Response) {
	if creds == nil {
		return
	}

	if res.StatusCode < 300 {
		execCreds(creds, "approve")
	} else if res.StatusCode == 401 {
		execCreds(creds, "reject")
	}
}

func newApiRequest(method, oid string) (*http.Request, Creds, error) {
	u, err := Config.ObjectUrl(oid)
	if err != nil {
		return nil, nil, err
	}

	req, creds, err := newClientRequest(method, u.String())
	if err == nil {
		req.Header.Set("Accept", mediaType)
	}
	return req, creds, err
}

func newClientRequest(method, rawurl string) (*http.Request, Creds, error) {
	req, err := http.NewRequest(method, rawurl, nil)
	if err != nil {
		return req, nil, err
	}

	req.Header.Set("User-Agent", UserAgent)
	creds, err := getCreds(req)
	return req, creds, err
}

func getCreds(req *http.Request) (Creds, error) {
	if len(req.Header.Get("Authorization")) > 0 {
		return nil, nil
	}

	apiUrl, err := Config.ObjectUrl("")
	if err != nil {
		return nil, err
	}

	if req.URL.Scheme == apiUrl.Scheme &&
		req.URL.Host == apiUrl.Host {
		creds, err := credentials(req.URL)
		if err != nil {
			return nil, err
		}

		token := fmt.Sprintf("%s:%s", creds["username"], creds["password"])
		auth := "Basic " + base64.URLEncoding.EncodeToString([]byte(token))
		req.Header.Set("Authorization", auth)
		return creds, nil
	}

	return nil, nil
}

func setErrorRequestContext(err *WrappedError, req *http.Request) {
	err.Set("Endpoint", Config.Endpoint())
	err.Set("URL", fmt.Sprintf("%s %s", req.Method, req.URL.String()))
	setErrorHeaderContext(err, "Response", req.Header)
}

func setErrorResponseContext(err *WrappedError, res *http.Response) {
	err.Set("Status", res.Status)
	setErrorHeaderContext(err, "Request", res.Header)
	setErrorRequestContext(err, res.Request)
}

func setErrorHeaderContext(err *WrappedError, prefix string, head http.Header) {
	for key, _ := range head {
		contextKey := fmt.Sprintf("%s:%s", prefix, key)
		if _, skip := hiddenHeaders[key]; skip {
			err.Set(contextKey, "--")
		} else {
			err.Set(contextKey, head.Get(key))
		}
	}
}

func init() {
	defaultErrors[403] = defaultErrors[401]
}
<|endoftext|>


<commit_before>package vegeta

import (
	"crypto/tls"
	"fmt"
	"io/ioutil"
	"net"
	"net/http"
	"sync"
	"time"
)

// Attacker is an attack executor which wraps an http.Client
type Attacker struct {
	dialer *net.Dialer
	client http.Client
}

var (
	// DefaultRedirects is the default number of times an Attacker follows
	// redirects.
	DefaultRedirects = 10
	// DefaultTimeout is the default amount of time an Attacker waits for a request
	// before it times out.
	DefaultTimeout = 30 * time.Second
	// DefaultLocalAddr is the default local IP address an Attacker uses.
	DefaultLocalAddr = net.IPAddr{IP: net.IPv4zero}
	// DefaultTLSConfig is the default tls.Config an Attacker uses.
	DefaultTLSConfig = &tls.Config{InsecureSkipVerify: true}
)

// NewAttacker returns a new Attacker with default options which are overridden
// by the optionally provided opts.
func NewAttacker(opts ...func(*Attacker)) *Attacker {
	a := &Attacker{}
	a.dialer = &net.Dialer{
		LocalAddr: &net.TCPAddr{IP: DefaultLocalAddr.IP, Zone: DefaultLocalAddr.Zone},
		KeepAlive: 30 * time.Second,
		Timeout:   DefaultTimeout,
	}
	a.client = http.Client{
		Transport: &http.Transport{
			Proxy: http.ProxyFromEnvironment,
			Dial:  a.dialer.Dial,
			ResponseHeaderTimeout: DefaultTimeout,
			TLSClientConfig:       DefaultTLSConfig,
			TLSHandshakeTimeout:   10 * time.Second,
		},
	}
	for _, opt := range opts {
		opt(a)
	}
	return a
}

// Redirects returns a functional option which sets the maximum
// number of redirects an Attacker will follow.
func Redirects(n int) func(*Attacker) {
	return func(a *Attacker) {
		a.client.CheckRedirect = func(_ *http.Request, via []*http.Request) error {
			if len(via) > n {
				return fmt.Errorf("stopped after %d redirects", n)
			}
			return nil
		}
	}
}

// Timeout returns a functional option which sets the maximum amount of time
// an Attacker will wait for a request to be responded to.
func Timeout(d time.Duration) func(*Attacker) {
	return func(a *Attacker) {
		tr := a.client.Transport.(*http.Transport)
		tr.ResponseHeaderTimeout = d
		a.dialer.Timeout = d
		tr.Dial = a.dialer.Dial
		a.client.Transport = tr
	}
}

// LocalAddr returns a functional option which sets the local address
// an Attacker will use with its requests.
func LocalAddr(addr net.IPAddr) func(*Attacker) {
	return func(a *Attacker) {
		tr := a.client.Transport.(*http.Transport)
		a.dialer.LocalAddr = &net.TCPAddr{IP: addr.IP, Zone: addr.Zone}
		tr.Dial = a.dialer.Dial
		a.client.Transport = tr
	}
}

// TLSConfig returns a functional option which sets the *tls.Config for a
// Attacker to use with its requests.
func TLSConfig(c *tls.Config) func(*Attacker) {
	return func(a *Attacker) {
		tr := a.client.Transport.(*http.Transport)
		tr.TLSClientConfig = c
		a.client.Transport = tr
	}
}

// Attack reads its Targets from the passed Targeter and attacks them at
// the rate specified for duration time. Results are put into the returned channel
// as soon as they arrive.
//
// The number of workers used in the attack is specified by wrk.
// If wrk is zero or greater than the total number of hits, it will be capped
// to that maximum.
func (a *Attacker) Attack(tr Targeter, rate uint64, du time.Duration, wrk uint64) chan *Result {
	resc := make(chan *Result)
	throttle := time.NewTicker(time.Duration(1e9 / rate))
	hits := rate * uint64(du.Seconds())
	if wrk == 0 || wrk > hits {
		wrk = hits
	}
	share := hits / wrk

	var wg sync.WaitGroup
	for i := uint64(0); i < wrk; i++ {
		wg.Add(1)
		go func(share uint64) {
			for j := uint64(0); j < share; j++ {
				<-throttle.C
				resc <- a.hit(tr)
			}
			wg.Done()
		}(share)
	}

	go func() {
		wg.Wait()
		close(resc)
		throttle.Stop()
	}()

	return resc
}

func (a *Attacker) hit(tr Targeter) *Result {
	tgt, err := tr()
	if err != nil {
		return &Result{Error: err.Error()}
	}

	res := new(Result)
	req, err := tgt.Request()
	if err != nil {
		res.Error = err.Error()
		return res
	}

	res.Timestamp = time.Now()
	r, err := a.client.Do(req)
	res.Latency = time.Since(res.Timestamp)
	if err != nil {
		res.Error = err.Error()
		return res
	}
	defer r.Body.Close()

	res.BytesOut = uint64(req.ContentLength)
	res.Code = uint16(r.StatusCode)
	if body, err := ioutil.ReadAll(r.Body); err != nil {
		if res.Code < 200 || res.Code >= 300 {
			res.Error = string(body)
		}
	} else {
		res.BytesIn = uint64(len(body))
	}
	res.Latency = time.Since(res.Timestamp)

	return res
}
<commit_msg>Add Stop method to Attacker<commit_after>package vegeta

import (
	"crypto/tls"
	"fmt"
	"io/ioutil"
	"net"
	"net/http"
	"sync"
	"time"
)

// Attacker is an attack executor which wraps an http.Client
type Attacker struct {
	dialer *net.Dialer
	client http.Client
	stop   chan struct{}
}

var (
	// DefaultRedirects is the default number of times an Attacker follows
	// redirects.
	DefaultRedirects = 10
	// DefaultTimeout is the default amount of time an Attacker waits for a request
	// before it times out.
	DefaultTimeout = 30 * time.Second
	// DefaultLocalAddr is the default local IP address an Attacker uses.
	DefaultLocalAddr = net.IPAddr{IP: net.IPv4zero}
	// DefaultTLSConfig is the default tls.Config an Attacker uses.
	DefaultTLSConfig = &tls.Config{InsecureSkipVerify: true}
)

// NewAttacker returns a new Attacker with default options which are overridden
// by the optionally provided opts.
func NewAttacker(opts ...func(*Attacker)) *Attacker {
	a := &Attacker{}
	a.dialer = &net.Dialer{
		LocalAddr: &net.TCPAddr{IP: DefaultLocalAddr.IP, Zone: DefaultLocalAddr.Zone},
		KeepAlive: 30 * time.Second,
		Timeout:   DefaultTimeout,
	}
	a.client = http.Client{
		Transport: &http.Transport{
			Proxy: http.ProxyFromEnvironment,
			Dial:  a.dialer.Dial,
			ResponseHeaderTimeout: DefaultTimeout,
			TLSClientConfig:       DefaultTLSConfig,
			TLSHandshakeTimeout:   10 * time.Second,
		},
	}
	for _, opt := range opts {
		opt(a)
	}
	return a
}

// Redirects returns a functional option which sets the maximum
// number of redirects an Attacker will follow.
func Redirects(n int) func(*Attacker) {
	return func(a *Attacker) {
		a.client.CheckRedirect = func(_ *http.Request, via []*http.Request) error {
			if len(via) > n {
				return fmt.Errorf("stopped after %d redirects", n)
			}
			return nil
		}
	}
}

// Timeout returns a functional option which sets the maximum amount of time
// an Attacker will wait for a request to be responded to.
func Timeout(d time.Duration) func(*Attacker) {
	return func(a *Attacker) {
		tr := a.client.Transport.(*http.Transport)
		tr.ResponseHeaderTimeout = d
		a.dialer.Timeout = d
		tr.Dial = a.dialer.Dial
		a.client.Transport = tr
	}
}

// LocalAddr returns a functional option which sets the local address
// an Attacker will use with its requests.
func LocalAddr(addr net.IPAddr) func(*Attacker) {
	return func(a *Attacker) {
		tr := a.client.Transport.(*http.Transport)
		a.dialer.LocalAddr = &net.TCPAddr{IP: addr.IP, Zone: addr.Zone}
		tr.Dial = a.dialer.Dial
		a.client.Transport = tr
	}
}

// TLSConfig returns a functional option which sets the *tls.Config for a
// Attacker to use with its requests.
func TLSConfig(c *tls.Config) func(*Attacker) {
	return func(a *Attacker) {
		tr := a.client.Transport.(*http.Transport)
		tr.TLSClientConfig = c
		a.client.Transport = tr
	}
}

// Attack reads its Targets from the passed Targeter and attacks them at
// the rate specified for duration time. Results are put into the returned channel
// as soon as they arrive.
//
// The number of workers used in the attack is specified by wrk.
// If wrk is zero or greater than the total number of hits, it will be capped
// to that maximum.
func (a *Attacker) Attack(tr Targeter, rate uint64, du time.Duration, wrk uint64) chan *Result {
	resc := make(chan *Result)
	throttle := time.NewTicker(time.Duration(1e9 / rate))
	hits := rate * uint64(du.Seconds())
	if wrk == 0 || wrk > hits {
		wrk = hits
	}
	share := hits / wrk

	var wg sync.WaitGroup
	for i := uint64(0); i < wrk; i++ {
		wg.Add(1)
		go func(share uint64) {
			defer wg.Done()
			for j := uint64(0); j < share; j++ {
				select {
				case <-throttle.C:
					resc <- a.hit(tr)
				case <-a.stop:
					return
				}
			}
		}(share)
	}

	go func() {
		wg.Wait()
		close(resc)
		throttle.Stop()
	}()

	return resc
}

// Stop stops the current attack.
func (a *Attacker) Stop() { close(a.stop) }

func (a *Attacker) hit(tr Targeter) *Result {
	tgt, err := tr()
	if err != nil {
		return &Result{Error: err.Error()}
	}

	res := new(Result)
	req, err := tgt.Request()
	if err != nil {
		res.Error = err.Error()
		return res
	}

	res.Timestamp = time.Now()
	r, err := a.client.Do(req)
	res.Latency = time.Since(res.Timestamp)
	if err != nil {
		res.Error = err.Error()
		return res
	}
	defer r.Body.Close()

	res.BytesOut = uint64(req.ContentLength)
	res.Code = uint16(r.StatusCode)
	if body, err := ioutil.ReadAll(r.Body); err != nil {
		if res.Code < 200 || res.Code >= 300 {
			res.Error = string(body)
		}
	} else {
		res.BytesIn = uint64(len(body))
	}
	res.Latency = time.Since(res.Timestamp)

	return res
}
<|endoftext|>


<commit_before>package main

import "github.com/ChimeraCoder/anaconda"
import "gopkg.in/gin-gonic/gin.v1"
import "net/http"
import "net/url"
import "os"
import "log"
import "strconv"

func setup() {
	anaconda.SetConsumerKey(os.Getenv("TW_CONSUMER_KEY"))
	anaconda.SetConsumerSecret(os.Getenv("TW_CONSUMER_SECRET"))
}

func extractTweets(c *gin.Context, timeline []anaconda.Tweet) []string {

	var tweets []string
	for _, tweet := range timeline {
		tweets = append(tweets, tweet.Text)
	}

	return tweets
}

// Get a list of friends from Twitter, put them in a map if setting,
// else add to a list if found in map
func getFriends(api *anaconda.TwitterApi, friends map[string]bool, userId string, setOrCheck bool) []string {

	var mutual []string

	values := url.Values{}
	values.Set("user_id", userId)

	ch := api.GetFriendsListAll(values)

	for friendPage := range ch {
		if friendPage.Error == nil {
			for _, user := range friendPage.Friends {
				id := strconv.FormatInt(user.Id, 10)
				log.Printf("name = %s, id = %s", user.Name, id)
				if setOrCheck {
					friends[id] = true
				} else {
					_, found := friends[id]
					if found {
						mutual = append(mutual, user.Name)
					}
				}
			}
		}
	}

	return mutual
}

func main() {
	setup()

	router := gin.Default()

	//Swagger docs
	router.Static("/doc", "./doc")

	// This handler will match /tweets/john but will not match either /tweets/ or /tweets
	router.GET("/tweets/:name", func(c *gin.Context) {
		name := c.Param("name")
		api := anaconda.NewTwitterApi(os.Getenv("TW_ACCESS_TOKEN"), os.Getenv("TW_ACCESS_TOKEN_SECRET"))
		values := url.Values{}
		values.Add("screen_name", name)
		timeline, err := api.GetUserTimeline(values)
		if err != nil {
			// log.Fatal(err)
			c.JSON(http.StatusBadRequest, gin.H{"error": "Could not find user"}) // TODO: Better error handling here
			return
		}
		tweets := extractTweets(c, timeline)
		c.JSON(http.StatusOK, tweets)
	})

	// This route will match /common/abby/boris
	router.GET("/common/:name/:other", func(c *gin.Context) {
		names := c.Param("name")
		other := c.Param("other")
		names = names + ","
		names = names + other
		api := anaconda.NewTwitterApi(os.Getenv("TW_ACCESS_TOKEN"), os.Getenv("TW_ACCESS_TOKEN_SECRET"))
		values := url.Values{} // Would like to stringify ids but not sure if anaconda will handle that ...
		users, err := api.GetUsersLookup(names, values)
		if err != nil {
			log.Fatal(err)
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error}) // TODO Wrong status code!
			return
		}
		if len(users) < 2 {
			c.JSON(http.StatusNotFound, gin.H{"error": "Could not find both users by name"})
			return
		}
		if len(users) != 2 {
			c.JSON(http.StatusNotFound, gin.H{"error": "Too many users with those names"})
			return
		}

		// This map contains the names of the friends
		//
		var friends map[string]bool
		friends = make(map[string]bool)

		// Get the friends for the smaller of the two
		var getUserIndex = 1
		if users[0].FriendsCount < users[1].FriendsCount {
			getUserIndex = 0
		}

		userId := strconv.FormatInt(users[getUserIndex].Id, 10)
		log.Printf("Getting friends for index %d, user %s\n", getUserIndex, userId)
		_ = getFriends(api, friends, userId, true) // true = set value

		// Now get the other user's friends
		getUserIndex = (getUserIndex + 1) % 2

		userId = strconv.FormatInt(users[getUserIndex].Id, 10)
		log.Printf("Getting friends for index %d, user %s\n", getUserIndex, userId)
		mutual := getFriends(api, friends, userId, false) // false = check values

		c.JSON(http.StatusOK, mutual)
	})

	router.Run(":8000")
}
<commit_msg>Use Env var for port<commit_after>package main

import "github.com/ChimeraCoder/anaconda"
import "gopkg.in/gin-gonic/gin.v1"
import "net/http"
import "net/url"
import "os"
import "log"
import "strconv"

func setup() {
	anaconda.SetConsumerKey(os.Getenv("TW_CONSUMER_KEY"))
	anaconda.SetConsumerSecret(os.Getenv("TW_CONSUMER_SECRET"))
}

func extractTweets(c *gin.Context, timeline []anaconda.Tweet) []string {

	var tweets []string
	for _, tweet := range timeline {
		tweets = append(tweets, tweet.Text)
	}

	return tweets
}

// Get a list of friends from Twitter, put them in a map if setting,
// else add to a list if found in map
func getFriends(api *anaconda.TwitterApi, friends map[string]bool, userId string, setOrCheck bool) []string {

	var mutual []string

	values := url.Values{}
	values.Set("user_id", userId)

	ch := api.GetFriendsListAll(values)

	for friendPage := range ch {
		if friendPage.Error == nil {
			for _, user := range friendPage.Friends {
				id := strconv.FormatInt(user.Id, 10)
				log.Printf("name = %s, id = %s", user.Name, id)
				if setOrCheck {
					friends[id] = true
				} else {
					_, found := friends[id]
					if found {
						mutual = append(mutual, user.Name)
					}
				}
			}
		}
	}

	return mutual
}

func main() {
	setup()

	router := gin.Default()

	//Swagger docs
	router.Static("/doc", "./doc")

	// This handler will match /tweets/john but will not match either /tweets/ or /tweets
	router.GET("/tweets/:name", func(c *gin.Context) {
		name := c.Param("name")
		api := anaconda.NewTwitterApi(os.Getenv("TW_ACCESS_TOKEN"), os.Getenv("TW_ACCESS_TOKEN_SECRET"))
		values := url.Values{}
		values.Add("screen_name", name)
		timeline, err := api.GetUserTimeline(values)
		if err != nil {
			// log.Fatal(err)
			c.JSON(http.StatusBadRequest, gin.H{"error": "Could not find user"}) // TODO: Better error handling here
			return
		}
		tweets := extractTweets(c, timeline)
		c.JSON(http.StatusOK, tweets)
	})

	// This route will match /common/abby/boris
	router.GET("/common/:name/:other", func(c *gin.Context) {
		names := c.Param("name")
		other := c.Param("other")
		names = names + ","
		names = names + other
		api := anaconda.NewTwitterApi(os.Getenv("TW_ACCESS_TOKEN"), os.Getenv("TW_ACCESS_TOKEN_SECRET"))
		values := url.Values{} // Would like to stringify ids but not sure if anaconda will handle that ...
		users, err := api.GetUsersLookup(names, values)
		if err != nil {
			log.Fatal(err)
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error}) // TODO Wrong status code!
			return
		}
		if len(users) < 2 {
			c.JSON(http.StatusNotFound, gin.H{"error": "Could not find both users by name"})
			return
		}
		if len(users) != 2 {
			c.JSON(http.StatusNotFound, gin.H{"error": "Too many users with those names"})
			return
		}

		// This map contains the names of the friends
		//
		var friends map[string]bool
		friends = make(map[string]bool)

		// Get the friends for the smaller of the two
		var getUserIndex = 1
		if users[0].FriendsCount < users[1].FriendsCount {
			getUserIndex = 0
		}

		userId := strconv.FormatInt(users[getUserIndex].Id, 10)
		log.Printf("Getting friends for index %d, user %s\n", getUserIndex, userId)
		_ = getFriends(api, friends, userId, true) // true = set value

		// Now get the other user's friends
		getUserIndex = (getUserIndex + 1) % 2

		userId = strconv.FormatInt(users[getUserIndex].Id, 10)
		log.Printf("Getting friends for index %d, user %s\n", getUserIndex, userId)
		mutual := getFriends(api, friends, userId, false) // false = check values

		c.JSON(http.StatusOK, mutual)
	})

	port := os.Getenv("PORT")
	if port == "" {
		log.Fatal("$PORT must be set")
	}
	router.Run(":" + port)
}
<|endoftext|>


<commit_before>package main

import "os"

const (
	raw = "https://raw.githubusercontent.com/amorwilliams/bodoni/master/lib/services/services.go"
)

func main() {
	if len(os.Args) <= 1 {
		return
	}
	// resp, err := http.Get(raw)
	// if err != nil {
	// 	log.Fatal(err)
	// }
}
<commit_msg>add discover tool<commit_after>package main

import (
	"go/ast"
	"go/format"
	"go/parser"
	"go/token"
	"log"
	"net/http"
	"os"
	"text/template"
	"unicode"
)

const (
	raw = "https://raw.githubusercontent.com/amorwilliams/bodoni/master/lib/services/services.go"
)

func main() {
	if len(os.Args) <= 1 {
		return
	}
	resp, err := http.Get(raw)
	if err != nil {
		log.Fatal(err)
	}

	// parser
	fset := token.NewFileSet()
	f, err := parser.ParseFile(fset, "", resp.Body, 0)
	if err != nil {
		log.Fatal(err)
	}

	// remove Init function
LOOP:
	for k := range f.Decls {
		switch f.Decls[k].(type) {
		case *ast.FuncDecl:
			decl := f.Decls[k].(*ast.FuncDecl)
			if decl.Name.Name == "Init" {
				f.Decls = append(f.Decls[:k], f.Decls[k+1:]...)
				break LOOP
			}
		}
	}

	// create file
	out, err := os.Create("services.go")
	if err != nil {
		log.Fatal(err)
	}

	// rewrite
	format.Node(out, fset, f)

	// add stub
	funcMap := template.FuncMap{
		"Name": func(s string) string {
			a := []rune(s)
			a[0] = unicode.ToUpper(a[0])
			return string(a)
		},
	}
	tmpl, err := template.New("proto.tmpl").Funcs(funcMap).Parse(t)
	if err != nil {
		log.Fatal(err)
	}
	err = tmpl.Execute(out, os.Args[1:])
	if err != nil {
		log.Fatal(err)
	}
}

var t = `
// stubs generated by discover
// DO NOT EDIT!!!
{{range .}}
func GET{{Name .}}WithID(id string) *grpc.ClientConn {
	return defaultPool.getServiceWithID(defautlServicePath + "/{{.}}", id)
}
{{end}}
{{range .}}
func Get{{Name .}}() *grpc.ClientConn {
	return defaultPool.getService(defautlServicePath + "/{{.}}")
}
{{end}}

func Init() {
	var names []string
	{{range .}}names = append(names, "{{.}}"){{end}}
	defaultPool.init(names...)
}
`
<|endoftext|>


<commit_before>/*Package transforms imports all of the transforms that are available with PipeScript. The core PipeScript
only has an if statement and the identity operator, which are not nearly enough.

This package imports EVERYTHING
*/
package transforms

import (
	_ "github.com/connectordb/transforms/core" // The core transforms
)
<commit_msg>Fixed wrong import<commit_after>/*Package transforms imports all of the transforms that are available with PipeScript. The core PipeScript
only has an if statement and the identity operator, which are not nearly enough.

This package imports EVERYTHING
*/
package transforms

import (
	_ "github.com/connectordb/pipescript/transforms/core" // The core transforms
)
<|endoftext|>


<commit_before>package tumblr

import (
	"io/ioutil"
	"os"
	"testing"

	"github.com/joho/godotenv"
)

const (
	testBlog = "testBlog"
)

var post = Post{
	1234,
	"title",
	"url",
	"http://placehold.it/350x150",
	123,
}

func cleanup() {
	csvLocation := getCSVPath()
	os.Remove(csvLocation)
}

func TestReadPostsFromCSV(t *testing.T) {
	defer cleanup()
	dotenvPath := os.Getenv("ROOT_DIR") + "/.env"
	err := godotenv.Load(dotenvPath)
	if err != nil {
		t.Fail()
	}
	data := []byte("1234,title,url,http://placehold.it/350x150,123")
	err = ioutil.WriteFile(getCSVPath(), data, 0644)
	if err != nil {
		t.Fail()
	}
	posts := ReadPostsFromCSV()
	if len(posts) != 1 {
		t.Fail()
	}
	if posts[0].ID != 1234 {
		t.Fail()
	}
	if posts[0].Title != "title" {
		t.Fail()
	}
	if posts[0].URL != "url" {
		t.Fail()
	}
	if posts[0].Image != "http://placehold.it/350x150" {
		t.Fail()
	}
	if posts[0].Likes != 123 {
		t.Fail()
	}
}
<commit_msg>Switch csv_test to testify<commit_after>package tumblr

import (
	"io/ioutil"
	"os"
	"testing"

	"github.com/joho/godotenv"
	"github.com/stretchr/testify/assert"
)

const (
	testBlog = "testBlog"
)

var post = Post{
	1234,
	"title",
	"url",
	"http://placehold.it/350x150",
	123,
}

func cleanup() {
	csvLocation := getCSVPath()
	os.Remove(csvLocation)
}

func TestReadPostsFromCSV(t *testing.T) {
	defer cleanup()
	dotenvPath := os.Getenv("ROOT_DIR") + "/.env"
	err := godotenv.Load(dotenvPath)
	assert.NoError(t, err)

	data := []byte("1234,title,url,http://placehold.it/350x150,123")
	err = ioutil.WriteFile(getCSVPath(), data, 0644)
	assert.NoError(t, err)

	posts := ReadPostsFromCSV()
	assert.Equal(t, len(posts), 1)
	assert.Equal(t, posts[0].ID, int64(1234))
	assert.Equal(t, posts[0].Title, "title")
	assert.Equal(t, posts[0].URL, "url")
	assert.Equal(t, posts[0].Image, "http://placehold.it/350x150")
	assert.Equal(t, posts[0].Likes, int64(123))
}
<|endoftext|>


<commit_before>package qmp

import (
	"encoding/json"
	"fmt"
	"os"
	"strings"
	"sync"
	"time"

	"github.com/digitalocean/go-qemu/qmp"

	"github.com/lxc/lxd/shared"
)

var monitors = map[string]*Monitor{}
var monitorsLock sync.Mutex

// RingbufSize is the size of the agent serial ringbuffer in bytes
var RingbufSize = 16

// Monitor represents a QMP monitor.
type Monitor struct {
	path string
	qmp  *qmp.SocketMonitor

	agentReady    bool
	disconnected  bool
	chDisconnect  chan struct{}
	eventHandler  func(name string, data map[string]interface{})
	serialCharDev string
}

// Connect creates or retrieves an existing QMP monitor for the path.
func Connect(path string, serialCharDev string, eventHandler func(name string, data map[string]interface{})) (*Monitor, error) {
	monitorsLock.Lock()
	defer monitorsLock.Unlock()

	// Look for an existing monitor.
	monitor, ok := monitors[path]
	if ok {
		monitor.eventHandler = eventHandler
		return monitor, nil
	}

	// Setup the connection.
	qmpConn, err := qmp.NewSocketMonitor("unix", path, time.Second)
	if err != nil {
		return nil, err
	}

	err = qmpConn.Connect()
	if err != nil {
		return nil, err
	}

	// Setup the monitor struct.
	monitor = &Monitor{}
	monitor.path = path
	monitor.qmp = qmpConn
	monitor.chDisconnect = make(chan struct{}, 1)
	monitor.eventHandler = eventHandler
	monitor.serialCharDev = serialCharDev

	// Spawn goroutines.
	err = monitor.run()
	if err != nil {
		return nil, err
	}

	// Register in global map.
	monitors[path] = monitor

	return monitor, nil
}

func (m *Monitor) run() error {
	// Start ringbuffer monitoring go routine.
	go func() {
		for {
			// Read the ringbuffer.
			resp, err := m.qmp.Run([]byte(fmt.Sprintf(`{"execute": "ringbuf-read", "arguments": {"device": "%s", "size": %d, "format": "utf8"}}`, m.serialCharDev, RingbufSize)))
			if err != nil {
				m.Disconnect()
				return
			}

			// Decode the response.
			var respDecoded struct {
				Return string `json:"return"`
			}

			err = json.Unmarshal(resp, &respDecoded)
			if err != nil {
				continue
			}

			// Extract the last entry.
			entries := strings.Split(respDecoded.Return, "\n")
			if len(entries) > 1 {
				status := entries[len(entries)-2]

				if status == "STARTED" {
					m.agentReady = true
				} else if status == "STOPPED" {
					m.agentReady = false
				}
			}

			// Wait until next read or cancel.
			select {
			case <-m.chDisconnect:
				return
			case <-time.After(10 * time.Second):
				continue
			}
		}
	}()

	// Start event monitoring go routine.
	chEvents, err := m.qmp.Events()
	if err != nil {
		return err
	}

	go func() {
		for {
			select {
			case <-m.chDisconnect:
				return
			case e := <-chEvents:
				if e.Event == "" {
					continue
				}

				if m.eventHandler != nil {
					m.eventHandler(e.Event, e.Data)
				}
			}
		}
	}()

	return nil
}

// Wait returns a channel that will be closed on disconnection.
func (m *Monitor) Wait() (chan struct{}, error) {
	// Check if disconnected
	if m.disconnected {
		return nil, ErrMonitorDisconnect
	}

	return m.chDisconnect, nil
}

// Disconnect forces a disconnection from QEMU.
func (m *Monitor) Disconnect() {
	// Stop all go routines and disconnect from socket.
	if !m.disconnected {
		close(m.chDisconnect)
	}
	m.disconnected = true
	m.qmp.Disconnect()

	// Remove from the map.
	monitorsLock.Lock()
	defer monitorsLock.Unlock()
	delete(monitors, m.path)
}

// Status returns the current VM status.
func (m *Monitor) Status() (string, error) {
	// Check if disconnected
	if m.disconnected {
		return "", ErrMonitorDisconnect
	}

	// Query the status.
	respRaw, err := m.qmp.Run([]byte("{'execute': 'query-status'}"))
	if err != nil {
		m.Disconnect()
		return "", ErrMonitorDisconnect
	}

	// Process the response.
	var respDecoded struct {
		Return struct {
			Status string `json:"status"`
		} `json:"return"`
	}

	err = json.Unmarshal(respRaw, &respDecoded)
	if err != nil {
		return "", ErrMonitorBadReturn
	}

	return respDecoded.Return.Status, nil
}

// Console fetches the File for a particular console.
func (m *Monitor) Console(target string) (*os.File, error) {
	// Check if disconnected
	if m.disconnected {
		return nil, ErrMonitorDisconnect
	}

	// Query the consoles.
	respRaw, err := m.qmp.Run([]byte("{'execute': 'query-chardev'}"))
	if err != nil {
		m.Disconnect()
		return nil, ErrMonitorDisconnect
	}

	// Process the response.
	var respDecoded struct {
		Return []struct {
			Label    string `json:"label"`
			Filename string `json:"filename"`
		} `json:"return"`
	}

	err = json.Unmarshal(respRaw, &respDecoded)
	if err != nil {
		return nil, ErrMonitorBadReturn
	}

	// Look for the requested console.
	for _, v := range respDecoded.Return {
		if v.Label == target {
			ptyPath := strings.TrimPrefix(v.Filename, "pty:")

			if !shared.PathExists(ptyPath) {
				continue
			}

			// Open the PTS device
			console, err := os.OpenFile(ptyPath, os.O_RDWR, 0600)
			if err != nil {
				return nil, err
			}

			return console, nil
		}
	}

	return nil, ErrMonitorBadConsole
}

func (m *Monitor) runCmd(cmd string) error {
	// Check if disconnected
	if m.disconnected {
		return ErrMonitorDisconnect
	}

	// Query the status.
	_, err := m.qmp.Run([]byte(fmt.Sprintf("{'execute': '%s'}", cmd)))
	if err != nil {
		m.Disconnect()
		return ErrMonitorDisconnect
	}

	return nil
}

// Powerdown tells the VM to gracefully shutdown.
func (m *Monitor) Powerdown() error {
	return m.runCmd("system_powerdown")
}

// Start tells QEMU to start the emulation.
func (m *Monitor) Start() error {
	return m.runCmd("cont")
}

// Pause tells QEMU to temporarily stop the emulation.
func (m *Monitor) Pause() error {
	return m.runCmd("stop")
}

// Quit tells QEMU to exit immediately.
func (m *Monitor) Quit() error {
	return m.runCmd("quit")
}

// AgentReady indicates whether an agent has been detected.
func (m *Monitor) AgentReady() bool {
	return m.agentReady
}

// GetCPUs fetches the vCPU information for pinning.
func (m *Monitor) GetCPUs() ([]int, error) {
	// Check if disconnected
	if m.disconnected {
		return nil, ErrMonitorDisconnect
	}

	// Query the consoles.
	respRaw, err := m.qmp.Run([]byte("{'execute': 'query-cpus'}"))
	if err != nil {
		m.Disconnect()
		return nil, ErrMonitorDisconnect
	}

	// Process the response.
	var respDecoded struct {
		Return []struct {
			CPU int `json:"CPU"`
			PID int `json:"thread_id"`
		} `json:"return"`
	}

	err = json.Unmarshal(respRaw, &respDecoded)
	if err != nil {
		return nil, ErrMonitorBadReturn
	}

	// Make a slice of PIDs.
	pids := []int{}
	for _, cpu := range respDecoded.Return {
		pids = append(pids, cpu.PID)
	}

	return pids, nil
}

// GetBalloonSizeBytes returns the current size of the memory balloon in bytes.
func (m *Monitor) GetBalloonSizeBytes() (int64, error) {
	respRaw, err := m.qmp.Run([]byte("{'execute': 'query-balloon'}"))
	if err != nil {
		m.Disconnect()
		return -1, ErrMonitorDisconnect
	}

	// Process the response.
	var respDecoded struct {
		Return struct {
			Actual int64 `json:"actual"`
		} `json:"return"`
	}

	err = json.Unmarshal(respRaw, &respDecoded)
	if err != nil {
		return -1, ErrMonitorBadReturn
	}

	return respDecoded.Return.Actual, nil
}

// SetBalloonSizeBytes sets the size of the memory balloon in bytes.
func (m *Monitor) SetBalloonSizeBytes(sizeBytes int64) error {
	respRaw, err := m.qmp.Run([]byte(fmt.Sprintf("{'execute': 'balloon', 'arguments': {'value': %d}}", sizeBytes)))
	if err != nil {
		m.Disconnect()
		return ErrMonitorDisconnect
	}

	if string(respRaw) != `{"return": {}}` {
		return ErrMonitorBadReturn
	}

	return nil
}
<commit_msg>lxd/instance/drivers/qmp/monitor: Renames GetMemoryBalloonSizeBytes<commit_after>package qmp

import (
	"encoding/json"
	"fmt"
	"os"
	"strings"
	"sync"
	"time"

	"github.com/digitalocean/go-qemu/qmp"

	"github.com/lxc/lxd/shared"
)

var monitors = map[string]*Monitor{}
var monitorsLock sync.Mutex

// RingbufSize is the size of the agent serial ringbuffer in bytes
var RingbufSize = 16

// Monitor represents a QMP monitor.
type Monitor struct {
	path string
	qmp  *qmp.SocketMonitor

	agentReady    bool
	disconnected  bool
	chDisconnect  chan struct{}
	eventHandler  func(name string, data map[string]interface{})
	serialCharDev string
}

// Connect creates or retrieves an existing QMP monitor for the path.
func Connect(path string, serialCharDev string, eventHandler func(name string, data map[string]interface{})) (*Monitor, error) {
	monitorsLock.Lock()
	defer monitorsLock.Unlock()

	// Look for an existing monitor.
	monitor, ok := monitors[path]
	if ok {
		monitor.eventHandler = eventHandler
		return monitor, nil
	}

	// Setup the connection.
	qmpConn, err := qmp.NewSocketMonitor("unix", path, time.Second)
	if err != nil {
		return nil, err
	}

	err = qmpConn.Connect()
	if err != nil {
		return nil, err
	}

	// Setup the monitor struct.
	monitor = &Monitor{}
	monitor.path = path
	monitor.qmp = qmpConn
	monitor.chDisconnect = make(chan struct{}, 1)
	monitor.eventHandler = eventHandler
	monitor.serialCharDev = serialCharDev

	// Spawn goroutines.
	err = monitor.run()
	if err != nil {
		return nil, err
	}

	// Register in global map.
	monitors[path] = monitor

	return monitor, nil
}

func (m *Monitor) run() error {
	// Start ringbuffer monitoring go routine.
	go func() {
		for {
			// Read the ringbuffer.
			resp, err := m.qmp.Run([]byte(fmt.Sprintf(`{"execute": "ringbuf-read", "arguments": {"device": "%s", "size": %d, "format": "utf8"}}`, m.serialCharDev, RingbufSize)))
			if err != nil {
				m.Disconnect()
				return
			}

			// Decode the response.
			var respDecoded struct {
				Return string `json:"return"`
			}

			err = json.Unmarshal(resp, &respDecoded)
			if err != nil {
				continue
			}

			// Extract the last entry.
			entries := strings.Split(respDecoded.Return, "\n")
			if len(entries) > 1 {
				status := entries[len(entries)-2]

				if status == "STARTED" {
					m.agentReady = true
				} else if status == "STOPPED" {
					m.agentReady = false
				}
			}

			// Wait until next read or cancel.
			select {
			case <-m.chDisconnect:
				return
			case <-time.After(10 * time.Second):
				continue
			}
		}
	}()

	// Start event monitoring go routine.
	chEvents, err := m.qmp.Events()
	if err != nil {
		return err
	}

	go func() {
		for {
			select {
			case <-m.chDisconnect:
				return
			case e := <-chEvents:
				if e.Event == "" {
					continue
				}

				if m.eventHandler != nil {
					m.eventHandler(e.Event, e.Data)
				}
			}
		}
	}()

	return nil
}

// Wait returns a channel that will be closed on disconnection.
func (m *Monitor) Wait() (chan struct{}, error) {
	// Check if disconnected
	if m.disconnected {
		return nil, ErrMonitorDisconnect
	}

	return m.chDisconnect, nil
}

// Disconnect forces a disconnection from QEMU.
func (m *Monitor) Disconnect() {
	// Stop all go routines and disconnect from socket.
	if !m.disconnected {
		close(m.chDisconnect)
	}
	m.disconnected = true
	m.qmp.Disconnect()

	// Remove from the map.
	monitorsLock.Lock()
	defer monitorsLock.Unlock()
	delete(monitors, m.path)
}

// Status returns the current VM status.
func (m *Monitor) Status() (string, error) {
	// Check if disconnected
	if m.disconnected {
		return "", ErrMonitorDisconnect
	}

	// Query the status.
	respRaw, err := m.qmp.Run([]byte("{'execute': 'query-status'}"))
	if err != nil {
		m.Disconnect()
		return "", ErrMonitorDisconnect
	}

	// Process the response.
	var respDecoded struct {
		Return struct {
			Status string `json:"status"`
		} `json:"return"`
	}

	err = json.Unmarshal(respRaw, &respDecoded)
	if err != nil {
		return "", ErrMonitorBadReturn
	}

	return respDecoded.Return.Status, nil
}

// Console fetches the File for a particular console.
func (m *Monitor) Console(target string) (*os.File, error) {
	// Check if disconnected
	if m.disconnected {
		return nil, ErrMonitorDisconnect
	}

	// Query the consoles.
	respRaw, err := m.qmp.Run([]byte("{'execute': 'query-chardev'}"))
	if err != nil {
		m.Disconnect()
		return nil, ErrMonitorDisconnect
	}

	// Process the response.
	var respDecoded struct {
		Return []struct {
			Label    string `json:"label"`
			Filename string `json:"filename"`
		} `json:"return"`
	}

	err = json.Unmarshal(respRaw, &respDecoded)
	if err != nil {
		return nil, ErrMonitorBadReturn
	}

	// Look for the requested console.
	for _, v := range respDecoded.Return {
		if v.Label == target {
			ptyPath := strings.TrimPrefix(v.Filename, "pty:")

			if !shared.PathExists(ptyPath) {
				continue
			}

			// Open the PTS device
			console, err := os.OpenFile(ptyPath, os.O_RDWR, 0600)
			if err != nil {
				return nil, err
			}

			return console, nil
		}
	}

	return nil, ErrMonitorBadConsole
}

func (m *Monitor) runCmd(cmd string) error {
	// Check if disconnected
	if m.disconnected {
		return ErrMonitorDisconnect
	}

	// Query the status.
	_, err := m.qmp.Run([]byte(fmt.Sprintf("{'execute': '%s'}", cmd)))
	if err != nil {
		m.Disconnect()
		return ErrMonitorDisconnect
	}

	return nil
}

// Powerdown tells the VM to gracefully shutdown.
func (m *Monitor) Powerdown() error {
	return m.runCmd("system_powerdown")
}

// Start tells QEMU to start the emulation.
func (m *Monitor) Start() error {
	return m.runCmd("cont")
}

// Pause tells QEMU to temporarily stop the emulation.
func (m *Monitor) Pause() error {
	return m.runCmd("stop")
}

// Quit tells QEMU to exit immediately.
func (m *Monitor) Quit() error {
	return m.runCmd("quit")
}

// AgentReady indicates whether an agent has been detected.
func (m *Monitor) AgentReady() bool {
	return m.agentReady
}

// GetCPUs fetches the vCPU information for pinning.
func (m *Monitor) GetCPUs() ([]int, error) {
	// Check if disconnected
	if m.disconnected {
		return nil, ErrMonitorDisconnect
	}

	// Query the consoles.
	respRaw, err := m.qmp.Run([]byte("{'execute': 'query-cpus'}"))
	if err != nil {
		m.Disconnect()
		return nil, ErrMonitorDisconnect
	}

	// Process the response.
	var respDecoded struct {
		Return []struct {
			CPU int `json:"CPU"`
			PID int `json:"thread_id"`
		} `json:"return"`
	}

	err = json.Unmarshal(respRaw, &respDecoded)
	if err != nil {
		return nil, ErrMonitorBadReturn
	}

	// Make a slice of PIDs.
	pids := []int{}
	for _, cpu := range respDecoded.Return {
		pids = append(pids, cpu.PID)
	}

	return pids, nil
}

// GetMemoryBalloonSizeBytes returns effective size of the memory in bytes (considering the current balloon size).
func (m *Monitor) GetMemoryBalloonSizeBytes() (int64, error) {
	respRaw, err := m.qmp.Run([]byte("{'execute': 'query-balloon'}"))
	if err != nil {
		m.Disconnect()
		return -1, ErrMonitorDisconnect
	}

	// Process the response.
	var respDecoded struct {
		Return struct {
			Actual int64 `json:"actual"`
		} `json:"return"`
	}

	err = json.Unmarshal(respRaw, &respDecoded)
	if err != nil {
		return -1, ErrMonitorBadReturn
	}

	return respDecoded.Return.Actual, nil
}

// SetBalloonSizeBytes sets the size of the memory balloon in bytes.
func (m *Monitor) SetBalloonSizeBytes(sizeBytes int64) error {
	respRaw, err := m.qmp.Run([]byte(fmt.Sprintf("{'execute': 'balloon', 'arguments': {'value': %d}}", sizeBytes)))
	if err != nil {
		m.Disconnect()
		return ErrMonitorDisconnect
	}

	if string(respRaw) != `{"return": {}}` {
		return ErrMonitorBadReturn
	}

	return nil
}
<|endoftext|>


<commit_before>package definition

type tree struct {
	root Resource
}

func NewTree(kv_resources []map[interface{}]interface{}) *tree {
	name := "."
	id := name
	resource := &Directory{
		name:     name,
		id:       id,
		children: generate(id, kv_resources),
	}
	return &tree{root: resource}
}

// Traverse public method
func (t *tree) Traverse(action func(r Resource)) {
	traverse(t.root, action)
}

// Traverse the tree and yield each node to a function
func traverse(r Resource, action func(r Resource)) {
	if r.Children() == nil {
		return
	}

	for _, node := range r.Children() {
		action(node)
		traverse(node, action)
	}
}

// Generates a Resource hierarchy
func generate(resource_id string, kv_resources []map[interface{}]interface{}) []Resource {
	var resources []Resource
	for _, resource := range kv_resources {
		for key, data := range resource {
			if key == "dir" {
				a_data := data.(map[interface{}]interface{})
				name := a_data["name"].(string)
				id := resource_id + "/" + name

				dir_resources := []map[interface{}]interface{}{
					a_data,
				}

				resources = append(resources, &Directory{
					name:     name,
					id:       id,
					children: generate(id, dir_resources),
				})

			} else if key == "files" {
				a_data := data.([]interface{})
				files := getFileResources(resource_id, filesStringify(a_data))
				resources = append(resources, files...)
			}
		}
	}
	return resources
}

// Convert a []string to []Resource
func getFileResources(resource_id string, file_names []string) []Resource {
	var resources []Resource
	for _, file := range file_names {
		id := resource_id + "/" + file
		resources = append(resources, &File{
			name: file,
			id:   id,
		})
	}
	return resources
}

// Convert a []interface{} to []string
func filesStringify(file_names []interface{}) []string {
	var files []string
	for _, file_name := range file_names {

		files = append(files, file_name.(string))
	}
	return files
}
<commit_msg>Pass definition context when creating a new tree Improved variable naming<commit_after>package definition

type tree struct {
	root Resource
}

// Creates a definition tree structure
func newTree(context string, definition_resources []map[interface{}]interface{}) *tree {
	resource := &Directory{
		name:     context,
		id:       context,
		children: generate(context, definition_resources),
	}
	return &tree{root: resource}
}

// Traverse the tree and yield each node to a function
func (t *tree) Traverse(action func(r Resource)) {
	traverse(t.root, action)
}

// Traverse the tree and yield each node to a function
func traverse(r Resource, action func(r Resource)) {
	if r.Children() == nil {
		return
	}

	for _, node := range r.Children() {
		action(node)
		traverse(node, action)
	}
}

// Generates a definition Resource hierarchy
func generate(resource_id string, definition_resources []map[interface{}]interface{}) []Resource {
	var resources []Resource
	for _, resource := range definition_resources {
		for key, data := range resource {
			if key == "dir" {
				a_data := data.(map[interface{}]interface{})
				name := a_data["name"].(string)
				id := resource_id + "/" + name

				dir_resources := []map[interface{}]interface{}{
					a_data,
				}

				resources = append(resources, &Directory{
					name:     name,
					id:       id,
					children: generate(id, dir_resources),
				})

			} else if key == "files" {
				a_data := data.([]interface{})
				files := getFileResources(resource_id, filesStringify(a_data))
				resources = append(resources, files...)
			}
		}
	}
	return resources
}

// Convert a []string to []Resource
func getFileResources(resource_id string, file_names []string) []Resource {
	var resources []Resource
	for _, file := range file_names {
		id := resource_id + "/" + file
		resources = append(resources, &File{
			name: file,
			id:   id,
		})
	}
	return resources
}

// Convert a []interface{} to []string
func filesStringify(file_names []interface{}) []string {
	var files []string
	for _, file_name := range file_names {
		files = append(files, file_name.(string))
	}
	return files
}
<|endoftext|>