<commit_before>package ramsql

import (
	"database/sql/driver"
	"fmt"
	"regexp"
	"strconv"
	"strings"

	"github.com/proullon/ramsql/engine/log"
)

// Stmt implements the Statement interface of sql/driver
type Stmt struct {
	conn     *Conn
	query    string
	numInput int
}

func countArguments(query string) int {
	for id := 1; id > 0; id++ {
		sep := fmt.Sprintf("$%d", id)
		if strings.Count(query, sep) == 0 {
			return id - 1
		}
	}

	return -1
}

func prepareStatement(c *Conn, query string) *Stmt {

	// Parse number of arguments here
	// Should handler either Postgres ($*) or ODBC (?) parameter markers
	numInput := strings.Count(query, "?")
	// if numInput == 0, maybe it's Postgres format
	if numInput == 0 {
		numInput = countArguments(query)
	}

	// Create statement
	stmt := &Stmt{
		conn:     c,
		query:    query,
		numInput: numInput,
	}

	stmt.conn.mutex.Lock()
	return stmt
}

// Close closes the statement.
//
// As of Go 1.1, a Stmt will not be closed if it's in use
// by any queries.
func (s *Stmt) Close() error {
	return fmt.Errorf("Not implemented.")
}

// NumInput returns the number of placeholder parameters.
//
// If NumInput returns >= 0, the sql package will sanity check
// argument counts from callers and return errors to the caller
// before the statement's Exec or Query methods are called.
//
// NumInput may also return -1, if the driver doesn't know
// its number of placeholders. In that case, the sql package
// will not sanity check Exec or Query argument counts.
func (s *Stmt) NumInput() int {
	return s.numInput
}

// Exec executes a query that doesn't return rows, such
// as an INSERT or UPDATE.
func (s *Stmt) Exec(args []driver.Value) (driver.Result, error) {
	defer s.conn.mutex.Unlock()
	var finalQuery string

	// replace $* by arguments in query string
	finalQuery = replaceArguments(s.query, args)
	log.Info("Exec <%s>\n", finalQuery)

	// Send query to server
	err := s.conn.conn.WriteExec(finalQuery)
	if err != nil {
		log.Warning("Exec: Cannot send query to server: %s", err)
		return nil, fmt.Errorf("Cannot send query to server: %s", err)
	}

	// Get answer from server
	lastInsertedID, rowsAffected, err := s.conn.conn.ReadResult()
	if err != nil {
		return nil, err
	}

	// Create a driver.Result
	return newResult(lastInsertedID, rowsAffected), nil
}

// Query executes a query that may return rows, such as a
// SELECT.
func (s *Stmt) Query(args []driver.Value) (driver.Rows, error) {
	defer s.conn.mutex.Unlock()

	finalQuery := replaceArguments(s.query, args)
	log.Info("Query <%s>\n", finalQuery)
	err := s.conn.conn.WriteQuery(finalQuery)
	if err != nil {
		return nil, err
	}

	rowsChannel, err := s.conn.conn.ReadRows()
	if err != nil {
		return nil, err
	}

	r := newRows(rowsChannel)
	return r, nil
}

// replace $* by arguments in query string
func replaceArguments(query string, args []driver.Value) string {

	holder := regexp.MustCompile(`[^\$]\$[0-9]+`)
	replacedQuery := ""

	if strings.Count(query, "?") == len(args) {
		return replaceArgumentsODBC(query, args)
	}

	allloc := holder.FindAllIndex([]byte(query), -1)
	queryB := []byte(query)
	for i, loc := range allloc {
		match := queryB[loc[0]+1 : loc[1]]

		index, err := strconv.Atoi(string(match[1:]))
		if err != nil {
			log.Warning("Matched %s as a placeholder but cannot get index: %s\n", match, err)
			return query
		}

		var v string
		if args[index-1] == nil {
			v = "null"
		} else {
			v = fmt.Sprintf("$$%v$$", args[index-1])
		}
		if i == 0 {
			replacedQuery = fmt.Sprintf("%s%s%s", replacedQuery, string(queryB[:loc[0]+1]), v)
		} else {
			replacedQuery = fmt.Sprintf("%s%s%s", replacedQuery, string(queryB[allloc[i-1][1]:loc[0]+1]), v)
		}
	}
	// add remaining query
	replacedQuery = fmt.Sprintf("%s%s", replacedQuery, string(queryB[allloc[len(allloc)-1][1]:]))

	return replacedQuery
}

func replaceArgumentsODBC(query string, args []driver.Value) string {
	var finalQuery string

	queryParts := strings.Split(query, "?")
	finalQuery = queryParts[0]
	for i := range args {
		arg := fmt.Sprintf("%v", args[i])
		_, ok := args[i].(string)
		if ok && !strings.HasSuffix(query, "'") {
			arg = "$$" + arg + "$$"
		}
		finalQuery += arg
		finalQuery += queryParts[i+1]
	}

	return finalQuery
}
<commit_msg>fix (driver): prevent panic<commit_after>package ramsql

import (
	"database/sql/driver"
	"fmt"
	"regexp"
	"strconv"
	"strings"

	"github.com/proullon/ramsql/engine/log"
)

// Stmt implements the Statement interface of sql/driver
type Stmt struct {
	conn     *Conn
	query    string
	numInput int
}

func countArguments(query string) int {
	for id := 1; id > 0; id++ {
		sep := fmt.Sprintf("$%d", id)
		if strings.Count(query, sep) == 0 {
			return id - 1
		}
	}

	return -1
}

func prepareStatement(c *Conn, query string) *Stmt {

	// Parse number of arguments here
	// Should handler either Postgres ($*) or ODBC (?) parameter markers
	numInput := strings.Count(query, "?")
	// if numInput == 0, maybe it's Postgres format
	if numInput == 0 {
		numInput = countArguments(query)
	}

	// Create statement
	stmt := &Stmt{
		conn:     c,
		query:    query,
		numInput: numInput,
	}

	stmt.conn.mutex.Lock()
	return stmt
}

// Close closes the statement.
//
// As of Go 1.1, a Stmt will not be closed if it's in use
// by any queries.
func (s *Stmt) Close() error {
	return fmt.Errorf("Not implemented.")
}

// NumInput returns the number of placeholder parameters.
//
// If NumInput returns >= 0, the sql package will sanity check
// argument counts from callers and return errors to the caller
// before the statement's Exec or Query methods are called.
//
// NumInput may also return -1, if the driver doesn't know
// its number of placeholders. In that case, the sql package
// will not sanity check Exec or Query argument counts.
func (s *Stmt) NumInput() int {
	return s.numInput
}

// Exec executes a query that doesn't return rows, such
// as an INSERT or UPDATE.
func (s *Stmt) Exec(args []driver.Value) (r driver.Result, err error) {
	defer func() {
		if r := recover(); r != nil {
			err = fmt.Errorf("fatalf error: %s", r)
			return
		}
	}()
	defer s.conn.mutex.Unlock()

	var finalQuery string

	// replace $* by arguments in query string
	finalQuery = replaceArguments(s.query, args)
	log.Info("Exec <%s>\n", finalQuery)

	// Send query to server
	err = s.conn.conn.WriteExec(finalQuery)
	if err != nil {
		log.Warning("Exec: Cannot send query to server: %s", err)
		return nil, fmt.Errorf("Cannot send query to server: %s", err)
	}

	// Get answer from server
	lastInsertedID, rowsAffected, err := s.conn.conn.ReadResult()
	if err != nil {
		return nil, err
	}

	// Create a driver.Result
	return newResult(lastInsertedID, rowsAffected), nil
}

// Query executes a query that may return rows, such as a
// SELECT.
func (s *Stmt) Query(args []driver.Value) (r driver.Rows, err error) {
	defer func() {
		if r := recover(); r != nil {
			err = fmt.Errorf("fatalf error: %s", r)
			return
		}
	}()
	defer s.conn.mutex.Unlock()

	finalQuery := replaceArguments(s.query, args)
	log.Info("Query <%s>\n", finalQuery)
	err = s.conn.conn.WriteQuery(finalQuery)
	if err != nil {
		return nil, err
	}

	rowsChannel, err := s.conn.conn.ReadRows()
	if err != nil {
		return nil, err
	}

	r = newRows(rowsChannel)
	return r, nil
}

// replace $* by arguments in query string
func replaceArguments(query string, args []driver.Value) string {

	holder := regexp.MustCompile(`[^\$]\$[0-9]+`)
	replacedQuery := ""

	if strings.Count(query, "?") == len(args) {
		return replaceArgumentsODBC(query, args)
	}

	allloc := holder.FindAllIndex([]byte(query), -1)
	queryB := []byte(query)
	for i, loc := range allloc {
		match := queryB[loc[0]+1 : loc[1]]

		index, err := strconv.Atoi(string(match[1:]))
		if err != nil {
			log.Warning("Matched %s as a placeholder but cannot get index: %s\n", match, err)
			return query
		}

		var v string
		if args[index-1] == nil {
			v = "null"
		} else {
			v = fmt.Sprintf("$$%v$$", args[index-1])
		}
		if i == 0 {
			replacedQuery = fmt.Sprintf("%s%s%s", replacedQuery, string(queryB[:loc[0]+1]), v)
		} else {
			replacedQuery = fmt.Sprintf("%s%s%s", replacedQuery, string(queryB[allloc[i-1][1]:loc[0]+1]), v)
		}
	}
	// add remaining query
	replacedQuery = fmt.Sprintf("%s%s", replacedQuery, string(queryB[allloc[len(allloc)-1][1]:]))

	return replacedQuery
}

func replaceArgumentsODBC(query string, args []driver.Value) string {
	var finalQuery string

	queryParts := strings.Split(query, "?")
	finalQuery = queryParts[0]
	for i := range args {
		arg := fmt.Sprintf("%v", args[i])
		_, ok := args[i].(string)
		if ok && !strings.HasSuffix(query, "'") {
			arg = "$$" + arg + "$$"
		}
		finalQuery += arg
		finalQuery += queryParts[i+1]
	}

	return finalQuery
}
<|endoftext|>


<commit_before>/*******************************************************************************
The MIT License (MIT)

Copyright (c) 2013-2014 Hajime Nakagami

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*******************************************************************************/

package firebirdsql

import (
	"database/sql"
	"testing"
	"time"
)

func TestBasic(t *testing.T) {
	conn, err := sql.Open("firebirdsql_createdb", "sysdba:masterkey@localhost:3050/tmp/go_test_basic.fdb")
	defer conn.Close()

	if err != nil {
		t.Fatalf("Error connecting: %v", err)
	}
	var sql string
	var n int

	sql = "SELECT Count(*) FROM rdb$relations where rdb$relation_name='FOO'"
	err = conn.QueryRow(sql).Scan(&n)
	if err != nil {
		t.Fatalf("Error QueryRow: %v", err)
	}
	if n > 0 {
		conn.Exec("DROP TABLE foo")
	}

	sql = `
        CREATE TABLE foo (
            a INTEGER NOT NULL,
            b VARCHAR(30) NOT NULL UNIQUE,
            c VARCHAR(1024),
            d DECIMAL(16,3) DEFAULT -0.123,
            e DATE DEFAULT '1967-08-11',
            f TIMESTAMP DEFAULT '1967-08-11 23:45:01',
            g TIME DEFAULT '23:45:01',
            h BLOB SUB_TYPE 1,
            i DOUBLE PRECISION DEFAULT 0.0,
            j FLOAT DEFAULT 0.0,
            PRIMARY KEY (a),
            CONSTRAINT CHECK_A CHECK (a <> 0)
        )
    `
	conn.Exec(sql)
	_, err = conn.Exec("CREATE TABLE foo (a INTEGER)")
	if err == nil {
		t.Fatalf("Need metadata update error")
	}
	if err.Error() != "unsuccessful metadata update\nTable FOO already exists\n" {
		t.Fatalf("Bad message:%v", err.Error())
	}

	// 3 records insert
	conn.Exec("insert into foo(a, b, c,h) values (1, 'a', 'b','This is a memo')")
	conn.Exec("insert into foo(a, b, c, e, g, i, j) values (2, 'A', 'B', '1999-01-25', '00:00:01', 0.1, 0.1)")
	conn.Exec("insert into foo(a, b, c, e, g, i, j) values (3, 'X', 'Y', '2001-07-05', '00:01:02', 0.2, 0.2)")

	err = conn.QueryRow("select count(*) cnt from foo").Scan(&n)
	if err != nil {
		t.Fatalf("Error QueryRow: %v", err)
	}
	if n != 3 {
		t.Fatalf("Error bad record count: %v", n)
	}

	rows, err := conn.Query("select a, b, c, d, e, f, g, i, j from foo")
	var a int
	var b, c string
	var d float64
	var e time.Time
	var f time.Time
	var g time.Time
	var i float64
	var j float32

	for rows.Next() {
		rows.Scan(&a, &b, &c, &d, &e, &f, &g, &i, &j)
	}

	stmt, _ := conn.Prepare("select count(*) from foo where a=? and b=? and d=? and e=? and f=? and g=?")
	ep := time.Date(1967, 8, 11, 0, 0, 0, 0, time.UTC)
	fp := time.Date(1967, 8, 11, 23, 45, 1, 0, time.UTC)
	gp, err := time.Parse("15:04:05", "23:45:01")
	err = stmt.QueryRow(1, "a", -0.123, ep, fp, gp).Scan(&n)
	if err != nil {
		t.Fatalf("Error QueryRow: %v", err)
	}
	if n != 1 {
		t.Fatalf("Error bad record count: %v", n)
	}
}

func TestReturning(t *testing.T) {
	conn, _ := sql.Open("firebirdsql_createdb", "SYSDBA:masterkey@localhost:3050/tmp/go_test_returning.fdb")
	defer conn.Close()

	conn.Exec(`
        CREATE TABLE test_returning (
            f1 integer NOT NULL,
            f2 integer default 2,
            f3 varchar(20) default 'abc')`)
	for i := 0; i < 2; i++ {

		rows, err := conn.Query("INSERT INTO test_returning (f1) values (1) returning f2, f3")
		if err != nil {
			t.Fatalf("Error Insert returning : %v", err)
		}
		var f2 int
		var f3 string
		rows.Next()
		rows.Scan(&f2, &f3)
		if f2 != 2 || f3 != "abc" {
			t.Fatalf("Bad value insert returning: %v,%v", f2, f3)
		}
	}

}

func TestIssue2(t *testing.T) {
	conn, _ := sql.Open("firebirdsql_createdb", "sysdba:masterkey@localhost:3050/tmp/go_test_issue2.fdb")

	_, err := conn.Exec(`
        CREATE TABLE test_issue2
         (f1 integer NOT NULL,
          f2 integer,
          f3 integer NOT NULL,
          f4 integer NOT NULL,
          f5 integer NOT NULL,
          f6 integer NOT NULL,
          f7 varchar(255) NOT NULL,
          f8 varchar(255) NOT NULL,
          f9 varchar(255) NOT NULL,
          f10 varchar(255) NOT NULL,
          f11 varchar(255) NOT NULL,
          f12 varchar(255) NOT NULL,
          f13 varchar(255) NOT NULL,
          f14 varchar(255) NOT NULL,
          f15 integer,
          f16 integer,
          f17 integer,
          f18 integer,
          f19 integer,
          f20 integer,
          f21 integer,
          f22 varchar(1),
          f23 varchar(255),
          f24 integer,
          f25 varchar(64),
          f26 integer)`)
	defer conn.Close()
	if err != nil {
		t.Fatalf("Error Create Table: %v", err)
	}

	_, err = conn.Exec(`
        INSERT INTO test_issue2 VALUES
        (1, 2, 3, 4, 5, 6, '7', '8', '9', '10', '11', '12', '13', '14',
          15, 16, 17, 18, 19, 20, 21, 'A', '23', 24, '25', '26')`)
	if err != nil {
		t.Fatalf("Error Insert: %v", err)
	}

	rows, err := conn.Query("SELECT * FROM test_issue2")
	if err != nil {
		t.Fatalf("Error Query: %v", err)
	}
	for rows.Next() {
	}
}

func TestIssue3(t *testing.T) {
	conn, _ := sql.Open("firebirdsql_createdb", "sysdba:masterkey@localhost:3050/tmp/go_test_issue3.fdb")
	too_many := 401

	conn.Exec("CREATE TABLE test_issue3 (f1 integer NOT NULL)")
	defer conn.Close()
	stmt, _ := conn.Prepare("INSERT INTO test_issue3 values (?)")
	for i := 0; i < too_many; i++ {
		stmt.Exec(i + 1)
	}

	rows, _ := conn.Query("SELECT * FROM test_issue3 ORDER BY f1")
	i := 0
	var n int
	for rows.Next() {
		rows.Scan(&n)
		i++
		if i != n {
			t.Fatalf("Error %v != %v", n, i)
		}
	}
	if i != too_many {
		t.Fatalf("Can't get all %v records. only %v", too_many, i)
	}
}

func TestError(t *testing.T) {
	conn, err := sql.Open("firebirdsql_createdb", "sysdba:masterkey@localhost:3050/tmp/go_test_error.fdb")
	if err != nil {
		t.Fatalf("Error connecting: %v", err)
	}
	_, err = conn.Exec("incorrect sql statement")
	if err == nil || err.Error() != "Dynamic SQL Error\nSQL error code = -104\nToken unknown - line 1, column 1\nincorrect\n" {
		t.Fatalf("Incorrect error")
	}
}

/*
func TestFB3(t *testing.T) {
	conn, err := sql.Open("firebirdsql_createdb", "sysdba:masterkey@localhost:3050/tmp/go_test_fb3.fdb")
	if err != nil {
		t.Fatalf("Error connecting: %v", err)
	}
	var sql string
	var n int

	sql = "SELECT Count(*) FROM rdb$relations where rdb$relation_name='TEST_FB3'"
	err = conn.QueryRow(sql).Scan(&n)
	if err != nil {
		t.Fatalf("Error QueryRow: %v", err)
	}
	if n > 0 {
		conn.Exec("DROP TABLE test_fb3")
	}

	sql = `
        CREATE TABLE test_fb3 (
            b BOOLEAN
        )
    `
	conn.Exec(sql)
	conn.Exec("insert into test_fb3(b) values (true)")
	conn.Exec("insert into test_fb3(b) values (false)")
    var b bool
	err = conn.QueryRow("select * from test_fb3 where b is true").Scan(&b)
	if err != nil {
		t.Fatalf("Error QueryRow: %v", err)
	}
	if b != true{
		conn.Exec("Invalid boolean value")
	}
	err = conn.QueryRow("select * from test_fb3 where b is false").Scan(&b)
	if err != nil {
		t.Fatalf("Error QueryRow: %v", err)
	}
	if b != false{
		conn.Exec("Invalid boolean value")
	}

	stmt, _ := conn.Prepare("select * from test_fb3 where b=?")
	err = stmt.QueryRow(true).Scan(&b)
	if err != nil {
		t.Fatalf("Error QueryRow: %v", err)
	}
	if b != false{
		conn.Exec("Invalid boolean value")
	}

	defer conn.Close()
}
*/
<commit_msg>'firebirdsql_createdb' driver Can't call Query() multi time. So Please use 'firebirdsql' driver #5<commit_after>/*******************************************************************************
The MIT License (MIT)

Copyright (c) 2013-2014 Hajime Nakagami

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*******************************************************************************/

package firebirdsql

import (
	"database/sql"
	"testing"
	"time"
)

func TestBasic(t *testing.T) {
	conn, err := sql.Open("firebirdsql_createdb", "sysdba:masterkey@localhost:3050/tmp/go_test_basic.fdb")
	defer conn.Close()

	if err != nil {
		t.Fatalf("Error connecting: %v", err)
	}
	var sql string
	var n int

	sql = "SELECT Count(*) FROM rdb$relations where rdb$relation_name='FOO'"
	err = conn.QueryRow(sql).Scan(&n)
	if err != nil {
		t.Fatalf("Error QueryRow: %v", err)
	}
	if n > 0 {
		conn.Exec("DROP TABLE foo")
	}

	sql = `
        CREATE TABLE foo (
            a INTEGER NOT NULL,
            b VARCHAR(30) NOT NULL UNIQUE,
            c VARCHAR(1024),
            d DECIMAL(16,3) DEFAULT -0.123,
            e DATE DEFAULT '1967-08-11',
            f TIMESTAMP DEFAULT '1967-08-11 23:45:01',
            g TIME DEFAULT '23:45:01',
            h BLOB SUB_TYPE 1,
            i DOUBLE PRECISION DEFAULT 0.0,
            j FLOAT DEFAULT 0.0,
            PRIMARY KEY (a),
            CONSTRAINT CHECK_A CHECK (a <> 0)
        )
    `
	conn.Exec(sql)
	_, err = conn.Exec("CREATE TABLE foo (a INTEGER)")
	if err == nil {
		t.Fatalf("Need metadata update error")
	}
	if err.Error() != "unsuccessful metadata update\nTable FOO already exists\n" {
		t.Fatalf("Bad message:%v", err.Error())
	}

	// 3 records insert
	conn.Exec("insert into foo(a, b, c,h) values (1, 'a', 'b','This is a memo')")
	conn.Exec("insert into foo(a, b, c, e, g, i, j) values (2, 'A', 'B', '1999-01-25', '00:00:01', 0.1, 0.1)")
	conn.Exec("insert into foo(a, b, c, e, g, i, j) values (3, 'X', 'Y', '2001-07-05', '00:01:02', 0.2, 0.2)")

	err = conn.QueryRow("select count(*) cnt from foo").Scan(&n)
	if err != nil {
		t.Fatalf("Error QueryRow: %v", err)
	}
	if n != 3 {
		t.Fatalf("Error bad record count: %v", n)
	}

	rows, err := conn.Query("select a, b, c, d, e, f, g, i, j from foo")
	var a int
	var b, c string
	var d float64
	var e time.Time
	var f time.Time
	var g time.Time
	var i float64
	var j float32

	for rows.Next() {
		rows.Scan(&a, &b, &c, &d, &e, &f, &g, &i, &j)
	}

	stmt, _ := conn.Prepare("select count(*) from foo where a=? and b=? and d=? and e=? and f=? and g=?")
	ep := time.Date(1967, 8, 11, 0, 0, 0, 0, time.UTC)
	fp := time.Date(1967, 8, 11, 23, 45, 1, 0, time.UTC)
	gp, err := time.Parse("15:04:05", "23:45:01")
	err = stmt.QueryRow(1, "a", -0.123, ep, fp, gp).Scan(&n)
	if err != nil {
		t.Fatalf("Error QueryRow: %v", err)
	}
	if n != 1 {
		t.Fatalf("Error bad record count: %v", n)
	}
}

func TestReturning(t *testing.T) {
	conn, _ := sql.Open("firebirdsql_createdb", "SYSDBA:masterkey@localhost:3050/tmp/go_test_returning.fdb")
	defer conn.Close()

	conn.Exec(`
        CREATE TABLE test_returning (
            f1 integer NOT NULL,
            f2 integer default 2,
            f3 varchar(20) default 'abc')`)
	conn.Close()

	conn, _ = sql.Open("firebirdsql", "SYSDBA:masterkey@localhost:3050/tmp/go_test_returning.fdb")

	for i := 0; i < 2; i++ {

		rows, err := conn.Query("INSERT INTO test_returning (f1) values (1) returning f2, f3")
		if err != nil {
			t.Fatalf("Error Insert returning : %v", err)
		}
		var f2 int
		var f3 string
		rows.Next()
		rows.Scan(&f2, &f3)
		if f2 != 2 || f3 != "abc" {
			t.Fatalf("Bad value insert returning: %v,%v", f2, f3)
		}
	}

}

func TestIssue2(t *testing.T) {
	conn, _ := sql.Open("firebirdsql_createdb", "sysdba:masterkey@localhost:3050/tmp/go_test_issue2.fdb")

	_, err := conn.Exec(`
        CREATE TABLE test_issue2
         (f1 integer NOT NULL,
          f2 integer,
          f3 integer NOT NULL,
          f4 integer NOT NULL,
          f5 integer NOT NULL,
          f6 integer NOT NULL,
          f7 varchar(255) NOT NULL,
          f8 varchar(255) NOT NULL,
          f9 varchar(255) NOT NULL,
          f10 varchar(255) NOT NULL,
          f11 varchar(255) NOT NULL,
          f12 varchar(255) NOT NULL,
          f13 varchar(255) NOT NULL,
          f14 varchar(255) NOT NULL,
          f15 integer,
          f16 integer,
          f17 integer,
          f18 integer,
          f19 integer,
          f20 integer,
          f21 integer,
          f22 varchar(1),
          f23 varchar(255),
          f24 integer,
          f25 varchar(64),
          f26 integer)`)
	defer conn.Close()
	if err != nil {
		t.Fatalf("Error Create Table: %v", err)
	}

	_, err = conn.Exec(`
        INSERT INTO test_issue2 VALUES
        (1, 2, 3, 4, 5, 6, '7', '8', '9', '10', '11', '12', '13', '14',
          15, 16, 17, 18, 19, 20, 21, 'A', '23', 24, '25', '26')`)
	if err != nil {
		t.Fatalf("Error Insert: %v", err)
	}

	rows, err := conn.Query("SELECT * FROM test_issue2")
	if err != nil {
		t.Fatalf("Error Query: %v", err)
	}
	for rows.Next() {
	}
}

func TestIssue3(t *testing.T) {
	conn, _ := sql.Open("firebirdsql_createdb", "sysdba:masterkey@localhost:3050/tmp/go_test_issue3.fdb")
	too_many := 401

	conn.Exec("CREATE TABLE test_issue3 (f1 integer NOT NULL)")
	defer conn.Close()
	stmt, _ := conn.Prepare("INSERT INTO test_issue3 values (?)")
	for i := 0; i < too_many; i++ {
		stmt.Exec(i + 1)
	}

	rows, _ := conn.Query("SELECT * FROM test_issue3 ORDER BY f1")
	i := 0
	var n int
	for rows.Next() {
		rows.Scan(&n)
		i++
		if i != n {
			t.Fatalf("Error %v != %v", n, i)
		}
	}
	if i != too_many {
		t.Fatalf("Can't get all %v records. only %v", too_many, i)
	}
}

func TestError(t *testing.T) {
	conn, err := sql.Open("firebirdsql_createdb", "sysdba:masterkey@localhost:3050/tmp/go_test_error.fdb")
	if err != nil {
		t.Fatalf("Error connecting: %v", err)
	}
	_, err = conn.Exec("incorrect sql statement")
	if err == nil || err.Error() != "Dynamic SQL Error\nSQL error code = -104\nToken unknown - line 1, column 1\nincorrect\n" {
		t.Fatalf("Incorrect error")
	}
}

/*
func TestFB3(t *testing.T) {
	conn, err := sql.Open("firebirdsql_createdb", "sysdba:masterkey@localhost:3050/tmp/go_test_fb3.fdb")
	if err != nil {
		t.Fatalf("Error connecting: %v", err)
	}
	var sql string
	var n int

	sql = "SELECT Count(*) FROM rdb$relations where rdb$relation_name='TEST_FB3'"
	err = conn.QueryRow(sql).Scan(&n)
	if err != nil {
		t.Fatalf("Error QueryRow: %v", err)
	}
	if n > 0 {
		conn.Exec("DROP TABLE test_fb3")
	}

	sql = `
        CREATE TABLE test_fb3 (
            b BOOLEAN
        )
    `
	conn.Exec(sql)
	conn.Exec("insert into test_fb3(b) values (true)")
	conn.Exec("insert into test_fb3(b) values (false)")
    var b bool
	err = conn.QueryRow("select * from test_fb3 where b is true").Scan(&b)
	if err != nil {
		t.Fatalf("Error QueryRow: %v", err)
	}
	if b != true{
		conn.Exec("Invalid boolean value")
	}
	err = conn.QueryRow("select * from test_fb3 where b is false").Scan(&b)
	if err != nil {
		t.Fatalf("Error QueryRow: %v", err)
	}
	if b != false{
		conn.Exec("Invalid boolean value")
	}

	stmt, _ := conn.Prepare("select * from test_fb3 where b=?")
	err = stmt.QueryRow(true).Scan(&b)
	if err != nil {
		t.Fatalf("Error QueryRow: %v", err)
	}
	if b != false{
		conn.Exec("Invalid boolean value")
	}

	defer conn.Close()
}
*/
<|endoftext|>


<commit_before>package integration_test

import (
	"fmt"
	"os/exec"
	"time"

	"github.com/cloudfoundry/libbuildpack/cutlass"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var _ = Describe("Deploy app with", func() {
	var (
		app                       *cutlass.App
		serviceName, serviceName2 string
		dynatraceAPI              *cutlass.App
		dynatraceAPIURI           string
	)

	var RunCf = func(args ...string) error {
		command := exec.Command("cf", args...)
		command.Stdout = GinkgoWriter
		command.Stderr = GinkgoWriter
		return command.Run()
	}

	BeforeEach(func() {
		dynatraceAPI = cutlass.New(Fixtures("fake_dynatrace_api"))
		dynatraceAPI.SetEnv("BP_DEBUG", "true")

		Expect(dynatraceAPI.Push()).To(Succeed())
		Eventually(func() ([]string, error) { return dynatraceAPI.InstanceStates() }, 60*time.Second).Should(Equal([]string{"RUNNING"}))

		var err error
		dynatraceAPIURI, err = dynatraceAPI.GetUrl("")
		Expect(err).NotTo(HaveOccurred())

		app = cutlass.New(Fixtures("with_dynatrace"))
		app.SetEnv("BP_DEBUG", "true")
		Expect(app.PushNoStart()).To(Succeed())
	})

	AfterEach(func() {
		app = DestroyApp(app)
		dynatraceAPI = DestroyApp(dynatraceAPI)

		if serviceName != "" {
			_ = RunCf("delete-service", "-f", serviceName)
			serviceName = ""
		}
		if serviceName2 != "" {
			_ = RunCf("delete-service", "-f", serviceName2)
			serviceName2 = ""
		}
	})

	FIt("single dynatrace service without manifest.json", func() {
		serviceName = "dynatrace-service-" + cutlass.RandStringRunes(20)
		Expect(RunCf("cups", serviceName, "-p", fmt.Sprintf(`{"apitoken":"TOKEN","apiurl":"%s/without-agent-path","environmentid":"envid"}`, dynatraceAPIURI))).To(Succeed())
		Expect(RunCf("bind-service", app.Name, serviceName)).To(Succeed())
		Expect(RunCf("start", app.Name)).To(Succeed())
		ConfirmRunning(app)
		Expect(app.ConfirmBuildpack(buildpackVersion)).To(Succeed())

		By("initializing dynatrace agent")
		Expect(app.Stdout.String()).To(ContainSubstring("Initializing"))

		By("detecting single dynatrace service")
		Expect(app.Stdout.String()).To(ContainSubstring("Found one matching Dynatrace service"))

		By("downloading dynatrace agent")
		Expect(app.Stdout.String()).To(ContainSubstring("Downloading Dynatrace OneAgent Installer"))

		By("extracting dynatrace agent")
		Expect(app.Stdout.String()).To(ContainSubstring("Extracting Dynatrace OneAgent"))

		By("removing dynatrace agent installer")
		Expect(app.Stdout.String()).To(ContainSubstring("Removing Dynatrace OneAgent Installer"))

		By("adding environment vars")
		Expect(app.Stdout.String()).To(ContainSubstring("Adding Dynatrace specific Environment Vars"))

		By("LD_PRELOAD settings")
		Expect(app.Stdout.String()).To(ContainSubstring("Adding Dynatrace LD_PRELOAD settings"))

		By("checking for manifest.json fallback")
		Expect(app.Stdout.String()).To(ContainSubstring("Agent path not found in manifest.json, using fallback"))
	})

	It("Deploy app with multiple dynatrace services", func() {
		serviceName = "dynatrace-service-" + cutlass.RandStringRunes(20)
		Expect(RunCf("cups", serviceName, "-p", fmt.Sprintf(`{"apitoken":"TOKEN","apiurl":"%s","environmentid":"envid"}`, dynatraceAPIURI))).To(Succeed())
		Expect(RunCf("bind-service", app.Name, serviceName)).To(Succeed())

		serviceName2 = "dynatrace-service-" + cutlass.RandStringRunes(20)
		Expect(RunCf("cups", serviceName2, "-p", fmt.Sprintf(`{"apitoken":"TOKEN","apiurl":"%s","environmentid":"envid_dupe"}`, dynatraceAPIURI))).To(Succeed())
		Expect(RunCf("bind-service", app.Name, serviceName2)).To(Succeed())

		By("deployment should fail")
		Expect(RunCf("start", app.Name)).ToNot(Succeed())
		Expect(app.ConfirmBuildpack(buildpackVersion)).To(Succeed())

		By("initializing dynatrace agent")
		Eventually(app.Stdout.String).Should(ContainSubstring("Initializing"))

		By("detecting multiple dynatrace services")
		Eventually(app.Stdout.String).Should(ContainSubstring("More than one matching service found!"))
	})

	It("Deploy app with single dynatrace service, wrong url and skiperrors on true", func() {
		serviceName = "dynatrace-service-" + cutlass.RandStringRunes(20)
		Expect(RunCf("cups", serviceName, "-p", fmt.Sprintf(`{"apitoken":"TOKEN","apiurl":"%s/no-such-endpoint","environmentid":"envid","skiperrors":"true"}`, dynatraceAPIURI))).To(Succeed())
		Expect(RunCf("bind-service", app.Name, serviceName)).To(Succeed())

		By("deployment should not fail")
		Expect(RunCf("start", app.Name)).To(Succeed())
		Expect(app.ConfirmBuildpack(buildpackVersion)).To(Succeed())

		By("initializing dynatrace agent")
		Expect(app.Stdout.String()).To(ContainSubstring("Initializing"))

		By("detecting single dynatrace service")
		Expect(app.Stdout.String()).To(ContainSubstring("Found one matching Dynatrace service"))

		By("downloading dynatrace agent")
		Expect(app.Stdout.String()).To(ContainSubstring("Downloading Dynatrace OneAgent Installer"))

		By("download retries work")
		Expect(app.Stdout.String()).To(ContainSubstring("Error during installer download, retrying in 4 seconds"))
		Expect(app.Stdout.String()).To(ContainSubstring("Error during installer download, retrying in 5 seconds"))
		Expect(app.Stdout.String()).To(ContainSubstring("Error during installer download, retrying in 7 seconds"))

		By("should exit gracefully")
		Expect(app.Stdout.String()).To(ContainSubstring("Error during installer download, skipping installation"))

		By("no further installer logs")
		Expect(app.Stdout.String()).ToNot(ContainSubstring("Extracting Dynatrace OneAgent"))
	})

	It("Deploy app with single dynatrace service, wrong url and skiperrors not set", func() {
		serviceName = "dynatrace-service-" + cutlass.RandStringRunes(20)
		Expect(RunCf("cups", serviceName, "-p", fmt.Sprintf(`{"apitoken":"TOKEN","apiurl":"%s/no-such-endpoint","environmentid":"envid"}`, dynatraceAPIURI))).To(Succeed())
		Expect(RunCf("bind-service", app.Name, serviceName)).To(Succeed())

		By("deployment should fail")
		Expect(RunCf("start", app.Name)).ToNot(Succeed())
		Expect(app.ConfirmBuildpack(buildpackVersion)).To(Succeed())

		By("initializing dynatrace agent")
		Eventually(app.Stdout.String).Should(ContainSubstring("Initializing"))

		By("detecting single dynatrace service")
		Expect(app.Stdout.String()).To(ContainSubstring("Found one matching Dynatrace service"))

		By("downloading dynatrace agent")
		Expect(app.Stdout.String()).To(ContainSubstring("Downloading Dynatrace OneAgent Installer"))

		By("download retries work")
		Expect(app.Stdout.String()).To(ContainSubstring("Error during installer download, retrying in 4 seconds"))
		Expect(app.Stdout.String()).To(ContainSubstring("Error during installer download, retrying in 5 seconds"))
		Expect(app.Stdout.String()).To(ContainSubstring("Error during installer download, retrying in 7 seconds"))

		By("error during agent download")
		Expect(app.Stdout.String()).To(ContainSubstring("ERROR: Dynatrace agent download failed"))

		By("no further installer logs")
		Expect(app.Stdout.String()).ToNot(ContainSubstring("Extracting Dynatrace OneAgent"))
	})
})
<commit_msg>Unfocus integration spec<commit_after>package integration_test

import (
	"fmt"
	"os/exec"
	"time"

	"github.com/cloudfoundry/libbuildpack/cutlass"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var _ = Describe("Deploy app with", func() {
	var (
		app                       *cutlass.App
		serviceName, serviceName2 string
		dynatraceAPI              *cutlass.App
		dynatraceAPIURI           string
	)

	var RunCf = func(args ...string) error {
		command := exec.Command("cf", args...)
		command.Stdout = GinkgoWriter
		command.Stderr = GinkgoWriter
		return command.Run()
	}

	BeforeEach(func() {
		dynatraceAPI = cutlass.New(Fixtures("fake_dynatrace_api"))
		dynatraceAPI.SetEnv("BP_DEBUG", "true")

		Expect(dynatraceAPI.Push()).To(Succeed())
		Eventually(func() ([]string, error) { return dynatraceAPI.InstanceStates() }, 60*time.Second).Should(Equal([]string{"RUNNING"}))

		var err error
		dynatraceAPIURI, err = dynatraceAPI.GetUrl("")
		Expect(err).NotTo(HaveOccurred())

		app = cutlass.New(Fixtures("with_dynatrace"))
		app.SetEnv("BP_DEBUG", "true")
		Expect(app.PushNoStart()).To(Succeed())
	})

	AfterEach(func() {
		app = DestroyApp(app)
		dynatraceAPI = DestroyApp(dynatraceAPI)

		if serviceName != "" {
			_ = RunCf("delete-service", "-f", serviceName)
			serviceName = ""
		}
		if serviceName2 != "" {
			_ = RunCf("delete-service", "-f", serviceName2)
			serviceName2 = ""
		}
	})

	It("single dynatrace service without manifest.json", func() {
		serviceName = "dynatrace-service-" + cutlass.RandStringRunes(20)
		Expect(RunCf("cups", serviceName, "-p", fmt.Sprintf(`{"apitoken":"TOKEN","apiurl":"%s/without-agent-path","environmentid":"envid"}`, dynatraceAPIURI))).To(Succeed())
		Expect(RunCf("bind-service", app.Name, serviceName)).To(Succeed())
		Expect(RunCf("start", app.Name)).To(Succeed())
		ConfirmRunning(app)
		Expect(app.ConfirmBuildpack(buildpackVersion)).To(Succeed())

		By("initializing dynatrace agent")
		Expect(app.Stdout.String()).To(ContainSubstring("Initializing"))

		By("detecting single dynatrace service")
		Expect(app.Stdout.String()).To(ContainSubstring("Found one matching Dynatrace service"))

		By("downloading dynatrace agent")
		Expect(app.Stdout.String()).To(ContainSubstring("Downloading Dynatrace OneAgent Installer"))

		By("extracting dynatrace agent")
		Expect(app.Stdout.String()).To(ContainSubstring("Extracting Dynatrace OneAgent"))

		By("removing dynatrace agent installer")
		Expect(app.Stdout.String()).To(ContainSubstring("Removing Dynatrace OneAgent Installer"))

		By("adding environment vars")
		Expect(app.Stdout.String()).To(ContainSubstring("Adding Dynatrace specific Environment Vars"))

		By("LD_PRELOAD settings")
		Expect(app.Stdout.String()).To(ContainSubstring("Adding Dynatrace LD_PRELOAD settings"))

		By("checking for manifest.json fallback")
		Expect(app.Stdout.String()).To(ContainSubstring("Agent path not found in manifest.json, using fallback"))
	})

	It("Deploy app with multiple dynatrace services", func() {
		serviceName = "dynatrace-service-" + cutlass.RandStringRunes(20)
		Expect(RunCf("cups", serviceName, "-p", fmt.Sprintf(`{"apitoken":"TOKEN","apiurl":"%s","environmentid":"envid"}`, dynatraceAPIURI))).To(Succeed())
		Expect(RunCf("bind-service", app.Name, serviceName)).To(Succeed())

		serviceName2 = "dynatrace-service-" + cutlass.RandStringRunes(20)
		Expect(RunCf("cups", serviceName2, "-p", fmt.Sprintf(`{"apitoken":"TOKEN","apiurl":"%s","environmentid":"envid_dupe"}`, dynatraceAPIURI))).To(Succeed())
		Expect(RunCf("bind-service", app.Name, serviceName2)).To(Succeed())

		By("deployment should fail")
		Expect(RunCf("start", app.Name)).ToNot(Succeed())
		Expect(app.ConfirmBuildpack(buildpackVersion)).To(Succeed())

		By("initializing dynatrace agent")
		Eventually(app.Stdout.String).Should(ContainSubstring("Initializing"))

		By("detecting multiple dynatrace services")
		Eventually(app.Stdout.String).Should(ContainSubstring("More than one matching service found!"))
	})

	It("Deploy app with single dynatrace service, wrong url and skiperrors on true", func() {
		serviceName = "dynatrace-service-" + cutlass.RandStringRunes(20)
		Expect(RunCf("cups", serviceName, "-p", fmt.Sprintf(`{"apitoken":"TOKEN","apiurl":"%s/no-such-endpoint","environmentid":"envid","skiperrors":"true"}`, dynatraceAPIURI))).To(Succeed())
		Expect(RunCf("bind-service", app.Name, serviceName)).To(Succeed())

		By("deployment should not fail")
		Expect(RunCf("start", app.Name)).To(Succeed())
		Expect(app.ConfirmBuildpack(buildpackVersion)).To(Succeed())

		By("initializing dynatrace agent")
		Expect(app.Stdout.String()).To(ContainSubstring("Initializing"))

		By("detecting single dynatrace service")
		Expect(app.Stdout.String()).To(ContainSubstring("Found one matching Dynatrace service"))

		By("downloading dynatrace agent")
		Expect(app.Stdout.String()).To(ContainSubstring("Downloading Dynatrace OneAgent Installer"))

		By("download retries work")
		Expect(app.Stdout.String()).To(ContainSubstring("Error during installer download, retrying in 4 seconds"))
		Expect(app.Stdout.String()).To(ContainSubstring("Error during installer download, retrying in 5 seconds"))
		Expect(app.Stdout.String()).To(ContainSubstring("Error during installer download, retrying in 7 seconds"))

		By("should exit gracefully")
		Expect(app.Stdout.String()).To(ContainSubstring("Error during installer download, skipping installation"))

		By("no further installer logs")
		Expect(app.Stdout.String()).ToNot(ContainSubstring("Extracting Dynatrace OneAgent"))
	})

	It("Deploy app with single dynatrace service, wrong url and skiperrors not set", func() {
		serviceName = "dynatrace-service-" + cutlass.RandStringRunes(20)
		Expect(RunCf("cups", serviceName, "-p", fmt.Sprintf(`{"apitoken":"TOKEN","apiurl":"%s/no-such-endpoint","environmentid":"envid"}`, dynatraceAPIURI))).To(Succeed())
		Expect(RunCf("bind-service", app.Name, serviceName)).To(Succeed())

		By("deployment should fail")
		Expect(RunCf("start", app.Name)).ToNot(Succeed())
		Expect(app.ConfirmBuildpack(buildpackVersion)).To(Succeed())

		By("initializing dynatrace agent")
		Eventually(app.Stdout.String).Should(ContainSubstring("Initializing"))

		By("detecting single dynatrace service")
		Expect(app.Stdout.String()).To(ContainSubstring("Found one matching Dynatrace service"))

		By("downloading dynatrace agent")
		Expect(app.Stdout.String()).To(ContainSubstring("Downloading Dynatrace OneAgent Installer"))

		By("download retries work")
		Expect(app.Stdout.String()).To(ContainSubstring("Error during installer download, retrying in 4 seconds"))
		Expect(app.Stdout.String()).To(ContainSubstring("Error during installer download, retrying in 5 seconds"))
		Expect(app.Stdout.String()).To(ContainSubstring("Error during installer download, retrying in 7 seconds"))

		By("error during agent download")
		Expect(app.Stdout.String()).To(ContainSubstring("ERROR: Dynatrace agent download failed"))

		By("no further installer logs")
		Expect(app.Stdout.String()).ToNot(ContainSubstring("Extracting Dynatrace OneAgent"))
	})
})
<|endoftext|>


<commit_before>// uploadHandler controls showing the upload form and the
// processing of POSTed data.  Files are saved automatically
// (via http package) to env(TMPDIR). Files are then moved to
// the specified assets directory.
//
// NOTE: It is strongly recommended that you set the TMPDIR
// environment variable when you launch the evh service and
// set it to a directory on the same filesystem as assets.
// Moving the temp file to the permament location will be
// much faster this way.
package main

import (
	"fmt"
	"html/template"
	"net/http"
	"path/filepath"
)

//This is where the action happens.
func uploadHandler(w http.ResponseWriter, r *http.Request) {
	// Redirect to SSL if enabled
	if r.TLS == nil && Config.Server.Ssl {
		redirectToSsl(w, r)
		return
	}

	// Get a new Page object
	var page = NewPage()
	// Set the appropriate protocol prefix for URLs
	if r.TLS != nil {
		page.HttpProto = "https"
	}

	// Prep our available expirations
	var expirations = ExpandExpirations()
	page.Expirations = ExpirationsToHtmlMap(expirations)

	switch r.Method {
	// Show the upload form
	case "GET":
		DisplayPage(w, r, "upload", page)

	// Process form submission
	case "POST":
		// Initialize our file count to zero
		var filecount = 0

		// New request object
		req, reqerr := NewRequest(r.RemoteAddr)
		if reqerr != nil {
			req.Log(reqerr.Error())
			return
		}

		// Setup our tracker
		page.Tracker = NewTracker(req.Dnldcode)

		// This is the download URL for the session, not used for individual files
		req.Log("New incoming transfer starting for", r.RemoteAddr)

		// Parse the multipart form in the request (set max memory in bytes)
		err := r.ParseMultipartForm(10000)
		if err != nil {
			page.Message = "Transfer aborted (client disconnected)"
			req.Log(string(page.Message))
		} else {
			// Store form values
			page.Tracker.Description = r.FormValue("FileDescr")
			page.Tracker.SrcEmail = r.FormValue("SrcEmail")
			page.Tracker.DstEmail = r.FormValue("DstEmail")
			page.Tracker.Expiration = r.FormValue("Expires")

			if r.FormValue("client") == "1" {
				page.Tracker.CliUpload = true
			}

			// Path to save file to
			req.Path = filepath.Join(Config.Server.Assets, req.Dnldcode)

			// Get the *fileheaders and keep count of uploadedjack filesN
			//   We don't care what the form field is called, just iterate over all form fields of type file
			for fieldname, files := range r.MultipartForm.File {
				req.Log("Processing files field:", fieldname)
				for i, _ := range files {
					var filename = ScrubFilename(files[i].Header.Get("Content-Disposition"))
					filecount++

					// Create a File object
					var newfile = NewFile(filename, req.Path)

					// Move the temp file to the permament location
					err := newfile.Save(files[i])
					if err != nil {
						req.Errors = append(req.Errors, err.Error())
						req.Log()
					} else {
						req.Log(fmt.Sprintf("Saved file (%s, %.2f MB): %s", newfile.Name, newfile.Size/1024/1024, newfile.Path))
					}

					// Update our tracker
					page.Tracker.Files = append(page.Tracker.Files, newfile)
					page.Tracker.Size += newfile.Size
					page.Tracker.SizeMB += float64(page.Tracker.Size) / 1024 / 1024
					page.Tracker.AddLog("Added file " + newfile.Name)
				}
			}

			// Set our expiration
			if val, ok := expirations[page.Tracker.Expiration]; ok {
				page.Tracker.ExpirationDate = val
			} else {
				req.Log("Invalid expiration specified, using default of 1 day")
				page.Tracker.ExpirationDate = expirations["1:d"]
			}
			page.Tracker.ExpirationStr = page.Tracker.ExpirationDate.Format(TimeLayout)

			// Send notification
			req.Notify(&page)
			page.Tracker.Save()
		}

		// DisplayPage result message (using template.HTML() allows the template to show the non-garbled URL)
		var filespageurl = page.BaseUrl + DownloadUrlPath + page.Tracker.Dnldcode + "?vercode=" + page.Tracker.Vercode
		if r.FormValue("client") == "1" {
			page.Message = template.HTML(fmt.Sprintf("Successfully uploaded %d of %d files.  Your files are available here:\n%s\n", page.Tracker.CountSaved(), filecount, filespageurl))
			DisplayPage(w, r, "uploadPlain", page)
		} else {
			page.Message = template.HTML(fmt.Sprintf("Successfully uploaded %d of %d files.  Your files are available here.", page.Tracker.CountSaved(), filecount, filespageurl))
			DisplayPage(w, r, "upload", page)
		}
	default:
		w.WriteHeader(http.StatusMethodNotAllowed)
	}
}
<commit_msg>Fixed bug in Tracker.SizeMB calculation.<commit_after>// uploadHandler controls showing the upload form and the
// processing of POSTed data.  Files are saved automatically
// (via http package) to env(TMPDIR). Files are then moved to
// the specified assets directory.
//
// NOTE: It is strongly recommended that you set the TMPDIR
// environment variable when you launch the evh service and
// set it to a directory on the same filesystem as assets.
// Moving the temp file to the permament location will be
// much faster this way.
package main

import (
	"fmt"
	"html/template"
	"net/http"
	"path/filepath"
)

//This is where the action happens.
func uploadHandler(w http.ResponseWriter, r *http.Request) {
	// Redirect to SSL if enabled
	if r.TLS == nil && Config.Server.Ssl {
		redirectToSsl(w, r)
		return
	}

	// Get a new Page object
	var page = NewPage()
	// Set the appropriate protocol prefix for URLs
	if r.TLS != nil {
		page.HttpProto = "https"
	}

	// Prep our available expirations
	var expirations = ExpandExpirations()
	page.Expirations = ExpirationsToHtmlMap(expirations)

	switch r.Method {
	// Show the upload form
	case "GET":
		DisplayPage(w, r, "upload", page)

	// Process form submission
	case "POST":
		// Initialize our file count to zero
		var filecount = 0

		// New request object
		req, reqerr := NewRequest(r.RemoteAddr)
		if reqerr != nil {
			req.Log(reqerr.Error())
			return
		}

		// Setup our tracker
		page.Tracker = NewTracker(req.Dnldcode)

		// This is the download URL for the session, not used for individual files
		req.Log("New incoming transfer starting for", r.RemoteAddr)

		// Parse the multipart form in the request (set max memory in bytes)
		err := r.ParseMultipartForm(10000)
		if err != nil {
			page.Message = "Transfer aborted (client disconnected)"
			req.Log(string(page.Message))
		} else {
			// Store form values
			page.Tracker.Description = r.FormValue("FileDescr")
			page.Tracker.SrcEmail = r.FormValue("SrcEmail")
			page.Tracker.DstEmail = r.FormValue("DstEmail")
			page.Tracker.Expiration = r.FormValue("Expires")

			if r.FormValue("client") == "1" {
				page.Tracker.CliUpload = true
			}

			// Path to save file to
			req.Path = filepath.Join(Config.Server.Assets, req.Dnldcode)

			// Get the *fileheaders and keep count of uploadedjack filesN
			//   We don't care what the form field is called, just iterate over all form fields of type file
			for fieldname, files := range r.MultipartForm.File {
				req.Log("Processing files field:", fieldname)
				for i, _ := range files {
					var filename = ScrubFilename(files[i].Header.Get("Content-Disposition"))
					filecount++

					// Create a File object
					var newfile = NewFile(filename, req.Path)

					// Move the temp file to the permament location
					err := newfile.Save(files[i])
					if err != nil {
						req.Errors = append(req.Errors, err.Error())
						req.Log()
					} else {
						req.Log(fmt.Sprintf("Saved file (%s, %.2f MB): %s", newfile.Name, newfile.Size/1024/1024, newfile.Path))
					}

					// Update our tracker
					page.Tracker.Files = append(page.Tracker.Files, newfile)
					page.Tracker.Size += newfile.Size
					page.Tracker.SizeMB = page.Tracker.Size / 1024 / 1024
					page.Tracker.AddLog("Added file " + newfile.Name)
				}
			}

			// Set our expiration
			if val, ok := expirations[page.Tracker.Expiration]; ok {
				page.Tracker.ExpirationDate = val
			} else {
				req.Log("Invalid expiration specified, using default of 1 day")
				page.Tracker.ExpirationDate = expirations["1:d"]
			}
			page.Tracker.ExpirationStr = page.Tracker.ExpirationDate.Format(TimeLayout)

			// Send notification
			req.Notify(&page)
			page.Tracker.Save()
		}

		// DisplayPage result message (using template.HTML() allows the template to show the non-garbled URL)
		var filespageurl = page.BaseUrl + DownloadUrlPath + page.Tracker.Dnldcode + "?vercode=" + page.Tracker.Vercode
		if r.FormValue("client") == "1" {
			page.Message = template.HTML(fmt.Sprintf("Successfully uploaded %d of %d files.  Your files are available here:\n%s\n", page.Tracker.CountSaved(), filecount, filespageurl))
			DisplayPage(w, r, "uploadPlain", page)
		} else {
			page.Message = template.HTML(fmt.Sprintf("Successfully uploaded %d of %d files.  Your files are available here.", page.Tracker.CountSaved(), filecount, filespageurl))
			DisplayPage(w, r, "upload", page)
		}
	default:
		w.WriteHeader(http.StatusMethodNotAllowed)
	}
}
<|endoftext|>


<commit_before>package main

import (
	"encoding/json"
	"net/http"

	"github.com/julienschmidt/httprouter"
)

/* Read functions
 */
func ListMonitoring(w http.ResponseWriter, r *http.Request,
	_ httprouter.Params) {
	defer PanicCatcher(w)

	returnChannel := make(chan somaResult)
	handler := handlerMap["monitoringReadHandler"].(somaMonitoringReadHandler)
	handler.input <- somaMonitoringRequest{
		action: "list",
		reply:  returnChannel,
	}
	result := <-returnChannel

	// declare here since goto does not jump over declarations
	cReq := proto.NewMonitoringFilter()
	if result.Failure() {
		goto skip
	}

	_ = DecodeJsonBody(r, &cReq)
	if cReq.Filter.Monitoring.Name != "" {
		filtered := make([]somaMonitoringResult, 0)
		for _, i := range result.Systems {
			if i.Monitoring.Name == cReq.Filter.Monitoring.Name {
				filtered = append(filtered, i)
			}
		}
		result.Systems = filtered
	}

skip:
	SendMonitoringReply(&w, &result)
}

func ShowMonitoring(w http.ResponseWriter, r *http.Request,
	params httprouter.Params) {
	defer PanicCatcher(w)

	returnChannel := make(chan somaResult)
	handler := handlerMap["monitoringReadHandler"].(somaMonitoringReadHandler)
	handler.input <- somaMonitoringRequest{
		action: "show",
		reply:  returnChannel,
		Monitoring: proto.Monitoring{
			Id: params.ByName("monitoring"),
		},
	}
	result := <-returnChannel
	SendMonitoringReply(&w, &result)
}

/* Write functions
 */
func AddMonitoring(w http.ResponseWriter, r *http.Request,
	_ httprouter.Params) {
	defer PanicCatcher(w)

	cReq := proto.NewMonitoringRequest()
	err := DecodeJsonBody(r, &cReq)
	if err != nil {
		DispatchBadRequest(&w, err)
		return
	}

	returnChannel := make(chan somaResult)
	handler := handlerMap["monitoringWriteHandler"].(somaMonitoringWriteHandler)
	handler.input <- somaMonitoringRequest{
		action: "add",
		reply:  returnChannel,
		Monitoring: proto.Monitoring{
			Name:     cReq.Monitoring.Name,
			Mode:     cReq.Monitoring.Mode,
			Contact:  cReq.Monitoring.Contact,
			TeamId:   cReq.Monitoring.TeamId,
			Callback: cReq.Monitoring.Callback,
		},
	}
	result := <-returnChannel
	SendMonitoringReply(&w, &result)
}

func DeleteMonitoring(w http.ResponseWriter, r *http.Request,
	params httprouter.Params) {
	defer PanicCatcher(w)

	returnChannel := make(chan somaResult)
	handler := handlerMap["monitoringWriteHandler"].(somaMonitoringWriteHandler)
	handler.input <- somaMonitoringRequest{
		action: "delete",
		reply:  returnChannel,
		Monitoring: proto.Monitoring{
			Id: params.ByName("monitoring"),
		},
	}
	result := <-returnChannel
	SendMonitoringReply(&w, &result)
}

/* Utility
 */
func SendMonitoringReply(w *http.ResponseWriter, r *somaResult) {
	result := proto.NewMonitoringResult()
	if r.MarkErrors(&result) {
		goto dispatch
	}
	for _, i := range (*r).Systems {
		*result.Monitorings = append(*result.Monitorings, i.Monitoring)
		if i.ResultError != nil {
			*result.Errors = append(*result.Errors, i.ResultError.Error())
		}
	}

dispatch:
	json, err := json.Marshal(result)
	if err != nil {
		DispatchInternalError(w, err)
		return
	}
	DispatchJsonReply(w, &json)
	return
}

// vim: ts=4 sw=4 sts=4 noet fenc=utf-8 ffs=unix
<commit_msg>Enforce monitoring name not containing . char<commit_after>package main

import (
	"encoding/json"
	"fmt"
	"net/http"
	"strings"

	"github.com/julienschmidt/httprouter"
)

/* Read functions
 */
func ListMonitoring(w http.ResponseWriter, r *http.Request,
	_ httprouter.Params) {
	defer PanicCatcher(w)

	returnChannel := make(chan somaResult)
	handler := handlerMap["monitoringReadHandler"].(somaMonitoringReadHandler)
	handler.input <- somaMonitoringRequest{
		action: "list",
		reply:  returnChannel,
	}
	result := <-returnChannel

	// declare here since goto does not jump over declarations
	cReq := proto.NewMonitoringFilter()
	if result.Failure() {
		goto skip
	}

	_ = DecodeJsonBody(r, &cReq)
	if cReq.Filter.Monitoring.Name != "" {
		filtered := make([]somaMonitoringResult, 0)
		for _, i := range result.Systems {
			if i.Monitoring.Name == cReq.Filter.Monitoring.Name {
				filtered = append(filtered, i)
			}
		}
		result.Systems = filtered
	}

skip:
	SendMonitoringReply(&w, &result)
}

func ShowMonitoring(w http.ResponseWriter, r *http.Request,
	params httprouter.Params) {
	defer PanicCatcher(w)

	returnChannel := make(chan somaResult)
	handler := handlerMap["monitoringReadHandler"].(somaMonitoringReadHandler)
	handler.input <- somaMonitoringRequest{
		action: "show",
		reply:  returnChannel,
		Monitoring: proto.Monitoring{
			Id: params.ByName("monitoring"),
		},
	}
	result := <-returnChannel
	SendMonitoringReply(&w, &result)
}

/* Write functions
 */
func AddMonitoring(w http.ResponseWriter, r *http.Request,
	_ httprouter.Params) {
	defer PanicCatcher(w)

	cReq := proto.NewMonitoringRequest()
	err := DecodeJsonBody(r, &cReq)
	if err != nil {
		DispatchBadRequest(&w, err)
		return
	}
	if strings.Contains(cReq.Monitoring.Name, `.`) {
		DispatchBadRequest(&w, fmt.Errorf(`Invalid monitoring system name containing . character`))
		return
	}

	returnChannel := make(chan somaResult)
	handler := handlerMap["monitoringWriteHandler"].(somaMonitoringWriteHandler)
	handler.input <- somaMonitoringRequest{
		action: "add",
		reply:  returnChannel,
		Monitoring: proto.Monitoring{
			Name:     cReq.Monitoring.Name,
			Mode:     cReq.Monitoring.Mode,
			Contact:  cReq.Monitoring.Contact,
			TeamId:   cReq.Monitoring.TeamId,
			Callback: cReq.Monitoring.Callback,
		},
	}
	result := <-returnChannel
	SendMonitoringReply(&w, &result)
}

func DeleteMonitoring(w http.ResponseWriter, r *http.Request,
	params httprouter.Params) {
	defer PanicCatcher(w)

	returnChannel := make(chan somaResult)
	handler := handlerMap["monitoringWriteHandler"].(somaMonitoringWriteHandler)
	handler.input <- somaMonitoringRequest{
		action: "delete",
		reply:  returnChannel,
		Monitoring: proto.Monitoring{
			Id: params.ByName("monitoring"),
		},
	}
	result := <-returnChannel
	SendMonitoringReply(&w, &result)
}

/* Utility
 */
func SendMonitoringReply(w *http.ResponseWriter, r *somaResult) {
	result := proto.NewMonitoringResult()
	if r.MarkErrors(&result) {
		goto dispatch
	}
	for _, i := range (*r).Systems {
		*result.Monitorings = append(*result.Monitorings, i.Monitoring)
		if i.ResultError != nil {
			*result.Errors = append(*result.Errors, i.ResultError.Error())
		}
	}

dispatch:
	json, err := json.Marshal(result)
	if err != nil {
		DispatchInternalError(w, err)
		return
	}
	DispatchJsonReply(w, &json)
	return
}

// vim: ts=4 sw=4 sts=4 noet fenc=utf-8 ffs=unix
<|endoftext|>


<commit_before>package middleware

import (
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"time"

	"github.com/remind101/pkg/httpx"
	"github.com/remind101/pkg/logger"
	"golang.org/x/net/context"
)

// StdoutLogger is a logger.Logger generator that generates a logger that writes
// to stdout.
var StdoutLogger = stdLogger(os.Stdout)

// LogTo is an httpx middleware that wraps the handler to insert a logger and
// log the request to it.
func LogTo(h httpx.Handler, f func(context.Context, *http.Request) logger.Logger) httpx.Handler {
	return InsertLogger(Log(h), f)
}

// InsertLogger returns an httpx.Handler middleware that will call f to generate
// a logger, then insert it into the context.
func InsertLogger(h httpx.Handler, f func(context.Context, *http.Request) logger.Logger) httpx.Handler {
	return httpx.HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
		l := f(ctx, r)
		ctx = logger.WithLogger(ctx, l)
		return h.ServeHTTPContext(ctx, w, r)
	})
}

func stdLogger(out io.Writer) func(context.Context, *http.Request) logger.Logger {
	return func(ctx context.Context, r *http.Request) logger.Logger {
		return logger.New(log.New(out, fmt.Sprintf("request_id=%s ", httpx.RequestID(ctx)), 0))
	}
}

// Logger is middleware that logs the request details to the logger.Logger
// embedded within the context.
type Logger struct {
	// handler is the wrapped httpx.Handler
	handler httpx.Handler
}

func Log(h httpx.Handler) *Logger {
	return &Logger{
		handler: h,
	}
}

func (h *Logger) ServeHTTPContext(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
	rw := NewResponseWriter(w)

	t := time.Now()

	err := h.handler.ServeHTTPContext(ctx, rw, r)

	ms := fmt.Sprintf("%d", (int(time.Now().Sub(t)).Seconds() * 1000))

	logger.Info(ctx, "request",
		"method", r.Method,
		"path", r.URL.Path,
		"status", rw.Status(),
		"ms", ms,
	)

	return err
}
<commit_msg>Fix tests<commit_after>package middleware

import (
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"time"

	"github.com/remind101/pkg/httpx"
	"github.com/remind101/pkg/logger"
	"golang.org/x/net/context"
)

// StdoutLogger is a logger.Logger generator that generates a logger that writes
// to stdout.
var StdoutLogger = stdLogger(os.Stdout)

// LogTo is an httpx middleware that wraps the handler to insert a logger and
// log the request to it.
func LogTo(h httpx.Handler, f func(context.Context, *http.Request) logger.Logger) httpx.Handler {
	return InsertLogger(Log(h), f)
}

// InsertLogger returns an httpx.Handler middleware that will call f to generate
// a logger, then insert it into the context.
func InsertLogger(h httpx.Handler, f func(context.Context, *http.Request) logger.Logger) httpx.Handler {
	return httpx.HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
		l := f(ctx, r)
		ctx = logger.WithLogger(ctx, l)
		return h.ServeHTTPContext(ctx, w, r)
	})
}

func stdLogger(out io.Writer) func(context.Context, *http.Request) logger.Logger {
	return func(ctx context.Context, r *http.Request) logger.Logger {
		return logger.New(log.New(out, fmt.Sprintf("request_id=%s ", httpx.RequestID(ctx)), 0))
	}
}

// Logger is middleware that logs the request details to the logger.Logger
// embedded within the context.
type Logger struct {
	// handler is the wrapped httpx.Handler
	handler httpx.Handler
}

func Log(h httpx.Handler) *Logger {
	return &Logger{
		handler: h,
	}
}

func (h *Logger) ServeHTTPContext(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
	rw := NewResponseWriter(w)

	t := time.Now()

	err := h.handler.ServeHTTPContext(ctx, rw, r)

	ms := fmt.Sprintf("%d", (int(time.Now().Sub(t).Seconds() * 1000)))

	logger.Info(ctx, "request",
		"method", r.Method,
		"path", r.URL.Path,
		"status", rw.Status(),
		"ms", ms,
	)

	return err
}
<|endoftext|>


<commit_before>//
// Copyright 2021, Sander van Harmelen
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

package gitlab

import (
	"encoding/json"
	"testing"
)

func TestBuildEventUnmarshal(t *testing.T) {
	jsonObject := loadFixture("testdata/webhooks/build.json")

	var event *BuildEvent
	err := json.Unmarshal(jsonObject, &event)

	if err != nil {
		t.Errorf("Build Event can not unmarshaled: %v\n ", err.Error())
	}

	if event == nil {
		t.Errorf("Build Event is null")
	}

	if event.BuildID != 1977 {
		t.Errorf("BuildID is %v, want %v", event.BuildID, 1977)
	}
}

func TestDeploymentEventUnmarshal(t *testing.T) {
	jsonObject := loadFixture("testdata/webhooks/deployment.json")

	var event *DeploymentEvent
	err := json.Unmarshal(jsonObject, &event)

	if err != nil {
		t.Errorf("Deployment Event can not unmarshaled: %v\n ", err.Error())
	}

	if event == nil {
		t.Errorf("Deployment Event is null")
	}

	if event.Project.ID != 30 {
		t.Errorf("Project.ID is %v, want %v", event.Project.ID, 30)
	}

	if event.User.Name == "" {
		t.Errorf("Username is %s, want %s", event.User.Name, "Administrator")
	}

	if event.CommitTitle != "Add new file" {
		t.Errorf("CommitTitle is %s, want %s", event.CommitTitle, "Add new file")
	}
}

func TestIssueCommentEventUnmarshal(t *testing.T) {
	jsonObject := loadFixture("testdata/webhooks/note_issue.json")

	var event *IssueCommentEvent
	err := json.Unmarshal(jsonObject, &event)

	if err != nil {
		t.Errorf("Issue Comment Event can not unmarshaled: %v\n ", err.Error())
	}

	if event.ObjectKind != string(NoteEventTargetType) {
		t.Errorf("ObjectKind is %v, want %v", event.ObjectKind, NoteEventTargetType)
	}

	if event.ProjectID != 5 {
		t.Errorf("ProjectID is %v, want %v", event.ProjectID, 5)
	}

	if event.ObjectAttributes.NoteableType != "Issue" {
		t.Errorf("NoteableType is %v, want %v", event.ObjectAttributes.NoteableType, "Issue")
	}

	if event.Issue.Title != "test_issue" {
		t.Errorf("Issue title is %v, want %v", event.Issue.Title, "test_issue")
	}

	if len(event.Issue.Labels) == 0 || event.Issue.Labels[0].ID != 25 {
		t.Errorf("Label id is null")
	}
}

func TestIssueEventUnmarshal(t *testing.T) {
	jsonObject := loadFixture("testdata/webhooks/issue.json")

	var event *IssueEvent
	err := json.Unmarshal(jsonObject, &event)

	if err != nil {
		t.Errorf("Issue Event can not unmarshaled: %v\n ", err.Error())
	}
	if event.Project.ID != 1 {
		t.Errorf("Project.ID is %v, want %v", event.Project.ID, 1)
	}
	if event.Changes.TotalTimeSpent.Previous != 8100 {
		t.Errorf("Changes.TotalTimeSpent.Previous is %v , want %v", event.Changes.TotalTimeSpent.Previous, 8100)
	}
	if event.Changes.TotalTimeSpent.Current != 9900 {
		t.Errorf("Changes.TotalTimeSpent.Current is %v , want %v", event.Changes.TotalTimeSpent.Current, 8100)
	}
}

func TestMergeEventUnmarshal(t *testing.T) {
	jsonObject := loadFixture("testdata/webhooks/merge_request.json")

	var event *MergeEvent
	err := json.Unmarshal(jsonObject, &event)

	if err != nil {
		t.Errorf("Merge Event can not unmarshaled: %v\n ", err.Error())
	}

	if event == nil {
		t.Errorf("Merge Event is null")
	}

	if event.ObjectAttributes.ID != 99 {
		t.Errorf("ObjectAttributes.ID is %v, want %v", event.ObjectAttributes.ID, 99)
	}

	if event.ObjectAttributes.Source.Homepage != "http://example.com/awesome_space/awesome_project" {
		t.Errorf("ObjectAttributes.Source.Homepage is %v, want %v", event.ObjectAttributes.Source.Homepage, "http://example.com/awesome_space/awesome_project")
	}

	if event.ObjectAttributes.LastCommit.ID != "da1560886d4f094c3e6c9ef40349f7d38b5d27d7" {
		t.Errorf("ObjectAttributes.LastCommit.ID is %v, want %s", event.ObjectAttributes.LastCommit.ID, "da1560886d4f094c3e6c9ef40349f7d38b5d27d7")
	}
	if event.ObjectAttributes.Assignee.Name != "User1" {
		t.Errorf("Assignee.Name is %v, want %v", event.ObjectAttributes.ID, "User1")
	}

	if event.ObjectAttributes.Assignee.Username != "user1" {
		t.Errorf("ObjectAttributes is %v, want %v", event.ObjectAttributes.Assignee.Username, "user1")
	}

	if event.User.Name == "" {
		t.Errorf("Username is %s, want %s", event.User.Name, "Administrator")
	}

	if event.ObjectAttributes.LastCommit.Timestamp == nil {
		t.Errorf("Timestamp isn't nil")
	}

	if name := event.ObjectAttributes.LastCommit.Author.Name; name != "GitLab dev user" {
		t.Errorf("Commit Username is %s, want %s", name, "GitLab dev user")
	}
}

func TestMergeEventUnmarshalFromGroup(t *testing.T) {
	jsonObject := loadFixture("testdata/webhooks/group_merge_request.json")

	var event *MergeEvent
	err := json.Unmarshal(jsonObject, &event)

	if err != nil {
		t.Errorf("Group Merge Event can not unmarshaled: %v\n ", err.Error())
	}

	if event == nil {
		t.Errorf("Group Merge Event is null")
	}

	if event.ObjectKind != "merge_request" {
		t.Errorf("ObjectKind is %v, want %v", event.ObjectKind, "merge_request")
	}

	if event.User.Username != "root" {
		t.Errorf("User.Username is %v, want %v", event.User.Username, "root")
	}

	if event.Project.Name != exampleProjectName {
		t.Errorf("Project.Name is %v, want %v", event.Project.Name, exampleProjectName)
	}

	if event.ObjectAttributes.ID != 15917 {
		t.Errorf("ObjectAttributes.ID is %v, want %v", event.ObjectAttributes.ID, 15917)
	}

	if event.ObjectAttributes.Source.Name != exampleProjectName {
		t.Errorf("ObjectAttributes.Source.Name is %v, want %v", event.ObjectAttributes.Source.Name, exampleProjectName)
	}

	if event.ObjectAttributes.LastCommit.Author.Email != "test.user@mail.com" {
		t.Errorf("ObjectAttributes.LastCommit.Author.Email is %v, want %v", event.ObjectAttributes.LastCommit.Author.Email, "test.user@mail.com")
	}

	if event.Repository.Name != exampleProjectName {
		t.Errorf("Repository.Name is %v, want %v", event.Repository.Name, exampleProjectName)
	}

	if event.Assignee.Username != "root" {
		t.Errorf("Assignee.Username is %v, want %v", event.Assignee, "root")
	}

	if event.User.Name == "" {
		t.Errorf("Username is %s, want %s", event.User.Name, "Administrator")
	}

	if event.ObjectAttributes.LastCommit.Timestamp == nil {
		t.Errorf("Timestamp isn't nil")
	}

	if name := event.ObjectAttributes.LastCommit.Author.Name; name != "Test User" {
		t.Errorf("Commit Username is %s, want %s", name, "Test User")
	}
}

func TestPipelineEventUnmarshal(t *testing.T) {
	jsonObject := loadFixture("testdata/webhooks/pipeline.json")

	var event *PipelineEvent
	err := json.Unmarshal(jsonObject, &event)

	if err != nil {
		t.Errorf("Pipeline Event can not unmarshaled: %v\n ", err.Error())
	}

	if event == nil {
		t.Errorf("Pipeline Event is null")
	}

	if event.ObjectAttributes.ID != 31 {
		t.Errorf("ObjectAttributes is %v, want %v", event.ObjectAttributes.ID, 1977)
	}

	if event.User.Name == "" {
		t.Errorf("Username is %s, want %s", event.User.Name, "Administrator")
	}

	if event.Commit.Timestamp == nil {
		t.Errorf("Timestamp isn't nil")
	}

	if name := event.Commit.Author.Name; name != "User" {
		t.Errorf("Commit Username is %s, want %s", name, "User")
	}
}

func TestPushEventUnmarshal(t *testing.T) {
	jsonObject := loadFixture("testdata/webhooks/push.json")
	var event *PushEvent
	err := json.Unmarshal(jsonObject, &event)

	if err != nil {
		t.Errorf("Push Event can not unmarshaled: %v\n ", err.Error())
	}

	if event == nil {
		t.Errorf("Push Event is null")
	}

	if event.ProjectID != 15 {
		t.Errorf("ProjectID is %v, want %v", event.ProjectID, 15)
	}

	if event.UserName != exampleEventUserName {
		t.Errorf("Username is %s, want %s", event.UserName, exampleEventUserName)
	}

	if event.Commits[0] == nil || event.Commits[0].Timestamp == nil {
		t.Errorf("Commit Timestamp isn't nil")
	}

	if event.Commits[0] == nil || event.Commits[0].Author.Name != "Jordi Mallach" {
		t.Errorf("Commit Username is %s, want %s", event.UserName, "Jordi Mallach")
	}
}

func TestReleaseEventUnmarshal(t *testing.T) {
	jsonObject := loadFixture("testdata/webhooks/release.json")

	var event *ReleaseEvent
	err := json.Unmarshal(jsonObject, &event)

	if err != nil {
		t.Errorf("Release Event can not unmarshaled: %v\n ", err.Error())
	}

	if event == nil {
		t.Errorf("Release Event is null")
	}

	if event.Project.ID != 327622 {
		t.Errorf("Project.ID is %v, want %v", event.Project.ID, 327622)
	}

	if event.Commit.Title != "Merge branch 'example-branch' into 'master'" {
		t.Errorf("Commit title is %s, want %s", event.Commit.Title, "Merge branch 'example-branch' into 'master'")
	}

	if len(event.Assets.Sources) != 4 {
		t.Errorf("Asset sources length is %d, want %d", len(event.Assets.Sources), 4)
	}

	if event.Assets.Sources[0].Format != "zip" {
		t.Errorf("First asset source format is %s, want %s", event.Assets.Sources[0].Format, "zip")
	}

	if len(event.Assets.Links) != 1 {
		t.Errorf("Asset links length is %d, want %d", len(event.Assets.Links), 1)
	}

	if event.Assets.Links[0].Name != "Changelog" {
		t.Errorf("First asset link name is %s, want %s", event.Assets.Links[0].Name, "Changelog")
	}

	if event.Commit.Author.Name != "User" {
		t.Errorf("Commit author name is %s, want %s", event.Commit.Author.Name, "User")
	}
}
<commit_msg>tests(event_webhook_types): test the value properly<commit_after>//
// Copyright 2021, Sander van Harmelen
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

package gitlab

import (
	"encoding/json"
	"testing"
)

func TestBuildEventUnmarshal(t *testing.T) {
	jsonObject := loadFixture("testdata/webhooks/build.json")

	var event *BuildEvent
	err := json.Unmarshal(jsonObject, &event)

	if err != nil {
		t.Errorf("Build Event can not unmarshaled: %v\n ", err.Error())
	}

	if event == nil {
		t.Errorf("Build Event is null")
	}

	if event.BuildID != 1977 {
		t.Errorf("BuildID is %v, want %v", event.BuildID, 1977)
	}
}

func TestDeploymentEventUnmarshal(t *testing.T) {
	jsonObject := loadFixture("testdata/webhooks/deployment.json")

	var event *DeploymentEvent
	err := json.Unmarshal(jsonObject, &event)

	if err != nil {
		t.Errorf("Deployment Event can not unmarshaled: %v\n ", err.Error())
	}

	if event == nil {
		t.Errorf("Deployment Event is null")
	}

	if event.Project.ID != 30 {
		t.Errorf("Project.ID is %v, want %v", event.Project.ID, 30)
	}

	if event.User.Name == "" {
		t.Errorf("Username is %s, want %s", event.User.Name, "Administrator")
	}

	if event.CommitTitle != "Add new file" {
		t.Errorf("CommitTitle is %s, want %s", event.CommitTitle, "Add new file")
	}
}

func TestIssueCommentEventUnmarshal(t *testing.T) {
	jsonObject := loadFixture("testdata/webhooks/note_issue.json")

	var event *IssueCommentEvent
	err := json.Unmarshal(jsonObject, &event)

	if err != nil {
		t.Errorf("Issue Comment Event can not unmarshaled: %v\n ", err.Error())
	}

	if event.ObjectKind != string(NoteEventTargetType) {
		t.Errorf("ObjectKind is %v, want %v", event.ObjectKind, NoteEventTargetType)
	}

	if event.ProjectID != 5 {
		t.Errorf("ProjectID is %v, want %v", event.ProjectID, 5)
	}

	if event.ObjectAttributes.NoteableType != "Issue" {
		t.Errorf("NoteableType is %v, want %v", event.ObjectAttributes.NoteableType, "Issue")
	}

	if event.Issue.Title != "test_issue" {
		t.Errorf("Issue title is %v, want %v", event.Issue.Title, "test_issue")
	}

	if len(event.Issue.Labels) == 0 || event.Issue.Labels[0].ID != 25 {
		t.Errorf("Label id is null")
	}
}

func TestIssueEventUnmarshal(t *testing.T) {
	jsonObject := loadFixture("testdata/webhooks/issue.json")

	var event *IssueEvent
	err := json.Unmarshal(jsonObject, &event)

	if err != nil {
		t.Errorf("Issue Event can not unmarshaled: %v\n ", err.Error())
	}
	if event.Project.ID != 1 {
		t.Errorf("Project.ID is %v, want %v", event.Project.ID, 1)
	}
	if event.Changes.TotalTimeSpent.Previous != 8100 {
		t.Errorf("Changes.TotalTimeSpent.Previous is %v , want %v", event.Changes.TotalTimeSpent.Previous, 8100)
	}
	if event.Changes.TotalTimeSpent.Current != 9900 {
		t.Errorf("Changes.TotalTimeSpent.Current is %v , want %v", event.Changes.TotalTimeSpent.Current, 8100)
	}
}

func TestMergeEventUnmarshal(t *testing.T) {
	jsonObject := loadFixture("testdata/webhooks/merge_request.json")

	var event *MergeEvent
	err := json.Unmarshal(jsonObject, &event)

	if err != nil {
		t.Errorf("Merge Event can not unmarshaled: %v\n ", err.Error())
	}

	if event == nil {
		t.Errorf("Merge Event is null")
	}

	if event.ObjectAttributes.ID != 99 {
		t.Errorf("ObjectAttributes.ID is %v, want %v", event.ObjectAttributes.ID, 99)
	}

	if event.ObjectAttributes.Source.Homepage != "http://example.com/awesome_space/awesome_project" {
		t.Errorf("ObjectAttributes.Source.Homepage is %v, want %v", event.ObjectAttributes.Source.Homepage, "http://example.com/awesome_space/awesome_project")
	}

	if event.ObjectAttributes.LastCommit.ID != "da1560886d4f094c3e6c9ef40349f7d38b5d27d7" {
		t.Errorf("ObjectAttributes.LastCommit.ID is %v, want %s", event.ObjectAttributes.LastCommit.ID, "da1560886d4f094c3e6c9ef40349f7d38b5d27d7")
	}
	if event.ObjectAttributes.Assignee.Name != "User1" {
		t.Errorf("Assignee.Name is %v, want %v", event.ObjectAttributes.ID, "User1")
	}

	if event.ObjectAttributes.Assignee.Username != "user1" {
		t.Errorf("ObjectAttributes is %v, want %v", event.ObjectAttributes.Assignee.Username, "user1")
	}

	if event.User.Name != "Administrator" {
		t.Errorf("Username is %s, want %s", event.User.Name, "Administrator")
	}

	if event.ObjectAttributes.LastCommit.Timestamp == nil {
		t.Errorf("Timestamp isn't nil")
	}

	if name := event.ObjectAttributes.LastCommit.Author.Name; name != "GitLab dev user" {
		t.Errorf("Commit Username is %s, want %s", name, "GitLab dev user")
	}
}

func TestMergeEventUnmarshalFromGroup(t *testing.T) {
	jsonObject := loadFixture("testdata/webhooks/group_merge_request.json")

	var event *MergeEvent
	err := json.Unmarshal(jsonObject, &event)

	if err != nil {
		t.Errorf("Group Merge Event can not unmarshaled: %v\n ", err.Error())
	}

	if event == nil {
		t.Errorf("Group Merge Event is null")
	}

	if event.ObjectKind != "merge_request" {
		t.Errorf("ObjectKind is %v, want %v", event.ObjectKind, "merge_request")
	}

	if event.User.Username != "root" {
		t.Errorf("User.Username is %v, want %v", event.User.Username, "root")
	}

	if event.Project.Name != exampleProjectName {
		t.Errorf("Project.Name is %v, want %v", event.Project.Name, exampleProjectName)
	}

	if event.ObjectAttributes.ID != 15917 {
		t.Errorf("ObjectAttributes.ID is %v, want %v", event.ObjectAttributes.ID, 15917)
	}

	if event.ObjectAttributes.Source.Name != exampleProjectName {
		t.Errorf("ObjectAttributes.Source.Name is %v, want %v", event.ObjectAttributes.Source.Name, exampleProjectName)
	}

	if event.ObjectAttributes.LastCommit.Author.Email != "test.user@mail.com" {
		t.Errorf("ObjectAttributes.LastCommit.Author.Email is %v, want %v", event.ObjectAttributes.LastCommit.Author.Email, "test.user@mail.com")
	}

	if event.Repository.Name != exampleProjectName {
		t.Errorf("Repository.Name is %v, want %v", event.Repository.Name, exampleProjectName)
	}

	if event.Assignee.Username != "root" {
		t.Errorf("Assignee.Username is %v, want %v", event.Assignee, "root")
	}

	if event.User.Name == "" {
		t.Errorf("Username is %s, want %s", event.User.Name, "Administrator")
	}

	if event.ObjectAttributes.LastCommit.Timestamp == nil {
		t.Errorf("Timestamp isn't nil")
	}

	if name := event.ObjectAttributes.LastCommit.Author.Name; name != "Test User" {
		t.Errorf("Commit Username is %s, want %s", name, "Test User")
	}
}

func TestPipelineEventUnmarshal(t *testing.T) {
	jsonObject := loadFixture("testdata/webhooks/pipeline.json")

	var event *PipelineEvent
	err := json.Unmarshal(jsonObject, &event)

	if err != nil {
		t.Errorf("Pipeline Event can not unmarshaled: %v\n ", err.Error())
	}

	if event == nil {
		t.Errorf("Pipeline Event is null")
	}

	if event.ObjectAttributes.ID != 31 {
		t.Errorf("ObjectAttributes is %v, want %v", event.ObjectAttributes.ID, 1977)
	}

	if event.User.Name == "" {
		t.Errorf("Username is %s, want %s", event.User.Name, "Administrator")
	}

	if event.Commit.Timestamp == nil {
		t.Errorf("Timestamp isn't nil")
	}

	if name := event.Commit.Author.Name; name != "User" {
		t.Errorf("Commit Username is %s, want %s", name, "User")
	}
}

func TestPushEventUnmarshal(t *testing.T) {
	jsonObject := loadFixture("testdata/webhooks/push.json")
	var event *PushEvent
	err := json.Unmarshal(jsonObject, &event)

	if err != nil {
		t.Errorf("Push Event can not unmarshaled: %v\n ", err.Error())
	}

	if event == nil {
		t.Errorf("Push Event is null")
	}

	if event.ProjectID != 15 {
		t.Errorf("ProjectID is %v, want %v", event.ProjectID, 15)
	}

	if event.UserName != exampleEventUserName {
		t.Errorf("Username is %s, want %s", event.UserName, exampleEventUserName)
	}

	if event.Commits[0] == nil || event.Commits[0].Timestamp == nil {
		t.Errorf("Commit Timestamp isn't nil")
	}

	if event.Commits[0] == nil || event.Commits[0].Author.Name != "Jordi Mallach" {
		t.Errorf("Commit Username is %s, want %s", event.UserName, "Jordi Mallach")
	}
}

func TestReleaseEventUnmarshal(t *testing.T) {
	jsonObject := loadFixture("testdata/webhooks/release.json")

	var event *ReleaseEvent
	err := json.Unmarshal(jsonObject, &event)

	if err != nil {
		t.Errorf("Release Event can not unmarshaled: %v\n ", err.Error())
	}

	if event == nil {
		t.Errorf("Release Event is null")
	}

	if event.Project.ID != 327622 {
		t.Errorf("Project.ID is %v, want %v", event.Project.ID, 327622)
	}

	if event.Commit.Title != "Merge branch 'example-branch' into 'master'" {
		t.Errorf("Commit title is %s, want %s", event.Commit.Title, "Merge branch 'example-branch' into 'master'")
	}

	if len(event.Assets.Sources) != 4 {
		t.Errorf("Asset sources length is %d, want %d", len(event.Assets.Sources), 4)
	}

	if event.Assets.Sources[0].Format != "zip" {
		t.Errorf("First asset source format is %s, want %s", event.Assets.Sources[0].Format, "zip")
	}

	if len(event.Assets.Links) != 1 {
		t.Errorf("Asset links length is %d, want %d", len(event.Assets.Links), 1)
	}

	if event.Assets.Links[0].Name != "Changelog" {
		t.Errorf("First asset link name is %s, want %s", event.Assets.Links[0].Name, "Changelog")
	}

	if event.Commit.Author.Name != "User" {
		t.Errorf("Commit author name is %s, want %s", event.Commit.Author.Name, "User")
	}
}
<|endoftext|>


<commit_before>// +build linux

package qemu

import (
	"fmt"
	"os"
	"os/exec"
	"strings"
	"syscall"
	"unsafe"

	"github.com/golang/glog"
	"github.com/hyperhq/runv/hypervisor/network"
)

const (
	IFNAMSIZ       = 16
	CIFF_TAP       = 0x0002
	CIFF_NO_PI     = 0x1000
	CIFF_ONE_QUEUE = 0x2000
)

type ifReq struct {
	Name  [IFNAMSIZ]byte
	Flags uint16
	pad   [0x28 - 0x10 - 2]byte
}

func GetTapFd(device, bridge, options string) (int, error) {
	var (
		req   ifReq
		errno syscall.Errno
	)

	tapFile, err := os.OpenFile("/dev/net/tun", os.O_RDWR, 0)
	if err != nil {
		return -1, err
	}

	req.Flags = CIFF_TAP | CIFF_NO_PI | CIFF_ONE_QUEUE
	copy(req.Name[:len(req.Name)-1], []byte(device))
	_, _, errno = syscall.Syscall(syscall.SYS_IOCTL, tapFile.Fd(),
		uintptr(syscall.TUNSETIFF),
		uintptr(unsafe.Pointer(&req)))
	if errno != 0 {
		tapFile.Close()
		return -1, fmt.Errorf("create tap device failed\n")
	}
	_, _, errno = syscall.Syscall(syscall.SYS_IOCTL, tapFile.Fd(), uintptr(syscall.TUNSETPERSIST), 0)
	if errno != 0 {
		tapFile.Close()
		return -1, fmt.Errorf("clear tap device persist flag failed\n")
	}

	err = network.UpAndAddToBridge(device, bridge, options)
	if err != nil {
		glog.Errorf("Add to bridge failed %s %s", bridge, device)
		tapFile.Close()
		return -1, err
	}

	return int(tapFile.Fd()), nil
}

func GetVhostUserPort(device, bridge, sockPath, option string) error {
	glog.V(3).Infof("Found ovs bridge %s, attaching tap %s to it\n", bridge, device)
	// append vhost-server-path
	options := fmt.Sprintf("vhost-server-path=%s/%s", sockPath, device)
	if option != "" {
		options = options + "," + option
	}

	// ovs command "ovs-vsctl add-port BRIDGE PORT" add netwok device PORT to BRIDGE,
	// PORT and BRIDGE here indicate the device name respectively.
	out, err := exec.Command("ovs-vsctl", "--may-exist", "add-port", bridge, device, "--", "set", "Interface", device, "type=dpdkvhostuserclient", "options:"+options).CombinedOutput()
	if err != nil {
		return fmt.Errorf("Ovs failed to add port: %s, error :%v", strings.TrimSpace(string(out)), err)
	}

	return nil
}
<commit_msg>Fix network performance issue on arm64 for runv<commit_after>// +build linux

package qemu

import (
	"fmt"
	"os"
	"os/exec"
	"strings"
	"syscall"
	"unsafe"

	"github.com/golang/glog"
	"github.com/hyperhq/runv/hypervisor/network"
)

const (
	IFNAMSIZ       = 16
	CIFF_TAP       = 0x0002
	CIFF_NO_PI     = 0x1000
	CIFF_ONE_QUEUE = 0x2000
	CIFF_VNET_HDR  = 0x4000
)

type ifReq struct {
	Name  [IFNAMSIZ]byte
	Flags uint16
	pad   [0x28 - 0x10 - 2]byte
}

func GetTapFd(device, bridge, options string) (int, error) {
	var (
		req   ifReq
		errno syscall.Errno
	)

	tapFile, err := os.OpenFile("/dev/net/tun", os.O_RDWR, 0)
	if err != nil {
		return -1, err
	}

	req.Flags = CIFF_TAP | CIFF_NO_PI | CIFF_ONE_QUEUE | CIFF_VNET_HDR
	copy(req.Name[:len(req.Name)-1], []byte(device))
	_, _, errno = syscall.Syscall(syscall.SYS_IOCTL, tapFile.Fd(),
		uintptr(syscall.TUNSETIFF),
		uintptr(unsafe.Pointer(&req)))
	if errno != 0 {
		tapFile.Close()
		return -1, fmt.Errorf("create tap device failed\n")
	}
	_, _, errno = syscall.Syscall(syscall.SYS_IOCTL, tapFile.Fd(), uintptr(syscall.TUNSETPERSIST), 0)
	if errno != 0 {
		tapFile.Close()
		return -1, fmt.Errorf("clear tap device persist flag failed\n")
	}

	err = network.UpAndAddToBridge(device, bridge, options)
	if err != nil {
		glog.Errorf("Add to bridge failed %s %s", bridge, device)
		tapFile.Close()
		return -1, err
	}

	return int(tapFile.Fd()), nil
}

func GetVhostUserPort(device, bridge, sockPath, option string) error {
	glog.V(3).Infof("Found ovs bridge %s, attaching tap %s to it\n", bridge, device)
	// append vhost-server-path
	options := fmt.Sprintf("vhost-server-path=%s/%s", sockPath, device)
	if option != "" {
		options = options + "," + option
	}

	// ovs command "ovs-vsctl add-port BRIDGE PORT" add netwok device PORT to BRIDGE,
	// PORT and BRIDGE here indicate the device name respectively.
	out, err := exec.Command("ovs-vsctl", "--may-exist", "add-port", bridge, device, "--", "set", "Interface", device, "type=dpdkvhostuserclient", "options:"+options).CombinedOutput()
	if err != nil {
		return fmt.Errorf("Ovs failed to add port: %s, error :%v", strings.TrimSpace(string(out)), err)
	}

	return nil
}
<|endoftext|>


<commit_before>// Copyright 2015 Davis Webb
// Copyright 2015 Zhandos Suleimenov
// Copyright 2015 Luke Shumaker

package handlers

import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/jinzhu/gorm"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"net/mail"
	"net/url"
	"os"
	"periwinkle/cfg"
	"periwinkle/store"
	"periwinkle/twilio"
	"strings"
	"time"
)

func HandleSMS(r io.Reader, name string, db *gorm.DB) uint8 {
	panic("TODO")
}

// Returns the status of the message: queued, sending, sent,
// delivered, undelivered, failed.  If an error occurs, it returns
// Error.
func sender(message mail.Message, to string) (status string, err error) {
	group := message.Header.Get("From")
	user := store.GetUserByAddress(cfg.DB, "email", message.Header.Get("From"))

	sms_from := group                   // TODO: numberFor(group)
	sms_to := strings.Split(to, "@")[1] //test 0 or 1
	sms_body := user.FullName + ":" + message.Header.Get("Subject")

	// account SID for Twilio account
	account_sid := os.Getenv("TWILIO_ACCOUNTID")

	// Authorization token for Twilio account
	auth_token := os.Getenv("TWILIO_TOKEN")

	messages_url := "https://api.twilio.com/2010-04-01/Accounts/" + account_sid + "/Messages.json"

	v := url.Values{}
	v.Set("From", sms_from)
	v.Set("To", sms_to)
	v.Set("Body", sms_body)
	v.Set("StatusCallback", "http://"+cfg.WebRoot+"/callbacks/twilio-sms")

	client := &http.Client{}

	req, err := http.NewRequest("POST", messages_url, bytes.NewBuffer([]byte(v.Encode())))
	if err != nil {
		return
	}
	req.SetBasicAuth(account_sid, auth_token)
	req.Header.Add("Accept", "application/json")
	req.Header.Add("Content-Type", "application/x-www-form-urlencoded")

	resp, err := client.Do(req)
	defer resp.Body.Close()
	if err != nil {
		return
	}

	if resp.StatusCode == 200 || resp.StatusCode == 201 {

		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			log.Println(err)
		}

		message := twilio.Message{}
		json.Unmarshal([]byte(body), &message)
		sms_status, err := SmsWaitForCallback(message.Sid)

		if err != nil {
			log.Println(err)
		}

		time.Sleep(time.Second)
		if sms_status.ErrorCode != "" {
			return sms_status.MessageStatus, fmt.Errorf("%s", sms_status.ErrorCode)
		}
		if sms_status.MessageStatus == "queued" || sms_status.MessageStatus == "sending" || sms_status.MessageStatus == "sent" {
			time.Sleep(time.Second)
		}
		status = sms_status.MessageStatus
		err = fmt.Errorf("%s", sms_status.ErrorCode)
		return status, err
	} else {
		err = fmt.Errorf("%s", resp.Status)
		return
	}
}
<commit_msg>smshandler fix<commit_after>// Copyright 2015 Davis Webb
// Copyright 2015 Zhandos Suleimenov
// Copyright 2015 Luke Shumaker

package handlers

import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/jinzhu/gorm"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"net/mail"
	"net/url"
	"os"
	"periwinkle/cfg"
	"periwinkle/store"
	"periwinkle/twilio"
	"strings"
	"time"
	"postfixpipe"
)

func HandleSMS(r io.Reader, name string, db *gorm.DB) uint8 {
	message, err := mail.ReadMessage(r)
	if err != nil {
		return postfixpipe.EX_NOINPUT
	}
	status, err := sender(*message, name, db)
	if err != nil {
		log.Println(err)
		return postfixpipe.EX_NOINPUT
	}
	log.Println(status)
	return postfixpipe.EX_OK
}

// Returns the status of the message: queued, sending, sent,
// delivered, undelivered, failed.  If an error occurs, it returns
// Error.
func sender(message mail.Message, to string, db *gorm.DB) (status string, err error) {
	//group := message.Header.Get("From")
	user := store.GetUserByAddress(db, "email", message.Header.Get("From"))

	sms_from := "+17653569541"   // TODO: group:numberFor(group)
	sms_to := strings.Split(to, "@")[1] //test 0 or 1
	sms_body := user.FullName + ":" + message.Header.Get("Subject")

	// account SID for Twilio account
	account_sid := os.Getenv("TWILIO_ACCOUNTID")

	// Authorization token for Twilio account
	auth_token := os.Getenv("TWILIO_TOKEN")

	messages_url := "https://api.twilio.com/2010-04-01/Accounts/" + account_sid + "/Messages.json"

	v := url.Values{}
	v.Set("From", sms_from)
	v.Set("To", sms_to)
	v.Set("Body", sms_body)
	v.Set("StatusCallback", "http://"+cfg.WebRoot+"/callbacks/twilio-sms")

	client := &http.Client{}

	req, err := http.NewRequest("POST", messages_url, bytes.NewBuffer([]byte(v.Encode())))
	if err != nil {
		return
	}
	req.SetBasicAuth(account_sid, auth_token)
	req.Header.Add("Accept", "application/json")
	req.Header.Add("Content-Type", "application/x-www-form-urlencoded")

	resp, err := client.Do(req)
	defer resp.Body.Close()
	if err != nil {
		return
	}

	if resp.StatusCode == 200 || resp.StatusCode == 201 {

		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			return "", fmt.Errorf("%v", err)
		}

		message := twilio.Message{}
		json.Unmarshal([]byte(body), &message)
		sms_status, err := SmsWaitForCallback(message.Sid)

		if err != nil {
			return "", fmt.Errorf("%v", err)
		}

		if sms_status.MessageStatus == "undelivered" || sms_status.MessageStatus == "failed" {
			return sms_status.MessageStatus, fmt.Errorf("%s", sms_status.ErrorCode)
		}
		if sms_status.MessageStatus == "queued" || sms_status.MessageStatus == "sending" || sms_status.MessageStatus == "sent" {
			time.Sleep(time.Second)
			sms_status, err = SmsWaitForCallback(message.Sid)

			if err != nil {
				return "", fmt.Errorf("%s", err)
			}
		}

		if sms_status.MessageStatus == "undelivered" || sms_status.MessageStatus == "failed" {
			return sms_status.MessageStatus, fmt.Errorf("%s", sms_status.ErrorCode)
		}

		status = sms_status.MessageStatus
		err = nil
		return status, err
	} else {
		err = fmt.Errorf("%s", resp.Status)
		return
	}
}
<|endoftext|>


<commit_before>package pachyderm

import (
	"context"
	"errors"

	"github.com/hashicorp/vault/logical"
	"github.com/hashicorp/vault/logical/framework"
	pclient "github.com/pachyderm/pachyderm/src/client"
	"github.com/pachyderm/pachyderm/src/client/auth"
)

func (b *backend) revokePath() *framework.Path {

	return &framework.Path{
		Pattern: "revoke",
		Fields: map[string]*framework.FieldSchema{
			"user_token": &framework.FieldSchema{
				Type: framework.TypeString,
			},
		},
		Callbacks: map[logical.Operation]framework.OperationFunc{
			logical.UpdateOperation: b.pathRevoke,
		},
	}
}

func (b *backend) pathRevoke(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
	userToken := d.Get("user_token").(string)
	if len(userToken) == 0 {
		return nil, logical.ErrInvalidRequest
	}

	config, err := b.Config(ctx, req.Storage)
	if err != nil {
		return nil, err
	}
	if len(config.AdminToken) == 0 {
		return nil, errors.New("plugin is missing admin token")
	}
	if len(config.PachdAddress) == 0 {
		return nil, errors.New("plugin is missing pachd_address")
	}

	err = b.revokeUserCredentials(ctx, config.PachdAddress, userToken, config.AdminToken)
	if err != nil {
		return nil, err
	}

	// Compose the response
	// TODO: Not sure if this is the right way to return a successful response
	return &logical.Response{
		Auth: &logical.Auth{},
	}, nil
}

func (b *backend) revokeUserCredentials(ctx context.Context, pachdAddress string, userToken string, adminToken string) error {
	// This is where we'd make the actual pachyderm calls to create the user
	// token using the admin token. For now, for testing purposes, we just do an action that only an
	// admin could do

	// Setup a single use client w the given admin token / address
	client, err := pclient.NewFromAddress(pachdAddress)
	if err != nil {
		return err
	}
	client = client.WithCtx(ctx)
	client.SetAuthToken(adminToken)

	_, err = client.AuthAPIClient.ModifyAdmins(client.Ctx(), &auth.ModifyAdminsRequest{
		Remove: []string{"tweetybird"},
	})

	if err != nil {
		return err
	}

	return nil
}
<commit_msg>Implement /revoke in vault plugin<commit_after>package pachyderm

import (
	"context"
	"errors"

	"github.com/hashicorp/vault/logical"
	"github.com/hashicorp/vault/logical/framework"
	pclient "github.com/pachyderm/pachyderm/src/client"
	"github.com/pachyderm/pachyderm/src/client/auth"
)

func (b *backend) revokePath() *framework.Path {

	return &framework.Path{
		Pattern: "revoke",
		Fields: map[string]*framework.FieldSchema{
			"user_token": &framework.FieldSchema{
				Type: framework.TypeString,
			},
		},
		Callbacks: map[logical.Operation]framework.OperationFunc{
			logical.UpdateOperation: b.pathRevoke,
		},
	}
}

func (b *backend) pathRevoke(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
	userToken := d.Get("user_token").(string)
	if len(userToken) == 0 {
		return nil, logical.ErrInvalidRequest
	}

	config, err := b.Config(ctx, req.Storage)
	if err != nil {
		return nil, err
	}
	if len(config.AdminToken) == 0 {
		return nil, errors.New("plugin is missing admin token")
	}
	if len(config.PachdAddress) == 0 {
		return nil, errors.New("plugin is missing pachd_address")
	}

	err = b.revokeUserCredentials(ctx, config.PachdAddress, userToken, config.AdminToken)
	if err != nil {
		return nil, err
	}

	// Compose the response
	// TODO: Not sure if this is the right way to return a successful response
	return &logical.Response{
		Auth: &logical.Auth{},
	}, nil
}

func (b *backend) revokeUserCredentials(ctx context.Context, pachdAddress string, userToken string, adminToken string) error {
	// Setup a single use client w the given admin token / address
	client, err := pclient.NewFromAddress(pachdAddress)
	if err != nil {
		return err
	}
	client = client.WithCtx(ctx)
	client.SetAuthToken(adminToken)
	_, err = client.AuthAPIClient.RevokeAuthToken(client.Ctx(), &auth.RevokeAuthTokenRequest{
		Token: userToken,
	})
	return err
}
<|endoftext|>


<commit_before>package aws

import (
	"github.com/hashicorp/terraform/helper/resource"
)

// resourceMap is the mapping of resources we support to their basic
// operations. This makes it easy to implement new resource types.
var resourceMap *resource.Map

func init() {
	resourceMap = &resource.Map{
		Mapping: map[string]resource.Resource{
			"aws_elb": resource.Resource{
				Create:  resource_aws_elb_create,
				Update:  resource_aws_elb_update,
				Destroy: resource_aws_elb_destroy,
				Diff:    resource_aws_elb_diff,
				Refresh: resource_aws_elb_refresh,
			},

			"aws_eip": resource.Resource{
				Create:  resource_aws_eip_create,
				Destroy: resource_aws_eip_destroy,
				Diff:    resource_aws_eip_diff,
				Refresh: resource_aws_eip_refresh,
			},

			"aws_instance": resource.Resource{
				Create:  resource_aws_instance_create,
				Destroy: resource_aws_instance_destroy,
				Diff:    resource_aws_instance_diff,
				Refresh: resource_aws_instance_refresh,
			},

			"aws_internet_gateway": resource.Resource{
				Create:  resource_aws_internet_gateway_create,
				Destroy: resource_aws_internet_gateway_destroy,
				Diff:    resource_aws_internet_gateway_diff,
				Refresh: resource_aws_internet_gateway_refresh,
			},

			"aws_route_table": resource.Resource{
				Create:  resource_aws_route_table_create,
				Destroy: resource_aws_route_table_destroy,
				Diff:    resource_aws_route_table_diff,
				Refresh: resource_aws_route_table_refresh,
			},

			"aws_security_group": resource.Resource{
				Create:  resource_aws_security_group_create,
				Destroy: resource_aws_security_group_destroy,
				Diff:    resource_aws_security_group_diff,
				Refresh: resource_aws_security_group_refresh,
			},

			"aws_subnet": resource.Resource{
				Create:  resource_aws_subnet_create,
				Destroy: resource_aws_subnet_destroy,
				Diff:    resource_aws_subnet_diff,
				Refresh: resource_aws_subnet_refresh,
			},

			"aws_vpc": resource.Resource{
				Create:  resource_aws_vpc_create,
				Destroy: resource_aws_vpc_destroy,
				Diff:    resource_aws_vpc_diff,
				Refresh: resource_aws_vpc_refresh,
			},
		},
	}
}
<commit_msg>providers/aws: validation of route table<commit_after>package aws

import (
	"github.com/hashicorp/terraform/helper/config"
	"github.com/hashicorp/terraform/helper/resource"
)

// resourceMap is the mapping of resources we support to their basic
// operations. This makes it easy to implement new resource types.
var resourceMap *resource.Map

func init() {
	resourceMap = &resource.Map{
		Mapping: map[string]resource.Resource{
			"aws_elb": resource.Resource{
				Create:  resource_aws_elb_create,
				Update:  resource_aws_elb_update,
				Destroy: resource_aws_elb_destroy,
				Diff:    resource_aws_elb_diff,
				Refresh: resource_aws_elb_refresh,
			},

			"aws_eip": resource.Resource{
				Create:  resource_aws_eip_create,
				Destroy: resource_aws_eip_destroy,
				Diff:    resource_aws_eip_diff,
				Refresh: resource_aws_eip_refresh,
			},

			"aws_instance": resource.Resource{
				Create:  resource_aws_instance_create,
				Destroy: resource_aws_instance_destroy,
				Diff:    resource_aws_instance_diff,
				Refresh: resource_aws_instance_refresh,
			},

			"aws_internet_gateway": resource.Resource{
				Create:  resource_aws_internet_gateway_create,
				Destroy: resource_aws_internet_gateway_destroy,
				Diff:    resource_aws_internet_gateway_diff,
				Refresh: resource_aws_internet_gateway_refresh,
			},

			"aws_route_table": resource.Resource{
				ConfigValidator: &config.Validator{
					Required: []string{"vpc_id"},
				},
				Create:  resource_aws_route_table_create,
				Destroy: resource_aws_route_table_destroy,
				Diff:    resource_aws_route_table_diff,
				Refresh: resource_aws_route_table_refresh,
			},

			"aws_security_group": resource.Resource{
				Create:  resource_aws_security_group_create,
				Destroy: resource_aws_security_group_destroy,
				Diff:    resource_aws_security_group_diff,
				Refresh: resource_aws_security_group_refresh,
			},

			"aws_subnet": resource.Resource{
				Create:  resource_aws_subnet_create,
				Destroy: resource_aws_subnet_destroy,
				Diff:    resource_aws_subnet_diff,
				Refresh: resource_aws_subnet_refresh,
			},

			"aws_vpc": resource.Resource{
				Create:  resource_aws_vpc_create,
				Destroy: resource_aws_vpc_destroy,
				Diff:    resource_aws_vpc_diff,
				Refresh: resource_aws_vpc_refresh,
			},
		},
	}
}
<|endoftext|>