-
Notifications
You must be signed in to change notification settings - Fork 5
/
imgwizard.go
683 lines (554 loc) · 14.8 KB
/
imgwizard.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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
package imgwizard
import (
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"path"
"regexp"
"strconv"
"strings"
"github.com/Azure/azure-sdk-for-go/storage"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/shifr/imgwizard/cache"
"github.com/shifr/vips"
)
type Route struct {
pattern *regexp.Regexp
handler http.Handler
}
type RegexpHandler struct {
routes []*Route
}
func (h *RegexpHandler) HandleFunc(pattern *regexp.Regexp, handler func(http.ResponseWriter, *http.Request)) {
h.routes = append(h.routes, &Route{pattern, http.HandlerFunc(handler)})
}
func (h *RegexpHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
for _, route := range h.routes {
if route.pattern.MatchString(r.URL.Path) {
route.handler.ServeHTTP(w, r)
return
}
}
http.NotFound(w, r)
}
type Context struct {
NoCache bool
OnlyCache bool
IsOriginal bool
Width int
Height int
AzureContainer string
S3Bucket string
Path string
RequestURI string
CachePath string
Storage string
SubPath string
OrigImage string
Query string
Options vips.Options
}
type Settings struct {
Scheme string
AllowedSizes []string
AllowedMedia []string
Directories []string
Nodes []string
UrlExp *regexp.Regexp
}
const (
VERSION = 1.5
DEFAULT_POOL_SIZE = 100000
WEBP_HEADER = "image/webp"
JPEG = "image/jpeg"
PNG = "image/png"
AZURE_ACCOUNT_NAME = "AZURE_ACCOUNT_NAME"
AZURE_ACCOUNT_KEY = "AZURE_ACCOUNT_KEY"
AWS_REGION = "AWS_REGION"
AWS_ACCESS_KEY_ID = "AWS_ACCESS_KEY_ID"
AWS_SECRET_ACCESS_KEY = "AWS_SECRET_ACCESS_KEY"
ONLY_CACHE_HEADER = "X-Cache-Only"
NO_CACHE_HEADER = "X-No-Cache"
CACHE_DESTINATION_HEADER = "X-Cache-Destination"
)
var (
DEBUG = false
WARNING = false
ClientConfirmed = false
DEFAULT_QUALITY = 80
Crop = map[string]vips.Gravity{
"top": vips.NORTH,
"right": vips.EAST,
"bottom": vips.SOUTH,
"left": vips.WEST,
}
ResizableImageTypes = []string{"image/jpeg", "image/png"}
Version bool
ListenAddr string
AllowedMedia string
AllowedSizes string
CacheDir string
S3BucketName string
AzureContainerName string
Default404 string
DirsToSearch string
Mark string
NoCacheKey string
Nodes string
Quality int
ChanPool chan int
Cache *cache.Cache
Options vips.Options
GlobalSettings Settings
AzureClient storage.BlobStorageClient
S3Client *s3.S3
)
func loadDefaults() {
if os.Getenv("DEBUG_ENABLED") != "" {
DEBUG = true
WARNING = true
}
if os.Getenv("WARNING_ENABLED") != "" {
WARNING = true
}
//defaults for vips
Options.Crop = true
Options.Enlarge = false
Options.Extend = vips.EXTEND_WHITE
Options.Interpolator = vips.BILINEAR
pool_size, err := strconv.Atoi(os.Getenv("IMGW_POOL_SIZE"))
if err != nil {
debug("Making channel with default size")
ChanPool = make(chan int, DEFAULT_POOL_SIZE)
} else {
debug("Making channe, size %d", pool_size)
ChanPool = make(chan int, pool_size)
}
Cache, err = cache.NewCache(S3BucketName, AzureContainerName)
if err != nil {
warning("Could not create cache object, reason - %s", err)
os.Exit(1)
}
azAccountName := os.Getenv(AZURE_ACCOUNT_NAME)
azAccountKey := os.Getenv(AZURE_ACCOUNT_KEY)
s3Region := os.Getenv(AWS_REGION)
s3AccessKey := os.Getenv(AWS_ACCESS_KEY_ID)
s3SecretKey := os.Getenv(AWS_SECRET_ACCESS_KEY)
if azAccountName != "" && azAccountKey != "" {
azureBasicCli, err := storage.NewBasicClient(azAccountName, azAccountKey)
if err != nil {
warning("Could not create AzureClient, reason - %s", err)
os.Exit(1)
}
AzureClient = azureBasicCli.GetBlobService()
log.Println("AzureClient created and confirmed")
ClientConfirmed = true
}
if s3Region != "" && s3AccessKey != "" && s3SecretKey != "" {
creds := credentials.NewStaticCredentials(s3AccessKey, s3SecretKey, "")
S3Client = s3.New(
session.New(&aws.Config{
Region: aws.String(s3Region),
Credentials: creds,
}))
log.Println("AWS S3 client created and confirmed")
ClientConfirmed = true
}
}
// makeCachePath generates cache path for resized image
func (c *Context) makeCachePath() {
var cacheImageName string
var imageFormat string
var subPath string
pathParts := strings.Split(c.Path, "/")
lastIndex := len(pathParts) - 1
imageName := pathParts[lastIndex]
imageNameParts := strings.Split(imageName, ".")
if len(imageNameParts) > 1 {
lastNameIndex := len(imageNameParts) - 1
imageName = strings.Join(imageNameParts[:lastNameIndex], ".")
imageFormat = imageNameParts[lastNameIndex]
}
if c.Options.Webp {
cacheImageName = fmt.Sprintf(
"%s_%dx%d_webp", imageName, c.Options.Width, c.Options.Height)
} else {
cacheImageName = fmt.Sprintf(
"%s_%dx%d", imageName, c.Options.Width, c.Options.Height)
}
if imageFormat != "" {
cacheImageName = fmt.Sprintf("%s.%s", cacheImageName, imageFormat)
}
subPath = strings.Join(pathParts[:lastIndex], "/")
switch c.Storage {
case "loc":
c.OrigImage, _ = url.QueryUnescape(c.Path)
case "az":
c.AzureContainer = pathParts[0]
subPath = strings.Join(pathParts[1:lastIndex], "/")
c.OrigImage, _ = url.QueryUnescape(fmt.Sprintf(
"%s/%s", subPath, pathParts[lastIndex]))
case "s3":
c.S3Bucket = pathParts[0]
subPath = strings.Join(pathParts[1:lastIndex], "/")
c.OrigImage, _ = url.QueryUnescape(fmt.Sprintf(
"%s/%s", subPath, pathParts[lastIndex]))
case "rem":
c.OrigImage = fmt.Sprintf("%s://%s", GlobalSettings.Scheme, c.Path)
}
if c.CachePath != "" {
return
}
if S3BucketName != "" || AzureContainerName != "" {
c.CachePath, _ = url.QueryUnescape(fmt.Sprintf(
"%s/%s", subPath, cacheImageName))
} else {
c.CachePath, _ = url.QueryUnescape(fmt.Sprintf(
"%s/%s/%s", CacheDir, subPath, cacheImageName))
}
if c.Query != "" {
c.CachePath = fmt.Sprintf(
"%s?%s", c.CachePath, c.Query)
}
}
func (c *Context) Fill(req *http.Request) {
acceptedTypes := strings.Split(req.Header.Get("Accept"), ",")
noCacheKey := req.Header.Get(NO_CACHE_HEADER)
onlyCacheHeader := req.Header.Get(ONLY_CACHE_HEADER)
cachePath := req.Header.Get(CACHE_DESTINATION_HEADER)
params := parseVars(req)
sizes := strings.Split(params["size"], "x")
c.Options = Options
c.Options.Gravity = vips.CENTRE
if crop := req.FormValue("crop"); crop != "" {
for _, g := range strings.Split(crop, ",") {
if v, ok := Crop[g]; ok {
c.Options.Gravity = c.Options.Gravity | v
}
}
}
if q := req.FormValue("q"); q != "" {
c.Options.Quality, _ = strconv.Atoi(q)
}
if o := req.FormValue("original"); o != "" {
c.IsOriginal = true
}
c.Options.Webp = stringExists(WEBP_HEADER, acceptedTypes)
c.Options.Width, _ = strconv.Atoi(sizes[0])
c.Options.Height, _ = strconv.Atoi(sizes[1])
c.NoCache = NoCacheKey != "" && NoCacheKey == noCacheKey
c.OnlyCache = onlyCacheHeader != ""
c.RequestURI = req.RequestURI
c.Storage = params["storage"]
c.Path = params["path"]
c.Query = params["query"]
c.CachePath = cachePath
c.makeCachePath()
}
// loadSettings loads settings from command-line
func (s *Settings) Load() {
loadDefaults()
s.Scheme = "http"
s.AllowedSizes = nil
s.AllowedMedia = nil
var sizes = "[0-9]*x[0-9]*"
var medias = ""
if AllowedMedia != "" {
s.AllowedMedia = strings.Split(AllowedMedia, ",")
}
if AllowedSizes != "" {
s.AllowedSizes = strings.Split(AllowedSizes, ",")
}
if DirsToSearch != "" {
s.Directories = strings.Split(DirsToSearch, ",")
}
if Nodes != "" {
s.Nodes = strings.Split(Nodes, ",")
}
if Quality != 0 {
DEFAULT_QUALITY = Quality
}
Options.Quality = DEFAULT_QUALITY
if len(s.AllowedSizes) > 0 {
sizes = strings.Join(s.AllowedSizes, "|")
}
if len(s.AllowedMedia) > 0 {
medias = strings.Join(s.AllowedMedia, "|")
}
template := fmt.Sprintf(
"/(?P<mark>%s)/(?P<storage>loc|rem|az|s3)/(?P<size>%s)/(?P<path>((%s)(.+)))",
Mark, sizes, medias)
debug("Template %s", template)
s.UrlExp, _ = regexp.Compile(template)
}
func fileExists(ctx *Context) (string, error) {
var filePath string
var err error
debug("Trying to find local image")
if len(GlobalSettings.Directories) > 0 {
for _, dir := range GlobalSettings.Directories {
filePath = path.Join("/", dir, ctx.OrigImage)
if _, err = os.Stat(filePath); err == nil {
return filePath, nil
}
}
return "", err
}
filePath = path.Join("/", ctx.OrigImage)
if _, err = os.Stat(filePath); os.IsNotExist(err) {
return "", err
}
return filePath, nil
}
// getLocalImage fetches original image from file system
func getLocalImage(ctx *Context, def bool) ([]byte, error) {
var image []byte
var err error
var filePath string
if def {
filePath = Default404
} else {
filePath, err = fileExists(ctx)
if err != nil {
return image, err
}
}
file, err := os.Open(filePath)
defer file.Close()
if err != nil {
return image, err
}
info, _ := file.Stat()
image = make([]byte, info.Size())
_, err = file.Read(image)
if err != nil {
return image, err
}
return image, nil
}
// getRemoteImage fetches original image by http url
func getRemoteImage(ctx *Context, isNode bool) ([]byte, error) {
var image []byte
var client = &http.Client{}
debug("Trying to fetch remote image: %s", ctx.OrigImage)
req, _ := http.NewRequest("GET", ctx.OrigImage, nil)
if isNode {
req.Header.Set(ONLY_CACHE_HEADER, "true")
req.Header.Set(CACHE_DESTINATION_HEADER, ctx.CachePath)
if ctx.Options.Webp {
req.Header.Set("Accept", WEBP_HEADER)
}
}
resp, err := client.Do(req)
defer resp.Body.Close()
if err != nil {
return image, err
}
if resp.StatusCode != http.StatusOK {
return image, errors.New("Not found")
}
image, err = ioutil.ReadAll(resp.Body)
return image, nil
}
// getAzureImage fetches original image AzureStorage
func getAzureImage(ctx *Context) ([]byte, error) {
var image []byte
var err error
debug("Trying to fetch azure image: '%s'", ctx.OrigImage)
rc, err := AzureClient.GetBlob(ctx.AzureContainer, ctx.OrigImage)
if err != nil {
return image, err
}
defer rc.Close()
image, err = ioutil.ReadAll(rc)
return image, err
}
// getS3Image fetches original image from AWS S3 storage
func getS3Image(ctx *Context) ([]byte, error) {
var image []byte
var err error
debug("Trying to fetch S3 image: '%s'", ctx.OrigImage)
params := &s3.GetObjectInput{
Bucket: aws.String(ctx.S3Bucket),
Key: aws.String(ctx.OrigImage),
}
resp, err := S3Client.GetObject(params)
if err != nil {
return image, err
}
defer resp.Body.Close()
image, err = ioutil.ReadAll(resp.Body)
return image, err
}
func checkCache(ctx *Context) ([]byte, error) {
var image []byte
var err error
debug("Get from cache, key: %s", ctx.CachePath)
if image, err = Cache.Get(ctx.CachePath); err == nil {
return image, nil
}
if len(GlobalSettings.Nodes) > 0 && !ctx.OnlyCache {
debug("Checking other nodes")
if image, err = checkNodes(ctx); err == nil {
return image, nil
}
}
debug("Image not found")
return image, err
}
func checkNodes(ctx *Context) ([]byte, error) {
var image []byte
var err error
context := *ctx
for _, node := range GlobalSettings.Nodes {
context.OrigImage = fmt.Sprintf("%s://%s%s", GlobalSettings.Scheme, node, context.RequestURI)
if image, err = getRemoteImage(&context, true); err == nil {
debug("Found at node: %s", node)
return image, nil
}
}
return image, errors.New("No one node has the image")
}
// getOrCreateImage check cache path for requested image
// if image doesn't exist - creates it
func getOrCreateImage(ctx *Context) []byte {
var image []byte
var err error
if !ctx.NoCache {
if image, err = checkCache(ctx); err == nil {
return image
}
}
switch ctx.Storage {
case "loc":
image, err = getLocalImage(ctx, false)
if err != nil {
warning("Can't get orig local file - %s, reason - %s", ctx.OrigImage, err)
if Default404 != "" {
image, err = getLocalImage(ctx, true)
if err != nil {
warning("Default 404 image was set but not found", Default404)
return image
}
}
return image
}
case "rem":
image, err = getRemoteImage(ctx, false)
if err != nil {
warning("Can't get orig remote file, reason - %s", err)
if Default404 != "" {
image, err = getLocalImage(ctx, true)
if err != nil {
warning("Default 404 image was set but not found", Default404)
return image
}
}
return image
}
case "az":
if !ClientConfirmed {
return image
}
image, err = getAzureImage(ctx)
if err != nil {
warning("Can't get orig Azure file - %s, reason - %s", ctx.OrigImage, err)
if Default404 != "" {
image, err = getLocalImage(ctx, true)
if err != nil {
warning("Default 404 image was set but not found", Default404)
return image
}
}
return image
}
case "s3":
if !ClientConfirmed {
return image
}
image, err = getS3Image(ctx)
if err != nil {
warning("Can't get orig AWS S3 file - %s, reason - %s", ctx.OrigImage, err)
if Default404 != "" {
image, err = getLocalImage(ctx, true)
if err != nil {
warning("Default 404 image was set but not found", Default404)
return image
}
}
return image
}
}
if ctx.IsOriginal {
debug("Returning original image as requested...")
return image
}
debug("Processing image...")
Transform(&image, ctx)
debug("Set to cache, key: %s", ctx.CachePath)
err = Cache.Set(ctx.CachePath, image)
if err != nil {
warning("Can't set cache, reason - %s", err)
}
return image
}
func stringExists(str string, list []string) bool {
for _, el := range list {
if el == str {
return true
}
}
return false
}
func parseVars(req *http.Request) map[string]string {
params := map[string]string{"query": req.URL.RawQuery}
match := GlobalSettings.UrlExp.FindStringSubmatch(req.URL.Path)
for i, name := range GlobalSettings.UrlExp.SubexpNames() {
params[name] = match[i]
}
return params
}
func FetchImage(rw http.ResponseWriter, req *http.Request) {
ChanPool <- 1
var resultImage []byte
var err error
context := Context{}
context.Fill(req)
if context.OnlyCache {
resultImage, err = checkCache(&context)
if err != nil {
http.NotFound(rw, req)
} else {
rw.Write(resultImage)
}
} else {
resultImage = getOrCreateImage(&context)
contentLength := len(resultImage)
if contentLength == 0 {
debug("Content length 0")
http.NotFound(rw, req)
}
rw.Header().Set("Content-Length", strconv.Itoa(contentLength))
rw.Write(resultImage)
}
<-ChanPool
}
func debug(s string, args ...interface{}) {
if !DEBUG {
return
}
log.Printf(s+"\n", args...)
}
func warning(s string, args ...interface{}) {
if !WARNING {
return
}
log.Printf(s+"\n", args...)
}