<commit_before>package metricdef

import (
	"encoding/json"
	"fmt"
	elastigo "github.com/mattbaird/elastigo/lib"
	"log"
	"time"
)

type MetricDefinition struct {
	ID         string `json:"id"`
	Name       string `json:"name"`
	Account    int    `json:"account"`
	Location   string `json:"location`
	Metric     string `json:"metric"`
	TargetType string `json:"target_type"` // an emum ["derive","gauge"] in nodejs
	Unit       string `json:"unit"`
	Interval   int    `json:"interval"` // minimum 10
	Site       int    `json:"site"`
	LastUpdate int64  `json:"lastUpdate"` // unix epoch time, per the nodejs definition
	Monitor    int    `json:"monitor"`
	Thresholds struct {
		WarnMin interface{} `json:"warnMin"`
		WarnMax interface{} `json:"warnMax"`
		CritMin interface{} `json:"critMin"`
		CritMax interface{} `json:"critMax"`
	} `json:"thresholds"`
	KeepAlives int  `json:"keepAlives"`
	State      int8 `json:"state"`
}

var es *elastigo.Conn

func init() {
	es = elastigo.NewConn()
	es.Domain = "elasticsearch" // needs to be configurable obviously
	// TODO: once this has gotten far enough to be able to start running
	// on its own without running in tandem with the nodejs client, the
	// elasticsearch indexes will need to be checked for existence and
	// created if necessary.
}

// required: name, account, target_type, interval, metric, unit

// These validate, and save to elasticsearch

func DefFromJSON(b []byte) (*MetricDefinition, error) {
	def := new(MetricDefinition)
	if err := json.Unmarshal(b, &def); err != nil {
		return nil, err
	}
	def.ID = fmt.Sprintf("%d.%s", def.Account, def.Name)
	return def, nil
}

func NewFromMessage(m map[string]interface{}) (*MetricDefinition, error) {
	log.Printf("incoming message: %+v", m)
	id := fmt.Sprintf("%d.%s", int64(m["account"].(float64)), m["name"])
	now := time.Now().Unix()

	var ka int
	if k, ok := m["keepAlives"].(float64) {
		ka = int(k)
	}

	// Thorough validation of the input needed once it's working.
	def := &MetricDefinition{ID: id, Name: m["name"].(string), Account: int(m["account"].(float64)), Location: m["location"].(string), Metric: m["metric"].(string), TargetType: m["target_type"].(string), Interval: int(m["interval"].(float64)), Site: int(m["site"].(float64)), LastUpdate: now, Monitor: int(m["monitor"].(float64)), KeepAlives: int(ka), State: int8(m["state"].(float64))}

	if t, exists := m["thresholds"]; exists {
		thresh, _ := t.(map[string]interface{})<commit_msg>guard against state not being in the message<commit_after>package metricdef

import (
	"encoding/json"
	"fmt"
	elastigo "github.com/mattbaird/elastigo/lib"
	"log"
	"time"
)

type MetricDefinition struct {
	ID         string `json:"id"`
	Name       string `json:"name"`
	Account    int    `json:"account"`
	Location   string `json:"location`
	Metric     string `json:"metric"`
	TargetType string `json:"target_type"` // an emum ["derive","gauge"] in nodejs
	Unit       string `json:"unit"`
	Interval   int    `json:"interval"` // minimum 10
	Site       int    `json:"site"`
	LastUpdate int64  `json:"lastUpdate"` // unix epoch time, per the nodejs definition
	Monitor    int    `json:"monitor"`
	Thresholds struct {
		WarnMin interface{} `json:"warnMin"`
		WarnMax interface{} `json:"warnMax"`
		CritMin interface{} `json:"critMin"`
		CritMax interface{} `json:"critMax"`
	} `json:"thresholds"`
	KeepAlives int  `json:"keepAlives"`
	State      int8 `json:"state"`
}

var es *elastigo.Conn

func init() {
	es = elastigo.NewConn()
	es.Domain = "elasticsearch" // needs to be configurable obviously
	// TODO: once this has gotten far enough to be able to start running
	// on its own without running in tandem with the nodejs client, the
	// elasticsearch indexes will need to be checked for existence and
	// created if necessary.
}

// required: name, account, target_type, interval, metric, unit

// These validate, and save to elasticsearch

func DefFromJSON(b []byte) (*MetricDefinition, error) {
	def := new(MetricDefinition)
	if err := json.Unmarshal(b, &def); err != nil {
		return nil, err
	}
	def.ID = fmt.Sprintf("%d.%s", def.Account, def.Name)
	return def, nil
}

func NewFromMessage(m map[string]interface{}) (*MetricDefinition, error) {
	log.Printf("incoming message: %+v", m)
	id := fmt.Sprintf("%d.%s", int64(m["account"].(float64)), m["name"])
	now := time.Now().Unix()

	var ka int
	switch k := m["keepAlives"].(type) {
        case float64:
                ka = int(k)
        }
        var state int8
        switch s := m["state"].(type) {
        case float64:
                state = int8(s)
        }

	// Thorough validation of the input needed once it's working.
	def := &MetricDefinition{ID: id, Name: m["name"].(string), Account: int(m["account"].(float64)), Location: m["location"].(string), Metric: m["metric"].(string), TargetType: m["target_type"].(string), Interval: int(m["interval"].(float64)), Site: int(m["site"].(float64)), LastUpdate: now, Monitor: int(m["monitor"].(float64)), KeepAlives: ka, State: state}

	if t, exists := m["thresholds"]; exists {
		thresh, _ := t.(map[string]interface{})
{'fraction_non_alphanumeric': 0.16168371361132966, 'fraction_numerical': 0.00885129819040126, 'mean_word_length': 4.064741035856573, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, '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': '2449211', 'n_tokens_mistral': 1699, 'n_tokens_neox': 1637, 'n_words': 483}