<commit_before>/*
   Copyright 2014 <NAME>

   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 mysqltest

import (
	"database/sql"
	//"encoding/json"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	//"log"
	//"io"
	"os"
	"path/filepath"
	//"reflect"
	"errors"
	"time"
)

var counts_to_check = []int64{1, 10, 50, 100, 150, 200, 250, 300, 600, 1200, 2400}
var seconds_to_check = []int64{0, 10, 30, 60, 120, 300, 600, 1200, 2400}

type MysqlTest struct {
	Name          string
	reportdir     string
	host          string
	user          string
	port          int
	pass          string
	interval      int
	timeout       int
	db            *sql.DB
	jsonlog       *os.File
	iteration     uint64
	maxjobs       uint
}


func RunMysqlTest(name string, host string, port int, user string, pass string, interval int, timeout int, reportdir string, jsonlog string) *MysqlTest {

	jsonlogfile, err := os.OpenFile(jsonlog, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
	if err != nil {
		panic(fmt.Sprintf("Couldn't open jsonlog \"%s\" for writing: %s", jsonlog, err.Error()))
	}
	defer jsonlogfile.Close()

	m := MysqlTest{Name: name, host: host, port: port, user: user, pass: <PASSWORD>, interval: interval, timeout: timeout, reportdir: reportdir, jsonlog: jsonlogfile, iteration: 1}

	m.Run()

  return &m
}

func (t *MysqlTest) Run() {
	if t.interval < 0 {
		panic("interval must be a positive integer, or 0 to run the tests only once.")
	}
	t.WriteResult(t.RunOnceWithTimeout()) // Run first test instantly.
	if t.interval > 0 {
		// run checks on intervals
		for _ = range time.Tick(time.Duration(t.interval) * time.Millisecond) {
			t.iteration++ // when this overflows it will become 0 with no problems http://play.golang.org/p/fbjwHKcIaU
			t.WriteResult(t.RunOnceWithTimeout())
		}
	}
}


// takes the MysqlTestResult and writes corresponding files
func (t *MysqlTest) WriteResult(res * MysqlTestResult) {
  for k,v := range res.Entries {
    t.WriteTextResult(k,v)
  }
}

// This is a very dumb json func. If more interesting stuff needs to be logged,
// pass it in as a map[string]interface{} and then detect value as int, string, w/e
// before marshaling json.
func (t *MysqlTest) JsonLog(msg string) {
	//t.logger.Println(json.Marshal(t))
	//buf, err := json.Marshal(v)
	//if err != nil {
	//	panic(err)
	//}
	//t.jsonlog.Write(buf)
	t.jsonlog.WriteString(fmt.Sprintf("{\"@timestamp\":\"%s\",\"type\":\"mysql_probe\",\"host\":\"%s\",\"iteration\":%v,\"message\":\"%s\"}\n",
		time.Now().Format(time.RFC3339), t.host, t.iteration, msg))
}

func (t *MysqlTest) GetWeight(val int64, max int64) string {
	if val == 0 {
		return "100%"
	}
	return fmt.Sprintf("%d%%", 100-(100*(val/max)))
}

// func writeHttpResult(reportdir string) {
//
// }

func (t *MysqlTest) RunOnceWithTimeout() *MysqlTestResult {
  timeout_ch := make(chan *MysqlTestResult, 1)
  ch := make(chan *MysqlTestResult, 1)

  // after 1 second, fill a blank response and
  // send that indicates everything timed out
  go func() {
    time.Sleep(time.Duration(t.timeout) * time.Millisecond)
    // fill timeout statuses up
    res := MysqlTestResult{}
    res.AddTextResult("connect", "down # timeout")
    for _,c := range counts_to_check {
      res.AddTextResult(fmt.Sprintf("connection_count_lte_%d", c), "down # timeout")
    }
    for _,c := range seconds_to_check {
       res.AddTextResult(fmt.Sprintf("replication_delay_lte_%d", c), "down # timeout")
    }
    timeout_ch <- &res
  }()

  // run the actual check with no delay
  // hopefully it wins.<commit_msg>Remove unused / commented out code<commit_after>/*
   Copyright 2014 <NAME>

   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 mysqltest

import (
	"database/sql"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	//"log"
	//"io"
	"os"
	"path/filepath"
	//"reflect"
	"errors"
	"time"
)

var counts_to_check = []int64{1, 10, 50, 100, 150, 200, 250, 300, 600, 1200, 2400}
var seconds_to_check = []int64{0, 10, 30, 60, 120, 300, 600, 1200, 2400}

type MysqlTest struct {
	Name          string
	reportdir     string
	host          string
	user          string
	port          int
	pass          string
	interval      int
	timeout       int
	db            *sql.DB
	jsonlog       *os.File
	iteration     uint64
	maxjobs       uint
}


func RunMysqlTest(name string, host string, port int, user string, pass string, interval int, timeout int, reportdir string, jsonlog string) *MysqlTest {

	jsonlogfile, err := os.OpenFile(jsonlog, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
	if err != nil {
		panic(fmt.Sprintf("Couldn't open jsonlog \"%s\" for writing: %s", jsonlog, err.Error()))
	}
	defer jsonlogfile.Close()

	m := MysqlTest{Name: name, host: host, port: port, user: user, pass: <PASSWORD>, interval: interval, timeout: timeout, reportdir: reportdir, jsonlog: jsonlogfile, iteration: 1}

	m.Run()

  return &m
}

func (t *MysqlTest) Run() {
	if t.interval < 0 {
		panic("interval must be a positive integer, or 0 to run the tests only once.")
	}
	t.WriteResult(t.RunOnceWithTimeout()) // Run first test instantly.
	if t.interval > 0 {
		// run checks on intervals
		for _ = range time.Tick(time.Duration(t.interval) * time.Millisecond) {
			t.iteration++ // when this overflows it will become 0 with no problems http://play.golang.org/p/fbjwHKcIaU
			t.WriteResult(t.RunOnceWithTimeout())
		}
	}
}


// takes the MysqlTestResult and writes corresponding files
func (t *MysqlTest) WriteResult(res * MysqlTestResult) {
  for k,v := range res.Entries {
    t.WriteTextResult(k,v)
  }
}

// This is a very dumb json func. If more interesting stuff needs to be logged,
// pass it in as a map[string]interface{} and then detect value as int, string, w/e
// before marshaling json.
func (t *MysqlTest) JsonLog(msg string) {
	t.jsonlog.WriteString(fmt.Sprintf("{\"@timestamp\":\"%s\",\"type\":\"mysql_probe\",\"host\":\"%s\",\"iteration\":%v,\"message\":\"%s\"}\n",
		time.Now().Format(time.RFC3339), t.host, t.iteration, msg))
}

func (t *MysqlTest) GetWeight(val int64, max int64) string {
	if val == 0 {
		return "100%"
	}
	return fmt.Sprintf("%d%%", 100-(100*(val/max)))
}

func (t *MysqlTest) RunOnceWithTimeout() *MysqlTestResult {
  timeout_ch := make(chan *MysqlTestResult, 1)
  ch := make(chan *MysqlTestResult, 1)

  // after 1 second, fill a blank response and
  // send that indicates everything timed out
  go func() {
    time.Sleep(time.Duration(t.timeout) * time.Millisecond)
    // fill timeout statuses up
    res := MysqlTestResult{}
    res.AddTextResult("connect", "down # timeout")
    for _,c := range counts_to_check {
      res.AddTextResult(fmt.Sprintf("connection_count_lte_%d", c), "down # timeout")
    }
    for _,c := range seconds_to_check {
       res.AddTextResult(fmt.Sprintf("replication_delay_lte_%d", c), "down # timeout")
    }
    timeout_ch <- &res
  }()

  // run the actual check with no delay
  // hopefully it wins.
{'fraction_non_alphanumeric': 0.13187230808208766, 'fraction_numerical': 0.02508234101849506, 'mean_word_length': 3.3594699061292106, 'pattern_counts': {'":': 10, '<': 11, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5358500', 'n_tokens_mistral': 2864, 'n_tokens_neox': 2633, 'n_words': 820}