-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
246 lines (212 loc) · 5.89 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
package main
import (
"bufio"
"bytes"
"fmt"
"github.com/mdaffin/go-telegraf"
"golang.org/x/image/bmp"
"golang.org/x/image/tiff"
"image"
"io/ioutil"
"log"
"net/http"
"os"
"time"
"path/filepath"
"image/jpeg"
"net/url"
"strings"
)
const (
// DefaultTsDirectoryStructure is the default directory structure for timestreams
DefaultTsDirectoryStructure = "2006/2006_01/2006_01_02/2006_01_02_15/"
// TsForm is the timestamp form for individual files.
TsForm = "2006_01_02_15_04_05"
)
var (
errLog *log.Logger
name string
interval time.Duration
)
type Metric struct {
OutputSize_b int
DecodeTime_s, EncodeTime_s, RequestTime_s float64
RequestStatusCode int
RequestContentLength_b int64
RequestStatus string
RequestContentType string
}
var netClient = &http.Client{
Timeout: time.Second * 60,
}
func stringInSlice(a string, list []string) bool {
for _, b := range list {
if b == a {
return true
}
}
return false
}
// unmarshalExtraTags turns a list of comma separated key=value pairs into a map
func unmarshalExtraTags(tagString string) (tags map[string]string, err error) {
tags = make(map[string]string)
for _, pair := range strings.Split(tagString, ","){
p := strings.Split(pair, "=")
if len(p) != 2 {
err = fmt.Errorf("couldn't parse %s into 2 items for extra tags\n", pair)
return
}
tagKey, tagValue := p[0], p[1]
tags[tagKey] = tagValue
}
return
}
func capture(filePath string) {
telegrafHost := "telegraf:8092"
if os.Getenv("TELEGRAF_HOST") != ""{
telegrafHost = os.Getenv("TELEGRAF_HOST")
}
telegrafClient, err := telegraf.NewUDP(telegrafHost)
if err != nil {
panic(err)
}
defer telegrafClient.Close()
m := telegraf.NewMeasurement("ipcamera")
m.AddTag("camera_name", name)
urlString := os.Getenv("URL")
if urlString == "" {
panic(fmt.Errorf("No URL environment var provided.\n"))
}
if extraTags, err := unmarshalExtraTags(os.Getenv("EXTRA_TAGS")); err == nil {
for tagKey, tagValue := range extraTags {
m.AddTag(tagKey, tagValue)
}
}else{
errLog.Println(err)
}
if u, err := url.Parse(urlString); err == nil{
m.AddTag("ipaddress", u.Host)
}else {
errLog.Println(err)
}
st := time.Now()
resp, err := netClient.Get(urlString)
m.AddFloat64("RequestTime_s", time.Now().Sub(st).Seconds())
if err != nil {
errLog.Println(err)
telegrafClient.Write(m)
return
}
m.AddTag("RequestStatus", resp.Status)
m.AddInt64("RequestStatusCode", int64(resp.StatusCode))
if !(resp.StatusCode >= 200 && resp.StatusCode <= 299) {
telegrafClient.Write(m)
return
}
errLog.Println(resp.Status)
contentType := resp.Header["Content-Type"][0]
m.AddTag("Content-Type", contentType)
var img image.Image
// todo: check if contentType == IMAGETYPE and write out image without decoding and re-encoding.
if contentType == "image/bmp" {
st = time.Now()
img, err = bmp.Decode(resp.Body)
m.AddFloat64("DecodeTime_s", time.Now().Sub(st).Seconds())
if err != nil {
panic(err)
}
} else if stringInSlice(contentType, []string{"image/png", "image/jpg", "image/jpeg"}) {
st = time.Now()
img, _, err = image.Decode(resp.Body)
m.AddFloat64("DecodeTime_s", time.Now().Sub(st).Seconds())
if err != nil {
panic(err)
}
} else {
panic(fmt.Errorf("unknown image format %s\n", contentType))
}
st = time.Now()
var imageBytes []byte
if stringInSlice(os.Getenv("IMAGETYPE"), []string{"jpeg", "jpg", "JPG", "JPEG"}) {
var jpegBytes bytes.Buffer
jpegWriter := bufio.NewWriter(&jpegBytes)
err = jpeg.Encode(jpegWriter, img, &jpeg.Options{Quality: 90})
if err != nil {
panic(err)
}
jpegWriter.Flush()
imageBytes = jpegBytes.Bytes()
m.AddFloat64("EncodeTime_s", time.Now().Sub(st).Seconds())
} else {
var tiffbytes bytes.Buffer
tiffwriter := bufio.NewWriter(&tiffbytes)
err = tiff.Encode(tiffwriter, img, &tiff.Options{Compression: tiff.Deflate})
if err != nil {
panic(err)
}
tiffwriter.Flush()
imageBytes = tiffbytes.Bytes()
m.AddFloat64("EncodeTime_s", time.Now().Sub(st).Seconds())
}
m.AddInt("OutputSize_b", len(imageBytes))
dirPath := filepath.Dir(filePath)
if _, err := os.Stat(dirPath); os.IsNotExist(err) {
os.MkdirAll(dirPath, 0775)
}
if err = ioutil.WriteFile(filePath, imageBytes, 0665); err != nil {
panic(err)
}
errLog.Printf("Wrote File %s\n", filePath)
telegrafClient.Write(m)
}
func init() {
errLog = log.New(os.Stderr, "[ipeye] ", log.Ldate|log.Ltime|log.Lshortfile)
intervalStr := os.Getenv("INTERVAL")
if intervalStr == "" {
intervalStr = "10m"
}
var err error
interval, err = time.ParseDuration(intervalStr)
if err != nil {
panic(err)
}
if name = os.Getenv("NAME"); name == "" {
name, err = os.Hostname()
if err != nil {
panic(err)
}
}
errLog.Println(name)
errLog.Println(interval)
errLog.Println(os.Getenv("TAGS"))
}
func getImagePath(theTime time.Time) string {
directory := theTime.Format(DefaultTsDirectoryStructure)
timestamp := theTime.Format(TsForm)
filename := fmt.Sprintf("%s_%s_00.tiff", name, timestamp)
if stringInSlice(os.Getenv("IMAGETYPE"), []string{"jpeg", "jpg", "JPG", "JPEG"}){
filename = fmt.Sprintf("%s_%s_00.%s", name, timestamp, os.Getenv("IMAGETYPE"))
}
outputPath := os.Getenv("OUTPUT")
if outputPath == ""{
outputPath = "/data"
}
return filepath.Join(outputPath, directory, filename)
}
func main() {
waitForNextTimepoint := time.After(time.Until(time.Now().Add(interval).Truncate(interval)))
errLog.Println("Waiting until "+time.Now().Add(interval).Truncate(interval).Format(time.RubyDate))
select {
case t:=<-waitForNextTimepoint:
capture(getImagePath(t.Truncate(interval)))
break
}
ticker := time.NewTicker(interval)
for {
select {
case t:= <-ticker.C:
capture(getImagePath(t.Truncate(interval)))
errLog.Println("Waiting until "+time.Now().Add(interval).Truncate(interval).Format(time.RubyDate))
}
}
}